Implementing a SFTP Client Using Python and Paramiko

By | April 28, 2016

This post shows how to use the Python library Paramiko to implement a SFTP client that can be used to programatically send and receive files over SFTP. As when using Paramiko for SSH communication, authentication is performed using either username and password or username and a private key.


The preparations are identical to those described in my previous post on SSH communication using Paramiko, please refer to that post for details.


I have written two functions that both create a SFTPClient object connected to a computer on which remote file operations can be performed. The two functions differ slightly in that the first one uses a Paramiko Transport object to establish a connection to the (remote) computer and then create the SFTClient object using the Transport object. The second function, on the other hand, creates a Paramiko SSHClient object which is then used to open a SFTP connection and obtain a SFTPClient object.

The code above establishes a SFTP connection to the same computer on which it executes (localhost) on port 22 using the user-name “ivan” and the password “secretpassword” and then retrieves the directory listing of the current directory, downloads a file and uploads a file.
If you want to use a private key for authorization, set the variable keyfile_path to contain the absolute or relative path to a file containing the private key. Don’t forget to change the keyfile type from ‘DSA’ to ‘RSA’ if your private key is a RSA key.

If you now run the program, a directory listing should be printed to the console, a new file named ‘downloaded_file’ should appear and, in the remote directory, a file named ‘remote_testfile.txt’ should appear.

Happy coding!

Leave a Reply

Your email address will not be published. Required fields are marked *