Python - SFTP


SFTP is also known as the SSH File Transfer Protocol. It is a network protocol that provides file access, file transfer, and file management over any reliable data stream. The program is run over a secure channel, such as SSH, that the server has already authenticated the client, and that the identity of the client user is available to the protocol.

The pysftp module is a simple interface to SFTP. The module offers high level abstractions and task based routines to handle the SFTP needs. So we install the module into our python environment with the below command.

pip install pysftp


In the below example we login to a remote server using sftp and then get and put some file in that directory.

import pysftp

with pysftp.Connection('hostname', username='me', password='secret') as sftp:

    with'/allcode'):           # temporarily chdir to allcode
        sftp.put('/pycode/filename')  	# upload file to allcode/pycode on remote
        sftp.get('remote_file')         # get a remote file

When we run the above code we are able to see the list of files present in the allcode directory and also put and get some file in that directory.