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

How to: Transfer files over SFTP in Python

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.

8 thoughts on “How to: Transfer files over SFTP in Python”

  1. Медицинский центр предлагает профессиональные медицинские услуги для взрослых и детей.
    Наши специалисты обладают высокой квалификацией и применяют передовые методики.
    Мы обеспечиваем комфортные условия для прохождения обследований.
    Клиника предоставляет персонализированные медицинские решения для всех обратившихся.
    Приоритетом для нас является здоровью наших пациентов.
    Каждый посетитель может получить качественное лечение в удобное время.
    smartopya.com

  2. The site features a large selection of medical products for home delivery.
    Users can securely access treatments with just a few clicks.
    Our catalog includes popular drugs and more specific prescriptions.
    Everything is supplied through trusted pharmacies.
    https://community.alteryx.com/t5/user/viewprofilepage/user-id/575800
    We maintain discreet service, with encrypted transactions and prompt delivery.
    Whether you’re filling a prescription, you’ll find trusted options here.
    Explore our selection today and get convenient healthcare delivery.

Leave a Reply

Your email address will not be published. Required fields are marked *