用rsync ssh配合pexpect免输入密码同步文件

需求:写一个脚本,把本地的文件通过rsync传到其他服务器上去,其中 1.本地目录 2.远端IP地址 3.远端目录 可以让用户手动输入,并且对执行结果记日志。

脚本如下: multi_rsync_v2.py

#!/usr/bin/env python
#coding: utf-8

import os
import time
import traceback
import pexpect

#按照这个格式填写目的IP和密码
SERVERS = {
    "ip":"password",
}

source_path = raw_input("请输入本地设备path: ")
source_path = source_path.strip()

print "您输入的目的IP需要在 " + "   ".join(SERVERS.keys()) + " 中..."
destination_ip = raw_input("请输入目的设备ip: ")
destination_ip = destination_ip.strip()

destination_path = raw_input("请输入目的设备path: ")
destination_path = destination_path.strip()

rsync_cmd = "/usr/bin/rsync -avz %s root@%s:%s" % (source_path,destination_ip,destination_path)

print "*" * 18
print "您输入的目的设备ip和path是: %s %s" % (destination_ip,destination_path)
print "您需要执行的rsync命令是: %s" % rsync_cmd

is_right = raw_input("以上信息是否正确?请输入yes/no进行确定: ")
is_right = is_right.strip()

def write_log(m):
        today = time.strftime('%Y%m%d',time.localtime(time.time()))
        rsync_log = "%s_rsync.log" % today

        with open(rsync_log,'a') as fh:
            fh.write('%s\n' % m)

def rsync(cmd):
    t = time.strftime('%Y:%m:%d_%H:%M:%S',time.localtime(time.time()))
    try:
        child = pexpect.spawn(cmd)
        index = child.expect(['password:','continue connecting (yes/no)?',pexpect.EOF, pexpect.TIMEOUT])
        if index == 0:
            print rsync_cmd
            try:
                child.sendline(SERVERS[destination_ip])
                child.expect(pexpect.EOF)
                m = "".join([t," ",rsync_cmd," ","OK"])
                write_log(m)
                print child.before
            except Exception,e:
                m = "".join([t," ",rsync_cmd," ","ERROR"])
                write_log(m)
                print str(e)
        elif index == 1:
            print rsync_cmd
            try:
                child.sendline('yes')
                child.expect(['password:'])
                child.sendline(SERVERS[destination_ip])
                child.expect(pexpect.EOF)
                m = "".join([t," ",rsync_cmd," ","OK"])
                write_log(m)
                print child.before
            except Exception,e:
                m = "".join([t," ",rsync_cmd," ","ERROR"])
                write_log(m)
                print str(e)
        elif index == 2:
            m = "".join([t," ",rsync_cmd," ","ERROR"])
            write_log(m)
            print "子程序异常,退出!"
        elif index == 3:
            m = "".join([t," ",rsync_cmd," ","TIMEOUT"])
            write_log(m)
            print "连接超时"
    except:
        traceback.print_exc()

if __name__ == '__main__':
    if is_right == "yes":
        print "输入正确执行中..."
        rsync(rsync_cmd)
    else:
        print "您确定输入有误,退出程序."
        os._exit(1)