scp模块用于paramiko
项目描述
The scp.py模块使用paramiko传输来通过scp1协议发送和接收文件。这是从openssh scp程序引用的协议,并且只与这个实现进行了测试。
示例
from paramiko import SSHClient
from scp import SCPClient
ssh = SSHClient()
ssh.load_system_host_keys()
ssh.connect('example.com')
# SCPCLient takes a paramiko transport as an argument
scp = 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 directory
scp.put('test', recursive=True, remote_path='/home/user/dump')
scp.close()
$ md5sum test.txt test2.txt
fc264c65fb17b7db5237cf7ce1780769 test.txt
fc264c65fb17b7db5237cf7ce1780769 test2.txt
使用‘with’关键字
from paramiko import SSHClient
from scp import SCPClient
with SSHClient() as ssh:
ssh.load_system_host_keys()
ssh.connect('example.com')
with SCPClient(ssh.get_transport()) as scp:
scp.put('test.txt', 'test2.txt')
scp.get('test2.txt')
$ md5sum test.txt test2.txt
fc264c65fb17b7db5237cf7ce1780769 test.txt
fc264c65fb17b7db5237cf7ce1780769 test2.txt
上传文件对象
可以使用putfo方法上传文件对象
import io
from paramiko import SSHClient
from scp import SCPClient
ssh = SSHClient()
ssh.load_system_host_keys()
ssh.connect('example.com')
# SCPCLient takes a paramiko transport as an argument
scp = SCPClient(ssh.get_transport())
# generate in-memory file-like object
fl = io.BytesIO()
fl.write(b'test')
fl.seek(0)
# upload it directly from memory
scp.putfo(fl, '/tmp/test.txt')
# close connection
scp.close()
# close file handler
fl.close()
跟踪文件上传/下载的进度
可以将一个progress函数作为回调传递给SCPClient,以处理当前SCP操作如何处理传输的进度。在下面的示例中,我们打印文件传输的完成百分比。
from paramiko import SSHClient
from scp import SCPClient
import sys
ssh = SSHClient()
ssh.load_system_host_keys()
ssh.connect('example.com')
# Define progress callback that prints the current percentage completed for the file
def progress(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 source
def progress4(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()
项目详情
下载文件
下载适合您平台的文件。如果您不确定选择哪个,请了解更多关于安装包的信息。
源代码分发
scp-0.15.0.tar.gz (13.9 kB 查看散列值)
构建分发
scp-0.15.0-py2.py3-none-any.whl (8.8 kB 查看散列值)