How to use Python to connect to sftp and download file

We can use pysftp to connect to python and get the files from an sftp server.

Before that, we need to get the sftp server’s key using following command.

$ ssh-keyscan example.com
# example.com SSH-2.0-OpenSSH_5.3
example.com ssh-rsa AAAAB3NzaC1yc2EAAAADAQAB...

When fetched the key, put it to file  C:/Users/username/.ssh/known_hosts
– You can also save the key in a folder and pass in using the cnopts variable shown below in the code

import pysftp
import io
import csv

myHostname = "HOST"
myUsername = "USERNAME"
myPassword = "PASSWORD"

cnopts = pysftp.CnOpts() # C:/Users/USERNAME/.ssh/known_hosts
cnopts.hostkeys.load('keys/testSftp.key')

with pysftp.Connection(host=myHostname, username= myUsername, password=myPassword, cnopts = cnopts) as sftp:
    print("Connection successfully stablished...")
    flo = io.BytesIO()
    sftp.getfo('/PATH_TO_DATA_FILE',flo)
    fileStr=flo.getvalue()
    textStr = fileStr.decode('UTF-8')
    print(textStr)

If everything works fine, you should see your file print in the command line