python rsync 数据同步脚本
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import pexpect
import time
import traceback
def doRsync(user,passwd,ip,srcDir,dstDir,timeout=3600):
cmd = "rsync -azPq --delete {srcDir} {rUser}@{rHost}:{dstDir}".fORMat(rUser = user,rHost=ip,srcDir=srcDir,dstDir=dstDir)
try:
ssh = pexpect.spawn(cmd,timeout=timeout)
i = ssh.expect(['passWord:', 'continue connecting (yes/no)?'], timeout=5)
if i == 0 :
ssh.sendline(passwd)
elif i == 1:
ssh.sendline('yes')
ssh.expect('password: ')
ssh.sendline(passwd)
ssh.expect(['#',pexpect.TIMEOUT,pexpect.EOF])
ssh.close()
except :
print traceback.format_exc()
pass
if __name__ == '__main__':
doRsync("tpuser","12345","10.1.1.230","/data/local/backupdir/","/data/local/backupdir/")
参考链接:
https://www.cnblogs.com/MikeZhang/p/rsyncExample_20160818.html
Http://blog.csdn.net/csapr1987/article/details/7692455
疑问1:
pexpect.spawn的对象child调用read()时触发TIMEOUT异常 ssh远程操作
read() 需要程序回话结束并且返回EOF才能读取剩下的所有内容
详细可见 pexpect模块参数解释
参考链接:https://blog.51cto.com/749807/1566258
pexpect模块参数解释
https://www.jianshu.com/p/cfd163200d12
相关文章