获取所有的AWS EC2主机信息
前置条件
- 本地需要安装aws cli工具,以及配置好相关的key;
- EC2 主机需要添加Tag(环境/部门/业务);
具体步骤
- 需要安装PrettyTable模块
1
# pip install PrettyTable
- 脚本内容
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162#! /usr/bin/env python
# -*- coding: utf-8 -*-
# __author__ = "shuke"
# Date: 2018/2/7
from prettytable import PrettyTable
import subprocess
import datetime
import xlwt
import json
import sys
import getopt
def get_all_aws_ec2():
"""
所有的EC2实例ID
:return:
"""
try:
command = "aws ec2 describe-instances --query 'Reservations[*].Instances[*].[InstanceId]'"
ret = subprocess.getoutput(command)
ret = json.loads(ret)
except Exception as e:
print("ERROR: ", e)
sys.exit("Bey Bey!")
all_aws_ec2_list = []
for ec2 in ret:
if len(ec2) > 1:
for item in ec2:
all_aws_ec2_list.append(item[0])
else:
all_aws_ec2_list.append(ec2[0][0])
return all_aws_ec2_list
def get_ec2_info():
"""
获取所有的 EC2 属性信息
:return:
"""
try:
command = "aws ec2 describe-instances --query 'Reservations[*].Instances[*].[InstanceId,Placement.AvailabilityZone,State.Name,Tags[?Key==`Name`].Value,PrivateIpAddress,NetworkInterfaces[0].PrivateIpAddresses[0].Association.PublicIp,SecurityGroups[0].GroupName,SecurityGroups[1].GroupName,Tags[?Key==`环境`].Value,Tags[?Key==`部门`].Value,Tags[?Key==`业务`].Value,Tags[?Key==`备注`].Value]'"
ret = subprocess.getoutput(command)
all_aws_ec2_list = json.loads(ret)
except Exception as e:
print("ERROR: ", e)
sys.exit("Bey Bey!")
host_info_list = []
for item in all_aws_ec2_list:
if len(item) > 1:
for ec2 in item:
host_info_list.append([ec2])
else:
host_info_list.append(item)
return host_info_list
def set_style(name, height, bold=False):
"""
表格样式
:param name:
:param height:
:param bold:
:return:
"""
style = xlwt.XFStyle() # 初始化样式
font = xlwt.Font() # 为样式创建字体
font.name = name # 'Times New Roman'
font.bold = bold
font.color_index = 3
font.height = height
style.font = font
return style
def write_execl(filename):
"""
输出到excel文件中
:param filename:
:return:
"""
f = xlwt.Workbook() # 创建工作簿
sheet1 = f.add_sheet('AWS主机信息表', cell_overwrite_ok=True)
title = ['实例ID', 'region', '状态', 'Name', '内网IP', '公网IP', '安全组-1', '安全组-2', '环境', '部门', '业务', '备注']
# 生成第一行
for i in range(0, len(title)):
sheet1.write(0, i, title[i], set_style('简体中文', 350, True))
host_info_list = get_ec2_info()
i = 1
while i < int(len(host_info_list) + 1):
for j in range(0, len(title)):
if isinstance(host_info_list[i - 1][0][j], list):
cell = host_info_list[i - 1][0][j] if host_info_list[i - 1][0][j] else None
else:
cell = host_info_list[i - 1][0][j]
sheet1.write(i, j, cell)
i += 1
f.save(filename)
def table_stdout():
"""
输出为表格形式
:return:
"""
table = PrettyTable(
["编号", "实例ID", "region", "状态", "Name", "内网IP", "公网IP", "安全组-1", "安全组-2", "环境", "部门", "业务", "备注"])
all_ec2_instance_id_list = get_all_aws_ec2()
host_info_list = get_ec2_info()
if len(all_ec2_instance_id_list) != len(host_info_list):
sys.exit("ERROR: 主机数量不一致,请检查!")
count = 0
for ec2_info in host_info_list:
temp = []
count += 1
ec2_info[0].insert(0, count)
for item in ec2_info[0]:
if isinstance(item, list):
temp.append(item[0] if item else None)
else:
temp.append(item)
table.add_row(temp)
table.reversesort = True
print(table)
print("\033[0;32m%s:, AWS EC2 Total: %d\033[0m" % (datetime.datetime.now(), len(all_ec2_instance_id_list)))
def main(argv, excel_path):
usage = """usage:
test.py -t/--table
test.py -f/--outfile
"""
try:
opts, args = getopt.getopt(argv, "htf", ["help", "table", "outfile"])
except getopt.GetoptError:
print(usage)
sys.exit(2)
for opt, arg in opts:
if opt in ("-h", "--help"):
print(usage)
sys.exit(2)
elif opt in ("-t", "--table"):
table_stdout()
elif opt in ("-f", "--outfile"):
write_execl(excel_path)
else:
print(usage)
sys.exit(2)
if __name__ == '__main__':
excel_path = "/tmp/AWS主机信息表-{date}.xlsx".format(date=datetime.date.today())
main(sys.argv[1:], excel_path