How to Transfer Files over SFTP in Python

09/14/2021

Contents

In this article, you will learn how to transfer files over SFTP in Python.

Transfer files over SFTP

To transfer files over SFTP in Python, you can use the paramiko module, which provides an implementation of the SSHv2 protocol. Here’s an example code snippet:

import paramiko

# create an SSH client object
ssh = paramiko.SSHClient()

# automatically add the host key
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

# connect to the SFTP server
ssh.connect('hostname', username='username', password='password')

# create an SFTP client object
sftp = ssh.open_sftp()

# transfer the file from the local machine to the remote server
sftp.put('local_file_path', 'remote_file_path')

# close the SFTP client and the SSH connection
sftp.close()
ssh.close()

In this example, you’ll need to replace hostname, username, and password with the appropriate values for your SFTP server. You’ll also need to replace local_file_path with the path to the file you want to transfer from the local machine and remote_file_path with the path to the file you want to transfer to on the remote server.

You can also transfer files in the other direction by using the get() method instead of put().