SFTP server with Python and Paramiko in under a minute

by Ruslan Spivak on December 12, 2011

I needed a simple server that could be used as a stub for testing Python SFTP clients so I whipped out one over the weekend.
It’s a simple single-threaded server so it’s not for production use but give it a try anyways, you might find it useful too.

Installation:

$ [sudo] pip install sftpserver

Running the server:


    $ sftpserver
    Usage: sftpserver [options]
    -k/--keyfile should be specified

    Options:
      -h, --help            show this help message and exit
      --host=HOST           listen on HOST [default: localhost]
      -p PORT, --port=PORT  listen on PORT [default: 3373]
      -l LEVEL, --level=LEVEL
                            Debug level: WARNING, INFO, DEBUG [default: INFO]
      -k FILE, --keyfile=FILE
                            Path to private key, for example /tmp/test_rsa.key

    $ sftpserver -k /tmp/test_rsa.key -l DEBUG

Connecting with a Python client to our server:

>>> import paramiko
>>> pkey = paramiko.RSAKey.from_private_key_file('/tmp/test_rsa.key')
>>> transport = paramiko.Transport(('localhost', 3373))
>>> transport.connect(username='admin', password='admin', pkey=pkey)
>>> sftp = paramiko.SFTPClient.from_transport(transport)
>>> sftp.listdir('.')
['loop.py', 'stub_sftp.py']

The server code itself is pretty minimal, check it out on GitHub.

If you enjoyed this post why not subscribe via email or my RSS feed and get the latest updates immediately. You can also follow me on GitHub or Twitter.

{ 5 comments… read them below or add one }

Andrei Savu December 12, 2011 at 2:16 AM

Nice work! How about making it use PyFilesystem? It could be useful for testing to be able to use an in-memory filesystem.

[1] http://code.google.com/p/pyfilesystem/

Reply

Ruslan Spivak December 12, 2011 at 8:03 AM

Hi Andrei,

Thanks for pointing out PyFilesystem. I’ll look into it.

Reply

Will Mcgugan December 13, 2011 at 7:22 AM

The ‘fsserve’ command in PyFilesystem can serve a directory over sftp.

For example, to serve the current working directory:

$ sudo fsserve -t sftp

And this to get a directory listing:

$ fsls sftp://127.0.0.1

You might want to join the PyFilesystem mailing list!

Reply

Ruslan Spivak December 13, 2011 at 8:11 AM

I didn’t know that, really neat! Thanks for the information, Will.

Reply

horizon September 1, 2013 at 2:51 AM

why not use paramiko common class ,such as from sftp_server import SFTPServer

Reply

Speak your mind

Previous post:

Next post: