With the purpose of secure file and data transfer, SFTP has been a top choice for many users. While it is an efficient and user friendly protocol, engaging with an SFTP server from a programming language such as Python may take a tad more deciphering. With the guidance of the following post, we hope you will come out the other side feeling familiar and ready to utilize and connect to SFTP from Python.


Prior to jumping in, some setup is required. We’ll use the ‘pysftp’ package to connect and pass commands to the SFTP server. When you are ready to install it, manually run:

pip install pysftp

Or create a requirements.txt file and declare your dependencies within. Then, save the following as requirements.txt:


Then run:

pip install -r requirements.txt

Connecting to SFTP

In this post, we’ll be using an environment variable named SFTPTOGO_URL that contains all the information required to connect to an SFTP server using a URI format: sftp://user:password@host. The variable is parsed to extract the URI parts using `urlparse`, and the remote server’s host key is verified by default using ~/.ssh/known_hosts.

Once the connection is established, the SFTP client object will be assigned to the variable: connection.

Listing Files

Now that the connection is all set up, we can use it to list files on the remote SFTP server. This is achieved by calling the connection object’s listdir function or the listdir_attr function. Either one of these functions can take a remote path argument or, if omitted, will list the files and directories in the current remote directory. The listdir function returns a list of filenames (as string), while the listdir_attr function returns a list of SFTPAttributes objects containing the file size, creation, modification timestamps and permissions, in addition to the file name. In our example, our wrapper function returns a generator, allowing the function caller to iterate over the returned files.

Upload File

The next step is to upload a file. Use the connection object’s put function and pass the path to the local file and the remote path, which is also where the file should end up by the end of the upload. The function call would look like: connection.put("./local.txt", "./remote.txt")

Download File

The last job left for us to complete is downloading our files. Use the connection object’s get function, and pass the path to the remote file and the local path, where you would store the downloaded file. You would call the function like so: connection.get("./remote.txt", "./download.txt")

The Whole Thing

So we’ve made it to the finish line! If you would like to run the entire program from start to finish, copy the following code and save it as main.py:

Finally, run it using the command:

python main.py

Congratulations on connecting to SFTP using Python!