Skip to content

Instantly share code, notes, and snippets.

@pydemo
Forked from peterlyeung/sfdc.py
Created April 6, 2022 13:49
Show Gist options
  • Save pydemo/61663f19b8f73b9f2d11990572d63e42 to your computer and use it in GitHub Desktop.
Save pydemo/61663f19b8f73b9f2d11990572d63e42 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
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