SlideShare a Scribd company logo
AWS Lambda
Scheduled file transfer sftp to s3
python
Steps
1. Create a new Administrator user in the IAM
2. Create a Role and allow Lambda execution and permissions for S3
operations
3. Take note of the User ARN
4. Deploy 64-bit Amazon Linux EC2 instance
5. SSH in, make project directory/folder
6. Create requirements.txt file, list python packages (except boto3)
7. Write the Handler
8. Zip up code and Dependencies
9. Create Lambda Function
10. Manually invoke the Lambda Function
11. Create the schedule
Handlerimport paramiko
import boto3
import datetime
import os
LOCALFILE='/tmp/invbatch.txt'
s3 = boto3.client('s3')
def connect_to_sftp():
transport = paramiko.Transport((os.environ['HOST'],int(os.environ['PORT'])))
transport.connect(username=os.environ['USERNAME'],
password=os.environ['PASSWORD'])
sftp = paramiko.SFTPClient.from_transport(transport)
return sftp
def handler(event, context):
sftp = connect_to_sftp()
sftp.get(os.environ['REMOTEFILE'], LOCALFILE)
now = datetime.datetime.today()
S3FILE='test/' + now.strftime('%Y%m%d-%H%M%S') + '_invbatch.txt'
s3.upload_file(Filename=LOCALFILE, Bucket='nufin-test-bucket', Key=S3FILE)
Makefile
Zip up Code and Dependencies
packageDependencies:
zip -r9 $(FUNCTION).zip sftp_to_s3.py
mkdir -p site-packages
virtualenv $(FUNCTION)
. $(FUNCTION)/bin/activate; pip install -r requirements.txt;
cd site-packages; cp -r $$VIRTUAL_ENV/lib/python2.7/site-packages/ ./;
cp -r $$VIRTUAL_ENV/lib64/python2.7/site-packages/ ./;
cd site-packages; zip -r9 ../../$(FUNCTION).zip .
PROJECT = sftp2s3
FUNCTION = $(PROJECT)
REGION = ap-southeast-1
ROLE = arn:aws:iam::864962608331:role/service-role/myLambdaRole
Makefile Variables
Makefile
Create the Lambda Function
createFunction:
aws lambda create-function 
--region $(REGION) 
--function-name $(PROJECT) 
--zip-file fileb://$(FUNCTION).zip 
--role $(ROLE) 
--environment Variables=“{HOST='12.123.123.12',PORT=22,USERNAME='lhftp',PASSWORD='123456789012',REMOTEFILE='lhftp_uploads/invb
--handler sftp_to_s3.handler 
--runtime python2.7 
--profile Administrator 
--timeout 10 
--memory-size 1024
Makefile
manualInvoke:
aws lambda invoke 
--invocation-type RequestResponse 
--function-name $(FUNCTION) 
--region $(REGION) 
--profile Administrator 
outputfile.txt
Manually Invoke the Lambda function to test it
Makefile
# Schedule the Lambda Function
# Step 1:
createRule:
aws events put-rule 
--region $(REGION) 
--name $(FUNCTION)-rule 
--schedule-expression 'cron(0/5 8-17 ? * MON-FRI *)' 
--profile Administrator
Schedule the Lambda function : Create the rule
Makefile
# $(ARNRULE) is taken from the put-rule target output and parsed in
# ARNRULE=arn:aws:events:.....
# Step 2:
addPermission:
aws lambda add-permission 
--region $(REGION) 
--function-name $(FUNCTION) 
--statement-id $(FUNCTION)-event 
--action 'lambda:InvokeFunction' 
--principal events.amazonaws.com 
--source-arn $(ARNRULE) 
--profile Administrator
Schedule the function : Give permission to the event
Makefile
Schedule the function : Associate the Lambda with the Event
putTargets:
aws events put-targets 
--region $(REGION) 
--rule $(FUNCTION)-rule 
--targets file://targets.json 
--profile Administrator
[
{
"Id": "1",
"Arn":"arn:aws:lambda:ap-southeast-1:864962608331:function:sftp2s3"
}
]
targets.json

More Related Content

Recently uploaded (20)

PPTX
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
PDF
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
PDF
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
PDF
Empower Inclusion Through Accessible Java Applications
Ana-Maria Mihalceanu
 
PDF
Log-Based Anomaly Detection: Enhancing System Reliability with Machine Learning
Mohammed BEKKOUCHE
 
PDF
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
PDF
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
PDF
DevBcn - Building 10x Organizations Using Modern Productivity Metrics
Justin Reock
 
PDF
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
PPTX
OpenID AuthZEN - Analyst Briefing July 2025
David Brossard
 
PPTX
UiPath Academic Alliance Educator Panels: Session 2 - Business Analyst Content
DianaGray10
 
PDF
Complete JavaScript Notes: From Basics to Advanced Concepts.pdf
haydendavispro
 
PDF
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
PPTX
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
PDF
LLMs.txt: Easily Control How AI Crawls Your Site
Keploy
 
PDF
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
PPTX
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 
PDF
Fl Studio 24.2.2 Build 4597 Crack for Windows Free Download 2025
faizk77g
 
PDF
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
PDF
Chris Elwell Woburn, MA - Passionate About IT Innovation
Chris Elwell Woburn, MA
 
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
Empower Inclusion Through Accessible Java Applications
Ana-Maria Mihalceanu
 
Log-Based Anomaly Detection: Enhancing System Reliability with Machine Learning
Mohammed BEKKOUCHE
 
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
DevBcn - Building 10x Organizations Using Modern Productivity Metrics
Justin Reock
 
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
OpenID AuthZEN - Analyst Briefing July 2025
David Brossard
 
UiPath Academic Alliance Educator Panels: Session 2 - Business Analyst Content
DianaGray10
 
Complete JavaScript Notes: From Basics to Advanced Concepts.pdf
haydendavispro
 
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
LLMs.txt: Easily Control How AI Crawls Your Site
Keploy
 
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 
Fl Studio 24.2.2 Build 4597 Crack for Windows Free Download 2025
faizk77g
 
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
Chris Elwell Woburn, MA - Passionate About IT Innovation
Chris Elwell Woburn, MA
 

Featured (20)

PDF
2024 Trend Updates: What Really Works In SEO & Content Marketing
Search Engine Journal
 
PDF
Storytelling For The Web: Integrate Storytelling in your Design Process
Chiara Aliotta
 
PDF
Artificial Intelligence, Data and Competition – SCHREPEL – June 2024 OECD dis...
OECD Directorate for Financial and Enterprise Affairs
 
PDF
How to Leverage AI to Boost Employee Wellness - Lydia Di Francesco - SocialHR...
SocialHRCamp
 
PDF
2024 State of Marketing Report – by Hubspot
Marius Sescu
 
PDF
Everything You Need To Know About ChatGPT
Expeed Software
 
PDF
Product Design Trends in 2024 | Teenage Engineerings
Pixeldarts
 
PDF
How Race, Age and Gender Shape Attitudes Towards Mental Health
ThinkNow
 
PDF
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
marketingartwork
 
PDF
Skeleton Culture Code
Skeleton Technologies
 
PDF
PEPSICO Presentation to CAGNY Conference Feb 2024
Neil Kimberley
 
PDF
Content Methodology: A Best Practices Report (Webinar)
contently
 
PPTX
How to Prepare For a Successful Job Search for 2024
Albert Qian
 
PDF
Social Media Marketing Trends 2024 // The Global Indie Insights
Kurio // The Social Media Age(ncy)
 
PDF
Trends In Paid Search: Navigating The Digital Landscape In 2024
Search Engine Journal
 
PDF
5 Public speaking tips from TED - Visualized summary
SpeakerHub
 
PDF
ChatGPT and the Future of Work - Clark Boyd
Clark Boyd
 
PDF
Getting into the tech field. what next
Tessa Mero
 
PDF
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Lily Ray
 
PDF
How to have difficult conversations
Rajiv Jayarajah, MAppComm, ACC
 
2024 Trend Updates: What Really Works In SEO & Content Marketing
Search Engine Journal
 
Storytelling For The Web: Integrate Storytelling in your Design Process
Chiara Aliotta
 
Artificial Intelligence, Data and Competition – SCHREPEL – June 2024 OECD dis...
OECD Directorate for Financial and Enterprise Affairs
 
How to Leverage AI to Boost Employee Wellness - Lydia Di Francesco - SocialHR...
SocialHRCamp
 
2024 State of Marketing Report – by Hubspot
Marius Sescu
 
Everything You Need To Know About ChatGPT
Expeed Software
 
Product Design Trends in 2024 | Teenage Engineerings
Pixeldarts
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
ThinkNow
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
marketingartwork
 
Skeleton Culture Code
Skeleton Technologies
 
PEPSICO Presentation to CAGNY Conference Feb 2024
Neil Kimberley
 
Content Methodology: A Best Practices Report (Webinar)
contently
 
How to Prepare For a Successful Job Search for 2024
Albert Qian
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Kurio // The Social Media Age(ncy)
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Search Engine Journal
 
5 Public speaking tips from TED - Visualized summary
SpeakerHub
 
ChatGPT and the Future of Work - Clark Boyd
Clark Boyd
 
Getting into the tech field. what next
Tessa Mero
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Lily Ray
 
How to have difficult conversations
Rajiv Jayarajah, MAppComm, ACC
 
Ad

Schedule File Transfer from SFTP to S3 with AWS Lambda

  • 1. AWS Lambda Scheduled file transfer sftp to s3 python
  • 2. Steps 1. Create a new Administrator user in the IAM 2. Create a Role and allow Lambda execution and permissions for S3 operations 3. Take note of the User ARN 4. Deploy 64-bit Amazon Linux EC2 instance 5. SSH in, make project directory/folder 6. Create requirements.txt file, list python packages (except boto3) 7. Write the Handler 8. Zip up code and Dependencies 9. Create Lambda Function 10. Manually invoke the Lambda Function 11. Create the schedule
  • 3. Handlerimport paramiko import boto3 import datetime import os LOCALFILE='/tmp/invbatch.txt' s3 = boto3.client('s3') def connect_to_sftp(): transport = paramiko.Transport((os.environ['HOST'],int(os.environ['PORT']))) transport.connect(username=os.environ['USERNAME'], password=os.environ['PASSWORD']) sftp = paramiko.SFTPClient.from_transport(transport) return sftp def handler(event, context): sftp = connect_to_sftp() sftp.get(os.environ['REMOTEFILE'], LOCALFILE) now = datetime.datetime.today() S3FILE='test/' + now.strftime('%Y%m%d-%H%M%S') + '_invbatch.txt' s3.upload_file(Filename=LOCALFILE, Bucket='nufin-test-bucket', Key=S3FILE)
  • 4. Makefile Zip up Code and Dependencies packageDependencies: zip -r9 $(FUNCTION).zip sftp_to_s3.py mkdir -p site-packages virtualenv $(FUNCTION) . $(FUNCTION)/bin/activate; pip install -r requirements.txt; cd site-packages; cp -r $$VIRTUAL_ENV/lib/python2.7/site-packages/ ./; cp -r $$VIRTUAL_ENV/lib64/python2.7/site-packages/ ./; cd site-packages; zip -r9 ../../$(FUNCTION).zip . PROJECT = sftp2s3 FUNCTION = $(PROJECT) REGION = ap-southeast-1 ROLE = arn:aws:iam::864962608331:role/service-role/myLambdaRole Makefile Variables
  • 5. Makefile Create the Lambda Function createFunction: aws lambda create-function --region $(REGION) --function-name $(PROJECT) --zip-file fileb://$(FUNCTION).zip --role $(ROLE) --environment Variables=“{HOST='12.123.123.12',PORT=22,USERNAME='lhftp',PASSWORD='123456789012',REMOTEFILE='lhftp_uploads/invb --handler sftp_to_s3.handler --runtime python2.7 --profile Administrator --timeout 10 --memory-size 1024
  • 6. Makefile manualInvoke: aws lambda invoke --invocation-type RequestResponse --function-name $(FUNCTION) --region $(REGION) --profile Administrator outputfile.txt Manually Invoke the Lambda function to test it
  • 7. Makefile # Schedule the Lambda Function # Step 1: createRule: aws events put-rule --region $(REGION) --name $(FUNCTION)-rule --schedule-expression 'cron(0/5 8-17 ? * MON-FRI *)' --profile Administrator Schedule the Lambda function : Create the rule
  • 8. Makefile # $(ARNRULE) is taken from the put-rule target output and parsed in # ARNRULE=arn:aws:events:..... # Step 2: addPermission: aws lambda add-permission --region $(REGION) --function-name $(FUNCTION) --statement-id $(FUNCTION)-event --action 'lambda:InvokeFunction' --principal events.amazonaws.com --source-arn $(ARNRULE) --profile Administrator Schedule the function : Give permission to the event
  • 9. Makefile Schedule the function : Associate the Lambda with the Event putTargets: aws events put-targets --region $(REGION) --rule $(FUNCTION)-rule --targets file://targets.json --profile Administrator [ { "Id": "1", "Arn":"arn:aws:lambda:ap-southeast-1:864962608331:function:sftp2s3" } ] targets.json