Retrieve a file from a server via SFTP – Python
Today in this article, we will see how to perform Python – Download, Upload files from a server via SFTP. We will retrieve a file from a server via SFTP and upload the file to a remote server using a package library called Paramiko.
Today in this article, we will cover below aspects,
Paramiko is a Python implementation of the SSHv2 protocol which provides client and server functionality.
It provides the basis for SSH library Fabric and lets you run remote shell commands or transfer files. One can use python ftp to download files to a directory including large files of any size.
Installing the Python Paramiko package
Let’s install the ‘ Paramiko’ package to connect and pass commands to the SFTP server.
pip install Paramiko
Or create a requirements.txt file and declare your dependencies.
Paramiko >= 2.11.0
pip install -r requirements.txt
SSH Client using Pramiko
We can use the Secure Shell SSHClient() method of the Paramiko package. SSH clients can be used to communicate with an SFTP server for the transfer of files.
So, we import our installed package Paramiko and create the SSH client in the following manner.
Let’s add the required import statement in the python file
import paramiko
SFTP Secured Connection
Let’s define the connection and startup class below,
class SFTPClient:
_connection = None
def __init__(self, host, port, username, password):
self.host = host
self.port = port
self.username = username
self.password = password
self.OpenConnection(self.host, self.port,
self.username, self.password)
@classmethod
def OpenConnection(cls, host, port, username, password):
transport = Transport(sock=(host, port))
transport.connect(username=username, password=password)
cls._connection = SFTPClient.from_transport(transport)
Paramiko – SFTP Upload file
Let’s define the upload file method,
def upload(self, local_path, remote_path):
self._connection.put(localpath=local_path,
remotepath=remote_path,
callback=self.uploading_info,
confirm=True)
Paramiko – SFTP Download file
Let’s define the download file method,
def download(self, remote_path, local_path):
self._connection.get(remote_path, local_path,
callback=None)
The close connection method is defined below,
def close(self):
self._connection.close()
That’s all now you can use SFTPCLient class defined above to Upload or Download files easily as below,
Upload files,
client = SFTPClient(host, port,
username, password)
client.upload(upload_local_path,
upload_remote_path)
client.close()
Download files,
client = SFTPClient(host, port,
username, password)
client.download(download_remote_path,
download_local_path)
client.close()
Do you have any comments or ideas or any better suggestions to share?
Please sound off your comments below.
Happy Coding !!
Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.