本文實(shí)例講述了Python實(shí)現(xiàn)的遠(yuǎn)程文件自動(dòng)打包并下載功能。分享給大家供大家參考,具體如下:
一 點(diǎn)睛
在Linux系統(tǒng)集群運(yùn)營(yíng)當(dāng)中,時(shí)常需要批量遠(yuǎn)程執(zhí)行Linux命令,并且雙向同步文件的操作。
本示例通過(guò)使用spawn()方法執(zhí)行ssh、scp 命令的思路來(lái)實(shí)現(xiàn)。
二 代碼
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"
三 運(yùn)行
[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
更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python文件與目錄操作技巧匯總》、《Python Socket編程技巧總結(jié)》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》及《Python入門與進(jìn)階經(jīng)典教程》
希望本文所述對(duì)大家Python程序設(shè)計(jì)有所幫助。
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號(hào)聯(lián)系: 360901061
您的支持是博主寫作最大的動(dòng)力,如果您喜歡我的文章,感覺(jué)我的文章對(duì)您有幫助,請(qǐng)用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長(zhǎng)非常感激您!手機(jī)微信長(zhǎng)按不能支付解決辦法:請(qǐng)將微信支付二維碼保存到相冊(cè),切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對(duì)您有幫助就好】元
