0

I saw an example how to upload a file to SFTP

import pysftp

srv = pysftp.Connection(host="www.destination.com", username="root",
password="password",log="./temp/pysftp.log")

with srv.cd('public'): #chdir to public
    srv.put('C:\Users\XXX\Dropbox\test.txt') #upload file to nodejs/

# Closes the connection
srv.close()

But how can I upload and zip it at the same time? To be clear I don't want to zip it and then upload it, I want to make it at the same time using zipped stream.

Ilya Gazman
  • 31,250
  • 24
  • 137
  • 216
  • You can use the `putfo()` method instead of `put()` and pass in a ZIP file instance (`zipfile.ZipFile`) that is backed by a `io.StringIO` object. – kindall Dec 05 '17 at 17:00
  • Can you provide a full example please where you take my sample.txt file and upload it to sample.zip file to SFTP – Ilya Gazman Dec 05 '17 at 17:07

1 Answers1

1

To stream a file via pysftp do the following:

import pysftp
import io

with io.StringIO("hello world!\r\n") as stream:
    with pysftp.Connection("sftp.mywebsite.com", username="myuser", password="mypassword") as sftp:
        with sftp.cd("myhome/uploads"):
            sftp.putfo(stream, "hello.txt", confirm=False)

Setting confirm to False will tell pysftp NOT to verify the length of the file. If you need to verify the length of the file with file_size in pysftp then you will need to say len(secondstream.read()) and duplicate the stream since reading consumes the stream from memory meaning no data will be written.

GHETTO.CHiLD
  • 3,267
  • 1
  • 22
  • 34