1. 程式人生 > 實用技巧 >[Contest on 2020.11.23] 遊戲

[Contest on 2020.11.23] 遊戲

環境需求

單位現在每隔一段時間需要核對一下 AWS 正在執行的 EC2 資源清單,為了避免核對失誤以及重複性的工作,打算用指令碼來解決這一重複性的工作。大概思路為 通過 AWS AK、SK 來索取 AWS EC2 list 的許可權,然後通過 Python 把正在執行的 EC2 例項篩選出來,然後提取出來想要的一些內容 寫入到 CSV 表格中,通過附件的方式傳送到郵箱中. 指令碼參考

執行指令碼所需

Python3、pip3

Python3 所需模組

boto3
csv
codecs
smtplib

指令碼內容

#!/usr/bin/python
#-*-coding:UTF-8-*-

importboto3
importcsv
importcodecs
importsmtplib

fromemail.mime.textimportMIMEText
fromemail.mime.multipartimportMIMEMultipart
fromsmtplibimportSMTP

ec2=boto3.client(
'ec2'
,
aws_access_key_id="AKIAUO5xxxxxxxxxxxxxxxxxxx",
aws_secret_access_key="0wcg69IbHT/5xxxxxxxxxxxxxxxxxxxxxx",
region_name='cn-north-1',
)

response=ec2.describe_instances()
withopen("/home/bsh/scripts/running.csv","w",encoding="utf-8",newline="")ascsvf:
writer=csv.writer(csvf)
csv_head=["Uptime","Project","InstanceName"
,"InstanceID","PublicIP","PriviteIP","KeyName","State"]
writer.writerow(csv_head)

foriinresponse['Reservations']:
ifi['Instances'][0]['State']['Name']=='running':
forjini['Instances']:
if'PublicIpAddress'notinj:
j['PublicIpAddress']=""
if'Tags'notinj:
j['Tags']=[]
if'InstanceId'notinj:
j['InstanceId']=[]
if'KeyName'
notinj:
j['KeyName']=[]
print(j['Tags'])
fordicinj['Tags']:
ifdic['Key']=='Name':
print(dic['Value'])
v=dic['Value']

fordicinj['Tags']:
ifdic['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=['[email protected]']
mail_host="smtp.189.cn"
mail_user="[email protected]"
mail_pass="xxxx"

defmake_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)
returnemail

defsend_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()
returnTrue
exceptExceptionase:
print(str(e))
returnFalse
foriinrange(1):#傳送1封
ifsend_mail(mailto_list,"awsec2list","msg.as_string()"):
print('傳送成功')
else:
print('傳送失敗')
[root@ip-10-0-10-243scripts]#pythonawsout.py
傳送成功
[root@ip-10-0-10-243scripts]#