Betterworks Engage: Sample Code to setup SFTP Automation

Avatar
by Amanda Iles
Follow

Sample Python Code that can be used as reference to set up the SFTP automation - Encrypt and Load in SFTP server

 

import requests
import json
import csv
import gnupg
import datetime
import pysftp
import os

rows = [["row1"],["row2"]]

op = open('C:\\Temp\\examplefile.csv','wb')
op.write('email,first_name,last_name,employee_id,locale,manager_email,status,roles,insights_access,hire_date,end_employment_date,location,department,gender,departmentcode,isRegretfulLeaver\n'.encode("UTF8"))

for row in rows:
	comma = ""
	for column in row:
		if '"' in column or ',' in column:
			op.write((comma + '"' + column.replace('"','""') + '"').encode("UTF8"))
		else:
			op.write((comma + column).encode("UTF8"))
		comma = ","
	op.write("\n".encode("UTF8"))
op.close()
gpg = gnupg.GPG()

dt = datetime.datetime.now().strftime('%Y%m%d%H%M%S')

with open('C:\\Temp\\examplefile.csv','rb') as f:
	status = gpg.encrypt_file(
		f, recipients=['sftp@gethyphen.com'],
		output='C:\\Temp\\' + dt + '.csv.tst',
		always_trust=True)

print('ok: ', status.ok)
print('status: ', status.status)
print('stderr: ', status.stderr)

cf = open('C:\\Temp\\' + dt + '.csv.done.tst','w')
cf.close()

cnopts = pysftp.CnOpts()
cnopts.hostkeys = None
srv = pysftp.Connection(host='sftp.gethyphen.com',username='username',password='password', cnopts=cnopts)

print(srv.listdir())

srv.put(dt + '.csv.tst','uploads/' + dt + '.csv.pgp')
srv.put(dt + '.csv.done.tst','uploads/' + dt + '.csv.done.pgp')
srv.close()

os.remove('C:\\Temp\\' + dt + '.csv.tst')
os.remove('C:\\Temp\\' + dt + '.csv.done.tst')