How to Use Pysftp Module for an Sftp Connection

by Ather Rashid

SFTP (Secure File Transfer Protocol) is used for securely exchanging files or directories over the internet. Now as far as pysftp is considered, it is just a simple interface to the sftp. Based on this module we can have different levels of abstractions that are required for our sftp connection.

Pysftp utilizes paramiko (Python implementation of the SSHv2 protocol, providing both client and server functionality) and pycrypto (collection of both secure hash functions such as SHA256 and RIPEMD160, and various encryption algorithms such as AES, DES, RSA, ElGamal, etc.) thereby providing a simple interface to sftp. Apart from these things it provides a number of features like handling RSA and DSS private key files automatically, supporting encrypted private key files or support for logging.

In order to start using pysftp we need to first install all our requirements which includes the pysftp module. We will now begin using this module to create a simple sftp connection to our server as given below.

import pysftp

srv = pysftp.Connection(host="YOUR_SERVER_IP", username="SERVER_USERNAME", password="SERVER_PASSWORD")

This would create an sftp with server having corresponding username and password. Once the connection is established with our server, we can accordingly do a number of things depending on our needs such as getting a particular file from a server or simply putting a file on the server.

So first of all, lets see how we can check the directories present on that particular server.

import pysftp

srv = pysftp.Connection(host="YOUR_SERVER_IP", username="SERVER_USERNAME", password="SERVER_PASSWORD")

filename = 'test.txt'
directories_data = srv.listdir()
if filename in directories_data:
srv.get(filename)

Now in the above example we first check the contents by using method listdir and after that check for a particular file. If the file is present then it would get it to our local machine. Similarly, we can use pysftp to put certain files from our local machine to a remote server.

Going forward we can even use this module for every operation that we do on our local machine right from creating, removing files, or directories to change directory permissions or assign certain attributes to directory permission. Even if this is not enough, we can change the directory’s structure on a remote machine.

At your convenience, while working on sftp operations, give this module a try and start playing with it.

Leave a Reply

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

Tools & Practices

Tools and Technologies we use at Applied

Contact us now

Popular Posts