How to use SFTP in Python

Published on Aug. 22, 2023, 12:15 p.m.

To use SFTP in Python, you can use the pysftp library or the paramiko library. Here’s an example of how to use pysftp to connect to an SFTP server, list its contents, and download a file:

import pysftp

# Set up the connection parameters
host = 'example.com'
username = 'myusername'
password = 'mypassword'
remote_path = '/remote/path/'

# Connect to the SFTP server and list its contents
with pysftp.Connection(host, username=username, password=password) as sftp:
    with sftp.cd(remote_path):
        directory_structure = sftp.listdir_attr()
        for attr in directory_structure:
            print(attr.filename)

    # Download a file from the SFTP server
    sftp.get('filename.txt')

Alternatively, you can use paramiko to accomplish the same tasks:

import paramiko

# Set up the connection parameters
host = 'example.com'
username = 'myusername'
password = 'mypassword'
remote_path = '/remote/path/'

# Connect to the SFTP server
with paramiko.Transport((host, 22)) as transport:
    transport.connect(username=username, password=password)
    sftp = paramiko.SFTPClient.from_transport(transport)

    # List the contents of the remote directory
    directory_structure = sftp.listdir_attr(remote_path)
    for attr in directory_structure:
        print(attr.filename)

    # Download a file from the SFTP server
    sftp.get(remote_path + 'filename.txt', 'local_filename.txt')

Tags: