Linux的scp命令可以实现两个主机之间的文件拷贝功能。
用python实现scp功能。
def run_scp(from1, to, passwd, log_file): cmd = "scp %s %s" % (from1, to) p = pexpect.spawn(cmd) if log_file is None: log_file = sys.__stdout__ p.logfile = open_log_file(log_file) basename = os.path.basename(from1) index = p.expect(["[Pp]assword:","(yes/no)",basename,pexpect.EOF]) if index == 0: p.sendline(passwd) elif index == 1: p.sendline("yes") p.expect("[Pp]assword:") p.sendline(passwd) elif index == 2: pass else: raise Exception("Fail to scp") def scp_to_server(local_file, server_ip, server_file, user='root', passwd='xxx', log_file=None): if not os.path.exists(local_file): raise Exception("File %s don't exist." % local_file) if not run_scp(local_file, "%s@%s:%s" % (user,server_ip,server_file),passwd,log_file): raise Exception("Wrong password to server!") def scp_from_server(server_ip, server_file, local_file, user='root', passwd='xxx',log_file=None): if not run_scp("%s@%s:%s" % (user,server,path),local_file,passed,log_file): raise Exception("Wrong password to server!")