本文實例講述了Python實現(xiàn)的遠(yuǎn)程文件自動打包并下載功能。分享給大家供大家參考,具體如下:
一 點睛
在Linux系統(tǒng)集群運營當(dāng)中,時常需要批量遠(yuǎn)程執(zhí)行Linux命令,并且雙向同步文件的操作。
本示例通過使用spawn()方法執(zhí)行ssh、scp 命令的思路來實現(xiàn)。
二 代碼
import pexpectimport sysip="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 = fouttry: 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 = fouttry: 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.pytar -czf /data/test.tar.gz /data/test.txttar: Removing leading `/' from member names
四 日志輸出
[root@localhost pymaintain]# cat mylog.txtKernel /r on an /mroot@192.168.0.104's password: 123456Last login: Sun Feb 24 16:20:25 2019 from 192.168.0.120hello cakin24![root@slave2 ~]# tar -czf /data/test.tar.gz /data/test.txttar -czf /data/test.tar.gz /data/test.txttar: Removing leading `/' from member names[root@slave2 ~]# exitKernel /r on an /mroot@192.168.0.104's password: 123456test.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)典教程》
希望本文所述對大家Python程序設(shè)計有所幫助。
新聞熱點
疑難解答