Guide

How to connect to SFTP using Python

A practical guide to SFTP in Python with Paramiko, uploading, downloading, and listing files, verifying host keys, and using SSH keys, with copy-paste examples.

The standard way to do SFTP in Python is Paramiko, a pure-Python SSH/SFTP library. (You may also see pysftp, a thin wrapper around Paramiko, but it’s largely unmaintained, so prefer Paramiko directly.) Here’s how to connect, transfer, and do it safely.

Install

pip install paramiko

Connect and transfer

import paramiko

ssh = paramiko.SSHClient()
# Load known_hosts so the server's identity is verified.
ssh.load_system_host_keys()
ssh.set_missing_host_key_policy(paramiko.RejectPolicy())

ssh.connect(
    hostname="sftp.example.com",
    port=22,
    username="alice",
    key_filename="/home/alice/.ssh/id_ed25519",   # or password="..."
)

sftp = ssh.open_sftp()

# Upload
sftp.put("report.csv", "/incoming/report.csv")

# Download
sftp.get("/incoming/processed.csv", "processed.csv")

# List a directory
for entry in sftp.listdir("/incoming"):
    print(entry)

sftp.close()
ssh.close()

Verify the host key (don’t skip this)

You’ll see tutorials use AutoAddPolicy(), which silently trusts any server, defeating the point of SSH. Use RejectPolicy() (above) with a populated known_hosts, or pin the key explicitly:

host_key = paramiko.Ed25519Key(data=base64.b64decode("AAAAC3Nza..."))
ssh.get_host_keys().add("sftp.example.com", "ssh-ed25519", host_key)

Your SFTP provider publishes the host-key fingerprint; compare it on first use.

A reusable upload function

import paramiko
from pathlib import Path

def upload(local: str, remote: str, *, host: str, user: str, key: str):
    ssh = paramiko.SSHClient()
    ssh.load_system_host_keys()
    ssh.set_missing_host_key_policy(paramiko.RejectPolicy())
    ssh.connect(host, username=user, key_filename=key)
    try:
        sftp = ssh.open_sftp()
        sftp.put(local, remote)
    finally:
        ssh.close()
    return Path(remote).name

Where the files go

If your SFTP endpoint is a bring-your-own-bucket gateway, each put streams straight into your own S3, Azure, or GCS bucket. Your Python code talks plain SFTP; the gateway handles the object-storage translation, and the file ends up in your cloud account. See SFTP to S3.

Tips

  • Use key auth (key_filename) for automation; keep passwords out of code and config.
  • Reuse one connection for many files rather than reconnecting per file.
  • Handle large files with sftp.put’s callback argument if you want progress reporting.

To run this on a schedule, see automate SFTP uploads with cron.

Try it on your own bucket

Connect a bucket you already own, Amazon S3, Azure Blob, Google Cloud Storage, or an S3-compatible store, and hand out a clean SFTP endpoint in minutes. Your files stay in your cloud.

Start free

← All guides