import paramiko
class HostInfo:
def __init__(self, host, port, username, password, location):
self.host = host
self.port = port
self.username = username
self.password = password
self.location = location
def sftp_remote_to_remote(remote_from, remote_to):
sf_from = paramiko.Transport((remote_from.host, remote_from.port))
sf_from.connect(username=remote_from.username, password=remote_from.password)
sftp_from = paramiko.SFTPClient.from_transport(sf_from)
sf_to = paramiko.Transport((remote_to.host, remote_to.port))
sf_to.connect(username=remote_to.username, password=remote_to.password)
sftp_to = paramiko.SFTPClient.from_transport(sf_to)
with sftp_to.file(remote_to.location, 'wb') as fl:
fl.set_pipelined(True)
file_size = sftp_from.stat(remote_from.location).st_size
with sftp_from.open(remote_from.location, 'rb') as fr:
fr.prefetch(file_size)
return sftp_from._transfer_with_callback(
reader=fr, writer=fl, file_size=file_size, callback=None
)
if __name__ == '__main__':
remote_from = HostInfo('192.168.56.200', 22, 'root', 'r00tme', '/root/pkg/logstash-5.6.3.tar.gz')
remote_to = HostInfo('192.168.56.200', 22, 'root', 'r00tme', '/root/cp/logstash-5.6.3.tar.gz')
sftp_remote_to_remote(remote_from, remote_to)
上面的代码是通过paramiko将远端的一个文件通过本机传输到远端。