How to use SFTP in Python?

python programs

SFTP stands for Secure File Transfer Protocol. It’s a way using which you can easily and securely transfer files over any reliable data stream.

Imagine you have a file on your computer that you want to send to someone else. Instead of using regular email or other unsecure methods, you can use SFTP to make sure the file is protected during the transfer.

In Python, you can use paramiko.SFTPClient to easily upload files to a server through SFTP protocol.

Use paramiko.SFTPClient for SFTP

#Create a Transport object
host = "temp.wftpserver.com"
port = 2222
transport = paramiko.Transport((host, port))


#Connect to a Transport server
password = "temp-user"
username = "temp-user"
transport.connect(username = username, password = password)


#Create an SFTP client
sftp = paramiko.SFTPClient.from_transport(transport)


#Upload file to server
path = "/upload/source.py"
localpath = "source.py"
sftp.put(localpath, path)

#close the connections
sftp.close()
transport.close()

Here, we called paramiko.Transport((host, port)) to create a new Transport client for the endpoint host:port.

After doing so, we call paramiko.Transport.connect(username = username, password = password), with paramiko.Transport as the previously created Transport object to connect the client to the endpoint with a username and password.

Then, we use paramiko.SFTPClient.from_transport(transport) to create a SFTPClient from the transport client used in the previous steps.

To upload the local file at localpath to the target path i.e. targetpath, we call paramiko.SFTPClient.put(localpath, targetpath) from the same SFTPClient.

At the end, we call paramiko.SFTPClient.close() and paramiko.Transport.close() methods to close the SFTPClient and Transport connections.

So, this is the way following which you can upload a file to target host server through SFTP in Python.

Leave a Reply

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