· 8 years ago · Dec 23, 2017, 09:46 PM
1import boto3
2from datetime import datetime, timedelta
3from operator import itemgetter
4import smtplib
5from email.mime.text import MIMEText
6
7
8AccessKey = "Your Access Key"
9SecretKey = "Your Secret Key"
10
11# Mail sender function
12def SendMail(alert):
13 # Define to/from
14 sender = 'sender email'
15 recipient = 'recipient email'
16
17 # Create message
18 msg = MIMEText(alert)
19 msg['Subject'] = "CPU Utilization Alert on server with InstanceID %s " % InstanceID
20 msg['From'] = sender
21 msg['To'] = recipient
22
23 # Create server object with SSL option
24 server = smtplib.SMTP_SSL('smtp.zoho.com', 465) # May be another mail server
25
26 # Perform operations via server
27 server.login('mail login', 'mail password')
28 server.sendmail(sender, [recipient], msg.as_string())
29 server.quit()
30
31
32now = datetime.utcnow() # Now time in UTC format
33past = now - timedelta(minutes=60) # Minus 60 minutes
34
35# Amazon Cloud Watch connection
36client_cw = boto3.client(
37 'cloudwatch',
38 aws_access_key_id = AccessKey,
39 aws_secret_access_key = SecretKey,
40
41)
42
43# Amazon EC2 connection
44client_ec2 = boto3.client(
45 'ec2',
46 aws_access_key_id = AccessKey,
47 aws_secret_access_key = SecretKey,
48
49)
50
51response = client_ec2.describe_instances() # Get all instances from Amazon EC2
52
53for reservation in response["Reservations"]:
54 for instance in reservation["Instances"]:
55
56 # This will print output the value of the Dictionary key 'InstanceId'
57 print(instance["InstanceId"])
58
59 # Get CPU Utilization for each InstanceID
60 CPUUtilization = client_cw.get_metric_statistics(
61 Namespace='AWS/EC2',
62 MetricName='CPUUtilization',
63 Dimensions=[{'Name': 'InstanceId', 'Value': instance["InstanceId"]}],
64 StartTime=past,
65 EndTime=now,
66 Period=600,
67 Statistics=['Average'])
68
69 datapoints = CPUUtilization['Datapoints'] # CPU Utilization results
70 last_datapoint = sorted(datapoints, key=itemgetter('Timestamp'))[-1] # Last result
71 utilization = last_datapoint['Average'] # Last utilization
72 load = round((utilization / 100.0), 3) # Last utilization in %
73 timestamp = str(last_datapoint['Timestamp']) # Last utilization timestamp
74 print("{0} load at {1}".format(load, timestamp))
75
76 # Send mail if CPU load more than 50%
77 if load > 50:
78 InstanceID = instance["InstanceId"]
79 SendMail("CPU Utilization more than 50% on server with InstanceID {0}\n"
80 "\n{1}% load at {2} (UTC time)".format(InstanceID, load, timestamp))