環境需求
單位現在每隔一段時間需要核對一下 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 ('發送失敗')
[root@ip-10-0-10-243 scripts]# python awsout.py
發送成功
[root@ip-10-0-10-243 scripts]#