How to Connect to an SFTP Server Using Python

SFTP (SSH File Transfer Protocol) is a secure file transfer protocol that operates over SSH. It’s a reliable way to upload, download, and manage files on a remote server. In this blog post, we’ll walk through how to connect to an SFTP server using Python, and explain the difference between authenticating with a password and an SSH key.

Prerequisites

  • Python 3.x installed
  • The paramiko library installed (pip install paramiko)
  • Access to an SFTP server (hostname, username, and either a password or private SSH key)

Installing Paramiko

Paramiko is a Python implementation of the SSHv2 protocol that allows you to programmatically connect and interact with SSH/SFTP servers.

pip install paramiko

1. Connecting Using a Password

This approach relies on basic credential-based authentication, where access to the server is granted by verifying a username and password combination. It's simple to set up but generally offers less security compared to key-based methods.

import paramiko
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(hostname='example.com', username='user', password='pass')
sftp = client.open_sftp()
print("Connected")
sftp.close()
client.close()

2. Connecting Using an SSH Key

Using an SSH key for authentication is generally considered more secure than traditional password-based methods. SSH key authentication uses a cryptographic key pair—comprising a private key (kept secure by the user) and a public key (shared with the server)—to establish trust and grant access. This method is especially well-suited for automated systems, such as continuous integration/continuous deployment (CI/CD) pipelines.

import paramiko
hostname = 'sftp.example.com'
port = 22
username = 'your_username'
key_path = '/path/to/private_key.pem'
key = paramiko.RSAKey.from_private_key_file(key_path)
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
client.connect(hostname, port=port, username=username, pkey=key)
sftp = client.open_sftp()
print("Connection successful with SSH key!")
# List files in remote directory
for filename in sftp.listdir('.'):
print(filename)
sftp.close()
finally:
client.close()

Which Authentication Method Should You Use?

Password Authentication: Simple and easy for one-time manual use, but less secure and harder to manage at scale.

SSH Key Authentication: More secure and ideal for automation. Keys can be protected with passphrases and rotated without changing server settings.

Conclusion

Connecting to an SFTP server in Python is straightforward with the help of the paramiko library. Whether you choose password or key-based authentication depends on your use case, but in general, SSH keys are more secure and flexible. Always ensure your connections are secure and your credentials are stored safely.