paramiko的scp模块
scp的Python项目详细描述
py模块使用paramiko传输通过 SCP1协议。这是openssh scp程序中引用的协议, 只在这个实现中测试过。
示例
fromparamikoimportSSHClientfromscpimportSCPClientssh=SSHClient()ssh.load_system_host_keys()ssh.connect('example.com')# SCPCLient takes a paramiko transport as an argumentscp=SCPClient(ssh.get_transport())scp.put('test.txt','test2.txt')scp.get('test2.txt')# Uploading the 'test' directory with its content in the# '/home/user/dump' remote directoryscp.put('test',recursive=True,remote_path='/home/user/dump')scp.close()
$ md5sum test.txt test2.txt fc264c65fb17b7db5237cf7ce1780769 test.txt fc264c65fb17b7db5237cf7ce1780769 test2.txt
使用“with”关键字
fromparamikoimportSSHClientfromscpimportSCPClientssh=SSHClient()ssh.load_system_host_keys()ssh.connect('example.com')withSCPClient(ssh.get_transport())asscp:scp.put('test.txt','test2.txt')scp.get('test2.txt')
$ md5sum test.txt test2.txt fc264c65fb17b7db5237cf7ce1780769 test.txt fc264c65fb17b7db5237cf7ce1780769 test2.txt
上载类似文件的对象
putfo方法可用于上载类似文件的对象:
importiofromparamikoimportSSHClientfromscpimportSCPClientssh=SSHClient()ssh.load_system_host_keys()ssh.connect('example.com')# SCPCLient takes a paramiko transport as an argumentscp=SCPClient(ssh.get_transport())# generate in-memory file-like objectfl=io.BytesIO()fl.write(b'test')fl.seek(0)# upload it directly from memoryscp.putfo(fl,'/tmp/test.txt')# close connectionscp.close()# close file handlerfl.close()
跟踪文件上载/下载的进度
可以将progress函数作为对scpclient的回调来处理 当前SCP操作如何处理传输进度在 下面的示例我们打印文件传输的完成百分比。
fromparamikoimportSSHClientfromscpimportSCPClientimportsysssh=SSHClient()ssh.load_system_host_keys()ssh.connect('example.com')# Define progress callback that prints the current percentage completed for the filedefprogress(filename,size,sent):sys.stdout.write("%s\'s progress: %.2f%%\r"%(filename,float(sent)/float(size)*100))# SCPCLient takes a paramiko transport and progress callback as its arguments.scp=SCPClient(ssh.get_transport(),progress=progress)# you can also use progress4, which adds a 4th parameter to track IP and port# useful with multiple threads to track sourcedefprogress4(filename,size,sent,peername):sys.stdout.write("(%s:%s) %s\'s progress: %.2f%%\r"%(peername[0],peername[1],filename,float(sent)/float(size)*100))scp=SCPClient(ssh.get_transport(),progress4=progress4)scp.put('test.txt','~/test.txt')# Should now be printing the current progress of your put function.scp.close()