日韩久久久精品,亚洲精品久久久久久久久久久,亚洲欧美一区二区三区国产精品 ,一区二区福利

Python實現的遠程文件自動打包并下載功能示例

系統 1907 0

本文實例講述了Python實現的遠程文件自動打包并下載功能。分享給大家供大家參考,具體如下:

一 點睛

在Linux系統集群運營當中,時常需要批量遠程執行Linux命令,并且雙向同步文件的操作。

本示例通過使用spawn()方法執行ssh、scp 命令的思路來實現。

二 代碼

            
import pexpect
import sys
ip="192.168.0.104"
user="root"
passwd="123456"
target_file="/data/test.txt"
child = pexpect.spawn('/usr/bin/ssh', [user+'@'+ip])
fout = file('mylog.txt','w')
child.logfile = fout
try:
  child.expect('password: ')
  child.sendline(passwd)
  child.expect('#')
  child.sendline('tar -czf /data/test.tar.gz '+target_file)
  child.expect('#')
  print child.before
  child.sendline('exit')
  fout.close()
except pexpect.EOF:
  print "expect EOF1"
except pexpect.TIMEOUT:
  print "expect TIMEOUT1"
child = pexpect.spawn('/usr/bin/scp', [user+'@'+ip+':/data/test.tar.gz','/home'])
fout = file('mylog.txt','a')
child.logfile = fout
try:
  child.expect('(?i)password')
  child.sendline(passwd)
  child.expect(pexpect.EOF)
except pexpect.EOF:
  print "expect EOF2"
except pexpect.TIMEOUT:
  print "expect TIMEOUT2"


          

三 運行

            
[root@localhost pymaintain]# python 5_3_3.py
tar -czf /data/test.tar.gz /data/test.txt
tar: Removing leading `/' from member names


          

四 日志輸出

            
[root@localhost pymaintain]# cat mylog.txt
Kernel \r on an \m
root@192.168.0.104's password: 123456
Last login: Sun Feb 24 16:20:25 2019 from 192.168.0.120
hello cakin24!
[root@slave2 ~]# tar -czf /data/test.tar.gz /data/test.txt
tar -czf /data/test.tar.gz /data/test.txt
tar: Removing leading `/' from member names
[root@slave2 ~]# exit
Kernel \r on an \m
root@192.168.0.104's password: 123456
test.tar.gz                  100% 115  40.3KB/s  00:00

          

更多關于Python相關內容感興趣的讀者可查看本站專題:《Python文件與目錄操作技巧匯總》、《Python Socket編程技巧總結》、《Python數據結構與算法教程》、《Python函數使用技巧總結》、《Python字符串操作技巧匯總》及《Python入門與進階經典教程》

希望本文所述對大家Python程序設計有所幫助。


更多文章、技術交流、商務合作、聯系博主

微信掃碼或搜索:z360901061

微信掃一掃加我為好友

QQ號聯系: 360901061

您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。

【本文對您有幫助就好】

您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描上面二維碼支持博主2元、5元、10元、自定義金額等您想捐的金額吧,站長會非常 感謝您的哦!??!

發表我的評論
最新評論 總共0條評論
主站蜘蛛池模板: 河北区| 四川省| 永丰县| 奉化市| 东海县| 霞浦县| 南京市| 辽宁省| 牟定县| 会昌县| 崇州市| 永善县| 于都县| 青河县| 忻城县| 三都| 梁河县| 华安县| 吴忠市| 佳木斯市| 沁源县| 兴业县| 绥江县| 盐池县| 苗栗县| 门源| 宁河县| 扎赉特旗| 木兰县| 白城市| 阿鲁科尔沁旗| 西林县| 龙口市| 明光市| 泗阳县| 白银市| 嵩明县| 松溪县| 平凉市| 通榆县| 罗田县|