SHARE
TWEET

Untitled

a guest Oct 22nd, 2019 69 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import boto3
  2.  
  3. def provideHelp(params):
  4.     message =  "Set the subject of the email to one of the following\n"
  5.     message += "help - provides this help\n"
  6.     message += "status - provides the status of all ec2 instances in the region\n"
  7.     message += "start {instance-id} - starts the ec2 instance with with the specified instance-id\n"
  8.     message += "stop {instance-id} - stops the ec2 instance with the specified instance id"
  9.    
  10.     return message
  11.  
  12. def getStatus(params):
  13.     #get a list of all ec2 instances
  14.     print("getStatus:Params:",params)
  15.    
  16.     #if a parameter is provided, it is the aws region to check
  17.     if (len(params) >= 1):
  18.         ec2 = boto3.client("ec2", params[0])
  19.     else:
  20.         ec2 = boto3.client("ec2")
  21.        
  22.     response = ec2.describe_instances()
  23.     instances = response['Reservations']
  24.    
  25.     number_instances = len(instances)
  26.     print("NumInstances:",number_instances)
  27.    
  28.     message = ""
  29.    
  30.     for instance in instances:
  31.         print("Instance:",str(instance))
  32.         instance_id = instance['Instances'][0]['InstanceId']
  33.        
  34.         message += instance_id + "\t"
  35.        
  36.         try:
  37.             if (instance['Instances'][0]['Tags'][0]['Key'] == 'Name'):
  38.                 instance_name = instance['Instances'][0]['Tags'][0]['Value']
  39.                
  40.                 if (instance_name == ""):
  41.                     message += "[No Name Found]\t"
  42.                 else:
  43.                     message += instance_name + "\t"
  44.         except:
  45.             message += "[No Name Found]\t"
  46.            
  47.         instance_state = instance['Instances'][0]['State']['Name']
  48.        
  49.         message += instance_state + "\t"
  50.        
  51.         try:
  52.             instance_privateip = instance['Instances'][0]['PrivateIpAddress']
  53.             message += instance_privateip + "\t"
  54.         except:
  55.             message += "[No Private IP]\t"
  56.            
  57.         try:
  58.             instance_publicip = instance['Instances'][0]['PublicIpAddress']
  59.             message += instance_publicip + "\t"
  60.         except:
  61.             message += "[No Public IP]\t"
  62.        
  63.         message += "\n"
  64.    
  65.     return message
  66.    
  67. def startInstance(params):
  68.    
  69.     if (len(params) > 1):
  70.         instanceId = params[0]
  71.         aws_region = params[1]
  72.         ec2 = boto3.client("ec2", aws_region)
  73.     else:
  74.         instanceId = params[0]
  75.         ec2 = boto3.client("ec2")
  76.    
  77.     try:
  78.         response = ec2.start_instances(
  79.             InstanceIds=[instanceId]    
  80.         )
  81.         message = "Starting instance " + str(instanceId) + " Please check status in a couple of minutes\n" + str(response)
  82.  
  83.     except Exception as e:
  84.         message = "Error starting instance(s) :" + str(instanceId) + " " + str(e)
  85.         print(message)
  86.        
  87.     return message
  88.  
  89. def stopInstance(params):
  90.    
  91.     if (len(params) > 1):
  92.         instanceId = params[0]
  93.         aws_region = params[1]
  94.         ec2 = boto3.client("ec2", aws_region)
  95.     else:
  96.         instanceId = params[0]
  97.         ec2 = boto3.client("ec2")
  98.    
  99.     try:
  100.         response = ec2.stop_instances(
  101.             InstanceIds=[instanceId]
  102.         )
  103.         message = "Stopping instance " + str(instanceId) + " Please check status in a couple of minutes\n" + str(response)
  104.    
  105.     except Exception as e:
  106.         message = "Error stopping instance(s) " + str(instanceId) + " " + str(e)
  107.         print(message)
  108.     return message
  109.  
  110. def sendEmail(fromAddress,recipientAddress,subject,body):
  111.     #sending email
  112.     print("sending email")
  113.    
  114.     client = boto3.client('ses')
  115.     response = client.send_email(
  116.         Destination={
  117.             'ToAddresses': [recipientAddress],
  118.         },
  119.         Message={
  120.             'Body': {
  121.                 'Text': {
  122.                     'Charset': 'UTF-8',
  123.                     'Data': body
  124.                 },
  125.             },
  126.             'Subject': {
  127.                 'Charset':  'UTF-8',
  128.                 'Data': subject
  129.             },
  130.         },
  131.         ReplyToAddresses=[fromAddress],
  132.         ReturnPath=fromAddress,
  133.         Source=fromAddress
  134.     )
  135.     print("Response from SES:",response)
  136.    
  137. def lambda_handler(event, context):
  138.     approvedSenders = ['john@example.com','tom@example.com','jane@example']
  139.    
  140.     print("Event:",event)
  141.     print("Context",context)
  142.     emailSender = event["Records"][0]["ses"]["mail"]["source"]
  143.     emailSubject = event["Records"][0]["ses"]["mail"]["commonHeaders"]["subject"]
  144.     command_split = emailSubject.split(" ")
  145.     command = command_split[0].lower()
  146.    
  147.     if (len(command_split) > 1):
  148.         commandParams = command_split[1:len(command_split)]
  149.     else:
  150.         commandParams = "" #if there are no command params, then just set it to blank
  151.    
  152.     print("From:",emailSender)
  153.     print("Subject:",emailSubject)
  154.     print("Command:",command)
  155.    
  156.     #authenticate the sender based on fromAddress
  157.     if emailSender in approvedSenders:
  158.         switcher = {
  159.             "help": provideHelp,
  160.             "status": getStatus,
  161.             "start": startInstance,
  162.             "stop": stopInstance
  163.         }
  164.        
  165.         #get the command that was specified in the email
  166.         functionToRun = switcher.get(command, lambda params: "invalid command")
  167.        
  168.         body = functionToRun(commandParams)
  169.            
  170.         sendEmail("admin@managedinstances.com",emailSender,"Execution result for command:"+ emailSubject, str(body))
  171.     else:
  172.         print("Sender ",emailSender," not approved for executing commands. Ignore")
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Not a member of Pastebin yet?
Sign Up, it unlocks many cool features!
 
Top