Python学习——实现secure copy功能
Posted Mr_DaLiN
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python学习——实现secure copy功能相关的知识,希望对你有一定的参考价值。
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, "%[email protected]%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("%[email protected]%s:%s" % (user,server,path),local_file,passed,log_file): raise Exception("Wrong password to server!")
以上是关于Python学习——实现secure copy功能的主要内容,如果未能解决你的问题,请参考以下文章