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()

欢迎加入QQ群-->: 979659372 Python中文网_新手群

推荐PyPI第三方库


热门话题
Java中ArrayList的超简单问题   Java 8在一段时间后过期   java如何创建具有用户定义维度的矩阵,并使用从上到下、从左到右的递增值填充它?   java从JDBC重启mysql   带有sqlite的java LiveData未更新UI   带有JDialog的java小程序在Mac OSX中未正确隐藏   java ActionListener无法从公共类引用数组?   java Apache Digester:NoSuchMethodException:没有这样的可访问方法   安卓中数据库中的java数据没有以正确的格式检索   java快速排序实现:使用random pivot时几乎排序   安卓 Java:高效的ArrayList过滤?   java如何在单独的文件中制作GUI程序   jasper报告如何从JSP或Java代码在JasperReport中传递参数值?