Created
July 18, 2018 02:59
-
-
Save peterlyeung/52c3b67ef1d2e5b20c7efb6a0fa12a1f to your computer and use it in GitHub Desktop.
Lambda function to copy files from a SFTP server and add it to Salesforce as an attachment
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import paramiko | |
import requests | |
import base64 | |
import json | |
from simple_salesforce import Salesforce | |
#--------------------------------- | |
# FTP portion | |
#--------------------------------- | |
host = "ftp.yourdomain.net" | |
port = 22 | |
transport = paramiko.Transport((host)) | |
password = "CHANGE_ME" | |
username = "demo" | |
transport.connect(username = username, password = password) | |
filename = 'ConsoleClient.png' | |
path = '/pub/example/'+filename | |
localpath = '/tmp/'+filename | |
def copy_file(hostname, port, username, password, src, dst): | |
client = paramiko.SSHClient() | |
client.load_system_host_keys() | |
print (" Connecting to %s \n with username=%s... \n" %(hostname,username)) | |
t = paramiko.Transport(hostname, port) | |
t.connect(username=username,password=password) | |
sftp = paramiko.SFTPClient.from_transport(t) | |
print ("Copying file: %s to path: %s" %(src, dst)) | |
sftp.get(dst,src) | |
sftp.close() | |
t.close() | |
def add_attachment_to_sfdc(): | |
userName = 'SFDC_USER' | |
password = 'CHANGE_ME' | |
securityToken = '' | |
instance = 'na50.salesforce.com' | |
sf = Salesforce(username=userName, password=password, security_token=securityToken) | |
sessionId = sf.session_id | |
account = sf.query("SELECT Id, Name FROM Account LIMIT 1") | |
accountId = account["records"][0]["Id"] | |
body = "" | |
with open(localpath, "r") as f: | |
body = base64.b64encode(f.read()) | |
response = requests.post('https://na50.salesforce.com/services/data/v29.0/sobjects/Attachment/', | |
headers = { 'Content-Type': 'application/json', 'Authorization': 'Bearer %s' % sessionId }, | |
data = json.dumps({ | |
'ParentId': accountId, | |
'Name': filename, | |
'body': body | |
}) | |
) | |
def lambda_handler(event, context): | |
copy_file(host, port, username, password, localpath, path) | |
add_attachment_to_sfdc() | |
#--------------------------------- | |
# Salesforce portion | |
#--------------------------------- | |
if __name__ == "__main__": | |
copy_file(host, port, username, password, localpath, path) | |
add_attachment_to_sfdc() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment