3

I am using paramiko in Python. I need SFTP a file to a remote linux box (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 is working fine. 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 with in memory stream just like ftp. For FTP, it's faster with in memory stream (working):

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!

Payson
  • 508
  • 4
  • 11
  • 22

2 Answers2

1

You should be able to 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)
buhtla
  • 2,819
  • 4
  • 25
  • 38
  • This works, but see [Writing to a file on SFTP server opened using pysftp “open” method is slow](https://stackoverflow.com/q/58111798/850848). If you have a file-like object, better (and easier) is to use `SFTPClient.putfo`, as the answer by @Vladimir shows. – Martin Prikryl Aug 11 '21 at 08:15
1

Now its possible to use file-like object: http://docs.paramiko.org/en/stable/api/sftp.html#paramiko.sftp_client.SFTPClient.putfo

Vladimir
  • 145
  • 2
  • 9