Upload a file-like object with Paramiko?

Brendan Long picture Brendan Long · May 6, 2011 · Viewed 8.4k times · Source

I have a bunch of code that looks like this:

with tempfile.NamedTemporaryFile() as tmpfile:
    tmpfile.write(fileobj.read()) # fileobj is some file-like object
    tmpfile.flush()
    try:
        self.sftp.put(tmpfile.name, path)
    except IOError:
        # error handling removed for ease of reading
        pass

Is it possible to do an upload like this without having to write the file out somewhere?

Answer

user25148 picture user25148 · May 6, 2011

Update As of Paramiko 1.10, you can use putfo:

self.sftp.putfo(fileobj, path)

Instead of using paramiko.SFTPClient.put, you can use paramiko.SFTPClient.open, which opens a file-like object. You can write to that. Something like this:

f = self.sftp.open(path, 'wb')
f.write(fileobj.read())
f.close()

Note that it may be worthwhile to feed paramiko data in 32 KiB chunks, since that's the largest chunk underlying SSH protocol can handle without breaking it into multiple packets.