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

server = sftp.Server("user", "pass", "example.com")
# upload a file
server.upload("/local/path", "/remote/path")
# download a file
server.download("remote/path", "/local/path")
server.close()

with statement also supported:

with sftp.Server("user", "pass", "example.com") as server:
    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:

# needed for python 2.5
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:

import paramiko

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()

4 comments to Easy SFTP uploading with paramiko

Leave a Reply

 

 

 

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>