编写python脚本调用阿里云SDK批量提取阿里云某region(如杭州)全部运行中实例的基本信息并生成表格。
# author lizhejie
import json
import csv
from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.acs_exception.exceptions import ClientException
from aliyunsdkcore.acs_exception.exceptions import ServerException
from aliyunsdkecs.request.v20140526.DescribeInstancesRequest import DescribeInstancesRequest
def get_page():
response = client.do_action_with_exception(request)
resj = json.loads(response, encoding='utf-8')
total_count = resj['TotalCount']
total_page, rem = divmod(resj['TotalCount'], 50)
if rem:
total_page = total_page + 1
return total_page
def desinstances(total_page):
count = 1
# 使用字典格式来收集最后实例的信息
total_dict = {}
for page in range(1, total_page+1):
request.set_PageNumber(page)
# 设置set_PageSize(50)中的数字必须大于等于get_page()中divmod方法中第二个参数值,否则无法显示所有的实例信息
request.set_PageSize(50)
# 选择状态为运行中的实例
request.set_Status("Running")
# 或得请求结果
response = client.do_action_with_exception(request)
# 结果解析为json格式
resj = json.loads(response, encoding='utf-8')
# 获得所有实例的所有信息
instances = resj['Instances']['Instance']
# 遍历每一页的实例信息
for item in instances:
# print(item)
# print(count, end=':')
# print(item['InstanceId'], end=' ')
# print(item['PublicIpAddress']['IpAddress'], end=' ')
# if item['InnerIpAddress']['IpAddress']:
# print(item['InnerIpAddress']['IpAddress'], end=' ')
# else:
# print(item['VpcAttributes']['PrivateIpAddress']['IpAddress'][0], end=' ')
# print(item['HostName'], item['InstanceTypeFamily'], item['Cpu'], item['Memory'] // 1024)
insid = item['InstanceId']
if item['PublicIpAddress']['IpAddress']:
puip = item['PublicIpAddress']['IpAddress'][0]
else:
puip = ''
if item['InnerIpAddress']['IpAddress']:
inip = item['InnerIpAddress']['IpAddress'][0]
else:
inip = item['VpcAttributes']['PrivateIpAddress']['IpAddress'][0]
hostname = item['HostName']
instype = item['InstanceTypeFamily']
vcpu = item['Cpu']
mem = item['Memory'] // 1024
insinfolist = [insid, puip, inip, hostname, instype, vcpu, mem]
total_dict[count] = insinfolist
count += 1
return total_dict
if __name__ == '__main__':
accessKeyId = input("请输入accessKeyId: ")
accessSecret = input("请输入accessSecret: ")
region = input("请输入region: ")
client = AcsClient(accessKeyId, accessSecret, region)
# 构造请求,请求的参数在每个函数中指定
request = DescribeInstancesRequest()
request.set_accept_format('json')
# 获得总页数
totalpage = get_page()
# 获得所有实例的相关信息
totaldict = desinstances(totalpage)
# print(type(totaldict))
# print(totaldict)
with open("InstanceInform.csv", 'w', newline="") as f:
headrow = ['实例ID', '公网IP', '私网IP', '主机名', '实例规格', 'CPU核数', '物理内存(G)']
write = csv.writer(f)
write.writerow(headrow)
for key in totaldict:
row = totaldict[key]
write = csv.writer(f)
write.writerow(row)
print("写入完毕!")