环境需求
单位现在每隔一段时间需要核对一下 AWS 正在运行的 EC2 资源清单,为了避免核对失误以及重复性的工作,打算用脚本来解决这一重复性的工作。大概思路为 通过 AWS AK、SK 来索取 AWS EC2 list 的权限,然后通过 Python 把正在运行的 EC2 实例筛选出来,然后提取出来想要的一些内容 写入到 CSV 表格中,通过附件的方式发送到邮箱中. 脚本参考
运行脚本所需
Python3、pip3
Python3 所需模块
boto3
csv
codecs
smtplib
脚本内容
#!/usr/bin/python # -*- coding: UTF-8 -*- import boto3 import csv import codecs import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from smtplib import SMTP ec2 = boto3.client( ‘ec2‘, aws_access_key_id="AKIAUO5xxxxxxxxxxxxxxxxxxx", aws_secret_access_key="0wcg69IbHT/5xxxxxxxxxxxxxxxxxxxxxx", region_name=‘cn-north-1‘, ) response = ec2.describe_instances() with open("/home/bsh/scripts/running.csv", "w", encoding="utf-8", newline="") as csvf: writer = csv.writer(csvf) csv_head = ["Up time", "Project", "Instance Name", "Instance ID", "Public IP", "Privite IP", "Key Name", "State"] writer.writerow(csv_head) for i in response[‘Reservations‘]: if i[‘Instances‘][0][‘State‘][‘Name‘] == ‘running‘: for j in i[‘Instances‘]: if ‘PublicIpAddress‘ not in j: j[‘PublicIpAddress‘] = "" if ‘Tags‘ not in j: j[‘Tags‘] = [] if ‘InstanceId‘ not in j: j[‘InstanceId‘] = [] if ‘KeyName‘ not in j: j[‘KeyName‘] = [] print(j[‘Tags‘]) for dic in j[‘Tags‘]: if dic[‘Key‘] == ‘Name‘: print(dic[‘Value‘]) v = dic[‘Value‘] for dic in j[‘Tags‘]: if dic[‘Key‘] == ‘Project‘: print(dic[‘Value‘]) p = dic[‘Value‘] row_cvs = [j[‘LaunchTime‘], p, v, j[‘InstanceId‘], j[‘PublicIpAddress‘], j[‘PrivateIpAddress‘], j[‘KeyName‘], ‘running‘] writer.writerow(row_cvs) print(j[‘LaunchTime‘], p, v, j[‘InstanceId‘], j[‘PublicIpAddress‘], j[‘PrivateIpAddress‘], j[‘KeyName‘], ‘running‘) mailto_list=[‘xuewenlong93@189.com‘] mail_host="smtp.189.cn" mail_user="xuewenlong93@189.cn" mail_pass="xxxx" def make_mpa_msg(): email = MIMEMultipart(‘alterbative‘) text = MIMEText(open(‘/home/bsh/scripts/running.csv‘, ‘rb‘).read(), ‘base64‘, ‘utf-8‘) text["Content-Disposition"] = ‘attachment; filename="running.csv"‘ email.attach(text) return email def send_mail(to_list,sub,content): me="awsEC2"+"<"+mail_user+">" msg = make_mpa_msg() msg[‘Subject‘] = sub msg[‘From‘] = me msg[‘To‘] = ";".join(to_list) try: server = smtplib.SMTP() server.connect(mail_host) server.login(mail_user,mail_pass) server.sendmail(me, to_list, msg.as_string()) server.close() return True except Exception as e: print (str(e)) return False for i in range(1): #发送1封 if send_mail(mailto_list,"awsec2list","msg.as_string()"): print (‘发送成功‘) else: print (‘发送失败‘)