Using a Python Program to Post to an SFTP Server
We have a client that requested that we deliver a daily file with some data to their SFTP site. They planned to import the data into their systems in order to do some internal reporting.
We are a Python shop so we needed to come up with an appropriate solution. Using pysftp seemed like our way to go, but the client provided a PPK file. To accommodate the module, we had to convert the PPK file to a PEM file.
Given the right key file, uploading to an SFTP server is a pretty straightforward process:
import pyodbc
try:
host = 'sftp.my-client.com'
local_filename = './data.txt'
filename = 'data.txt'
cnopts = pysftp.CnOpts()
# To get know host, use: ssh-keyscan sftp.my-client.com
cnopts.hostkeys = None
with pysftp.Connection(host,
username='my_username',
private_key='converted_from_ppk.pem',
cnopts=cnopts) as sftp:
print(" Putting {0}".format(filename))
sftp.put(local_filename, filename)
except Exception as e:
print("EXCEPTION THROWN **************")
print(str(e))
Having any issues uploading to SFTP servers? Any successes? Love to hear about them!
