Skip to content
Home ยป How to: Transfer files over SFTP in Python

How to: Transfer files over SFTP in Python

  • by
  • 2 min read

This article covers the transfer of files over SFTP (or Secure/SSH File Transfer Protocol). While there are quite some options to choose from, the Python package Paramiko is used to achieve it.

Paramiko is a pure-python implementation of the SSH2 protocol. Although Paramiko is the foundation for some other packages (like Fabric), it provides a lot of granularity regarding options and parameters, which might come in handy in an enterprise context.

First, we’ll load the Paramiko package, and set the local file path (from which we want to copy) and the remote file path (destination).

import paramiko

local_file_path = '<your_local_file_path>'
remote_file_path = '<your_remote_file_path>'

Next, we’ll open an SSH client. To prevent you running into the following error, make sure to use Paramiko’s set_missing_host_key_policy method and pass it AutoAddPolicy, which will add the hostname & key to the HostKeys object (so you don’t have to).

SSHException: Server ‘<YOUR_SERVER>’ not found in known_hosts

ssh_client = paramiko.SSHClient()
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

Next, we establish an SSH connection. In my situation, I needed an OpenSSH certificate which I provided by specifying the path in the key_filename parameter. You probably need other parameters. Check them out on this documentation page.

ssh_client.connect( \
                   hostname = '<your_hostname>', \
                   username = 'busde', 
                   key_filename = ssh_key_path
                  )

Using this SSH connection, we’ll establish an SFTP connection through the open_sftp method of our SSH connection. Finally, we’ll use the put method of our SFTP to transfer the file.

ftp_client = ssh_client.open_sftp()
ftp_client.put(local_file_path, remote_file_path)

Full code

Find the full code below.

import paramiko

local_file_path = '<your_local_file_path>'
remote_file_path = '<your_remote_file_path>'

ssh_client = paramiko.SSHClient()
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

ssh_client.connect( \
                   hostname = '<your_hostname>', \
                   username = 'busde', 
                   key_filename = ssh_key_path
                  )

ftp_client = ssh_client.open_sftp()
ftp_client.put(local_file_path, remote_file_path)

ftp_client.close()
ssh_client.close()

Say thanks, ask questions or give feedback

Technologies get updated, syntax changes and honestly… I make mistakes too. If something is incorrect, incomplete or doesn’t work, let me know in the comments below and help thousands of visitors.

Leave a Reply

Your email address will not be published.