Easy SFTP uploading with paramiko
paramiko makes it so easy to use SFTP that it's hard to believe it's legal in this day and age. Command Line Warriors has a wonderful post showing how to use paramiko to do SFTP uploads/downloads.
In this post, I want to share a small helper module called sftp (zip file) (code in post below) that wraps paramiko.SFTPClient and makes uploading/downloading via SFTP even simpler.
First, some usage
Upload or download a file
# upload a file
server.upload("/local/path", "/remote/path")
# download a file
server.download("remote/path", "/local/path")
server.close()
with statement also supported:
server.upload("/local/path", "/remote/path")
Finally, a demo recipe for uploading all the png files from a specified local directory to a specified directory on the server:
from __future__ import with_statement
import sftp
import glob
from os import path
remote_dir = "/path/on/remote/server/"
with sftp.Server("user", "pass", "www.example.com") as server:
for image in glob.glob("/local/path/to/*.png"):
base = path.basename(image)
server.upload(image, path.join(remote_dir, base))
Now, here's the code for my sftp module:
class Server(object):
"""
Wraps paramiko for super-simple SFTP uploading and downloading.
"""
def __init__(self, username, password, host, port=22):
self.transport = paramiko.Transport((host, port))
self.transport.connect(username=username, password=password)
self.sftp = paramiko.SFTPClient.from_transport(self.transport)
def upload(self, local, remote):
self.sftp.put(local, remote)
def download(self, remote, local):
self.sftp.get(remote, local)
def close(self):
"""
Close the connection if it's active
"""
if self.transport.is_active():
self.sftp.close()
self.transport.close()
# with-statement support
def __enter__(self):
return self
def __exit__(self, type, value, tb):
self.close()

I’d modify the put/get code to have pipelining (in the new paramiko) as this will be extremely slow for large files. Looks very good though making the server class..
Hello! I have a question: It is too slow when I use your module as a sftp client to transfer large files(300MB or larger). I’ve googled a lot and don’t know why… Could you please help me?
@knktc: Have you tried Vasu’s suggestion?
Is that means I must modify the source code of paramiko? But… I can’t find which part should be modified…