Learn how to establish a SFTP connection with Python using the awesome PySftp library.

How to access a SFTP server using PySftp in Python

Handling things via SFTP with your own scripts can always be helpful, if you are working with Python, PySftp is the library that you need to work with this technology without having headaches as it's pretty easy to use. pysftp is a wrapper around Paramiko with a more Python-ish interface. The Paramiko library is a great python library and it is the backbone of pysftp. The methods pysftp has created are abstractions that serve a programmer’s productivity by encapsulating many of the higher function use cases of interacting with SFTP. Instead of writing your own code to walk directories and call get and put, dealing with not only paramiko but Python’s own os and stat modules and writing tests (many code snippets on the net are incomplete and don’t account for edge cases) pysftp supplies a complete library for dealing with all three. Leaving you to focus on your primary task.

1. Install PySftp

pysftp interface does not expose all of the features of Paramiko but abstracts a lot of features in single methods. On the other hand, pysftp implements more high-level features on top of Paramiko, notably recursive file transfers.

To install pysftp on your environment with Pip, run the following command:

python -m pip install pysftp

For more information about PySftp don't forget to visit the official documentation website here or the pyp repository here.

2. Usage

The usage of this library and multiple tasks that you need to accomplish with this library will be shown basically with a lot of examples:

List files from a directory

You can list the content of a directory using the following snippet. After opening a connection, you need to switch from directory using either the cwd or chdir method and providing the remote directory as first argument:

import pysftp

myHostname = "yourserverdomainorip.com"
myUsername = "root"
myPassword = "12345"

with pysftp.Connection(host=myHostname, username=myUsername, password=myPassword) as sftp:
    print "Connection succesfully stablished ... "

    # Switch to a remote directory
    sftp.cwd('/var/www/vhosts/')

    # Obtain structure of the remote directory '/var/www/vhosts'
    directory_structure = sftp.listdir_attr()

    # Print data
    for attr in directory_structure:
        print attr.filename, attr
    
# connection closed automatically at the end of the with-block

This will print a row in the console with the SFTPAttributes object of every file/directory in the remote directory.  The list is in arbitrary order. It does not include the special entries ‘.’ and ‘..’. The returned SFTPAttributes objects will each have an additional field: longname, which may contain a formatted string of the file’s attributes, in unix format. The content of this string will depend on the SFTP server:

.skel drwxr-xr-x   1 0        0            4096 10 Jul 17:39 .skel
bestfreehtmlcsstemplates.com drwx--x---   1 10002    1002         4096 22 Jul 15:51 bestfreehtmlcsstemplates.com
chroot drwxr-x---   1 0        0            4096 10 Jul 17:39 chroot
default drwxr-xr-x   1 0        0            4096 10 Jul 17:36 default
eagle148.startdedicated.com drwx--x---   1 10000    1002         4096 25 Jul 17:53 eagle148.startdedicated.com
fs drwxr-xr-x   1 0        0            4096 10 Jul 18:03 fs
fs-passwd drwxr-x---   1 999      33           4096 10 Jul 18:03 fs-passwd
ourcodeworld.com drwx--x---   1 10001    1002         4096 10 Sep 15:30 ourcodeworld.com
system drwxr-xr-x   1 0        0            4096 19 Jul 10:26 system

Download remote file

In order to download a remote file, open a connection and from the sftp instance use the get method that expects the path of the remote file that will be downloaded and as second argument the local path where the file should be stored:

import pysftp

myHostname = "yourserverdomainorip.com"
myUsername = "root"
myPassword = "12345"

with pysftp.Connection(host=myHostname, username=myUsername, password=myPassword) as sftp:
    print "Connection succesfully stablished ... "

    # Define the file that you want to download from the remote directory
    remoteFilePath = '/var/integraweb-db-backups/TUTORIAL.txt'

    # Define the local path where the file will be saved
    # or absolute "C:\Users\sdkca\Desktop\TUTORIAL.txt"
    localFilePath = './TUTORIAL.txt'

    sftp.get(remoteFilePath, localFilePath)
 
# connection closed automatically at the end of the with-block

Upload file

In order to upload a file to your server via SFTP, just use the put method of the SFTP client. This method expects as first argument the relative or absolute local path of the file that you want to upload and as second argument the remote path where the file should be uploaded:

import pysftp

myHostname = "yourserverdomainorip.com"
myUsername = "root"
myPassword = "12345"

with pysftp.Connection(host=myHostname, username=myUsername, password=myPassword) as sftp:
    print "Connection succesfully stablished ... "

    # Define the file that you want to upload from your local directorty
    # or absolute "C:\Users\sdkca\Desktop\TUTORIAL2.txt"
    localFilePath = './TUTORIAL2.txt'

    # Define the remote path where the file will be uploaded
    remoteFilePath = '/var/integraweb-db-backups/TUTORIAL2.txt'

    sftp.put(localFilePath, remoteFilePath)
 
# connection closed automatically at the end of the with-block

Delete file

If you are willing to remove a file from your server, you can do it with the remove method that expects as the first argument the absolute path to the remote file:

import pysftp

myHostname = "yourserverdomainorip.com"
myUsername = "root"
myPassword = "12345"

with pysftp.Connection(host=myHostname, username=myUsername, password=myPassword) as sftp:
    print "Connection succesfully stablished ... "

    # Define the file that you want to upload from your local directorty
    sftp.remove('/var/custom-folder/TUTORIAL2.txt')
 
# connection closed automatically at the end of the with-block

Remember that PySftp has a wide range of methods that you can use to do multiple things, like handling permissions, etc. so don't forget to check out the official documentation website. If you want someone to provide you with Python help online, let Python assignment helper AssignmentCore assist you.

Happy coding ❤️!


Senior Software Engineer at Software Medico. Interested in programming since he was 14 years old, Carlos is a self-taught programmer and founder and author of most of the articles at Our Code World.

Sponsors