Python SFTP: Use SFTP to transfer your memory stream to a remote folder. How to FTP storbinary

I am using paramiko in Python. I need an SFTP file for a remote Linux module (dev platform is windows). Here are the codes (working)

import paramiko
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(HOST, username=USERNAME, password=PASSWORD)
stdin, stdout, stderr = client.exec_command("cd %s; pwd" % PATH)
data = stdout.readlines()
print "Current folder:"
for line in data:
    print (line.rstrip())
sftp = client.open_sftp()
sftp.put(local_path, PATH + '/' + FILE_NAME, confirm = True)

sftp.close() 
client.close()

      

This works great. But to call put (), I need to save the file to local_path, which takes a long time.

I am wondering if there is a way to do sftp on a memory stream exactly like ftp. For FTP, it's faster on a memory stream (works):

import ftplib
ftp_conn = ftplib.FTP(HOST, USERNAME, PASSWORD)
ftp_conn.cwd(FILE_PATH)
ftp_conn.storbinary('STOR '+posixpath.basename(FILE_PATH), buffer, blocksize=1024)
ftp_conn.close()

      

Many thanks!

+3


source to share


1 answer


You should do something like this:



import shutil

with sftp.open("/path/to/remote/file", mode="w") as remote_file:
    shutil.copyfileobj(file_string_io, remote_file)

      

0


source







All Articles