使用Python获取ECS相关信息2

上一次我们已经知道如何用python获取ECS信息了,不知道的可以点这里


1.返回数据格式


通过上回的代码,我们将会获得如下的数据(json格式)


{"PageNumber":1,"TotalCount":1,"PageSize":10,"RequestId":"CF15510B-9510-4E04-939B-F48C453D0E62","Instances":{"Instance":[{"ImageId":"centos_7_04_64_20G_alibase_201701015.vhd","VlanId":"","EipAddress":{"IpAddress":"","AllocationId":"","InternetChargeType":""},"ZoneId":"cn-shanghai-b","IoOptimized":true,"SerialNumber":"41b2b827-014b-4723-bcdf-a5764c9d1c2e","Cpu":1,"Memory":2048,"DeviceAvailable":true,"SecurityGroupIds":{"SecurityGroupId":["sg-uf6fq26zc62t0u0t8ftr"]},"SaleCycle":"","AutoReleaseTime":"","OSType":"linux","ResourceGroupId":"","OSName":"CentOS  7.4 64位","InstanceNetworkType":"vpc","HostName":"aliyun-sh","CreationTime":"2018-12-05T06:51Z","RegionId":"cn-shanghai","DeletionProtection":false,"OperationLocks":{"LockReason":[]},"ExpiredTime":"2019-06-05T16:00Z","InnerIpAddress":{"IpAddress":[]},"InstanceTypeFamily":"ecs.n4","InstanceId":"i-uf6gchn2j65r5scbn6rz","NetworkInterfaces":{"NetworkInterface":[{"MacAddress":"00:16:3e:02:0e:a2","PrimaryIpAddress":"172.19.214.188","NetworkInterfaceId":"eni-uf68mu7aigxbcs3huv90"}]},"InternetMaxBandwidthIn":500,"CreditSpecification":"","InternetChargeType":"PayByBandwidth","SpotStrategy":"NoSpot","StoppedMode":"Not-applicable","InternetMaxBandwidthOut":1,"VpcAttributes":{"NatIpAddress":"","PrivateIpAddress":{"IpAddress":["172.19.214.188"]},"VSwitchId":"vsw-uf6a4tfeug6t05akf9w92","VpcId":"vpc-uf6eyafn4cmj5nol253d4"},"SpotPriceLimit":0.0,"StartTime":"2018-12-14T02:33Z","KeyPairName":"哇咔咔的sh密钥","InstanceName":"哇咔咔的上海ECS","Description":"","PublicIpAddress":{"IpAddress":["47.100.239.99"]},"InstanceType":"ecs.n4.small","Status":"Running","Recyclable":false,"ClusterId":"","GPUSpec":"","GPUAmount":0,"InstanceChargeType":"PrePaid","DedicatedHostAttribute":{"DedicatedHostId":"","DedicatedHostName":""},"DeploymentSetId":""}]}}

稍微排版一下是这样的


{
"PageNumber":1,
"TotalCount":1,
"PageSize":10,
"RequestId":"04F89A1C-EC73-4F6C-84EE-F2703732DE09",

"Instances":
{
	"Instance":
	[
		{
			"ImageId":"centos_7_03_64_20G_alibase_20170818.vhd",
			"VlanId":"",
			"EipAddress":
			{
				"IpAddress":"",
				"AllocationId":"",
				"InternetChargeType":""
			},
			"ZoneId":"cn-shanghai-b",
			"IoOptimized":true,
			"SerialNumber":"41b2b827-014b-4723-bcdf-a5764c9d1c2e",
			"Cpu":1,
			"Memory":2048,
			"DeviceAvailable":true,
			"SecurityGroupIds":
			{
				"SecurityGroupId":["sg-uf6fq26zc62t0u0t8ftr"]
			},
			"SaleCycle":"",
			"AutoReleaseTime":"",
			"OSType":"linux",
			"ResourceGroupId":"",
			"OSName":"CentOS  7.3 64位",
			"InstanceNetworkType":"vpc",
			"HostName":"aliyun",
			"CreationTime":"2018-12-05T06:51Z",
			"RegionId":"cn-shanghai",
			"DeletionProtection":false,
			"OperationLocks":{"LockReason":[]},
			"ExpiredTime":"2019-06-05T16:00Z",
			"InnerIpAddress":{"IpAddress":[]},
			"InstanceTypeFamily":"ecs.n4",
			"InstanceId":"i-uf6gchn2j65r5scbn6rz",
			"NetworkInterfaces":
			{
				NetworkInterface":
				[
					{
						"MacAddress":"00:16:3e:02:0e:a2",
						"PrimaryIpAddress":"172.19.214.188",
						"NetworkInterfaceId":"eni-uf68mu7aigxbcs3huv90"
					}
				]
			},
			"InternetMaxBandwidthIn":500,
			"CreditSpecification":"",
			"InternetChargeType":"PayByBandwidth",
			"SpotStrategy":"NoSpot",
			"StoppedMode":"Not-applicable",
			"InternetMaxBandwidthOut":1,
			"VpcAttributes":
			{
				"NatIpAddress":"",
				"PrivateIpAddress":
				{
					"IpAddress":["172.19.214.188"]
				},
				"VSwitchId":"vsw-uf6a4tfeug6t05akf9w92",
				"VpcId":"vpc-uf6eyafn4cmj5nol253d4"
			},
			"SpotPriceLimit":0.0,
			"StartTime":"2018-12-05T06:55Z",
			"KeyPairName":"哇咔咔的密钥",
			"InstanceName":"哇咔咔",
			"Description":"",
			"PublicIpAddress":
			{
				"IpAddress"["47.100.239.99"]
			},
			"InstanceType":"ecs.n4.small",
			"Status":"Running",
			"Recyclable":false,
			"ClusterId":"",
			"GPUSpec":"",
			"GPUAmount":0,
			"InstanceChargeType":"PrePaid",
			"DedicatedHostAttribute":
			{
				"DedicatedHostId":"",
				"DedicatedHostName":""
			},
			"DeploymentSetId":""
		}
	]
}
}


2.数据处理


接下来我们就要用python对这些数据进行处理,恕本人才疏学浅,用了最蠢的方法来处理,直接上代码:



首先用python中的json.loads方法将获取到的json数据转化为字典


dictA=json.loads(response)

之后用for循环将一层一层的字典,列表的嵌套提取出来,并且存储到一个新的字典里面去:


dictEnd={}
dictB=dictA['Instances']
listA=dictB['Instance']
dictC=listA[0]
for i in dictC:
	if(type(dictC[i])==dict):
		dictD=dictC[i]
		if(type(dictD)==dict):
			for d in dictD:
				dictE=dictD[d]
				if(type(dictE)==list):
					listB=dictE
					if listB:
						if(type(listB[0])==dict):
							dictF=listB[0]
							for f in dictF:
								dictEnd[f]=dictF[f]
					else:
						dictEnd[d] = dictD[d]
				elif(type(dictE)==dict):
					dictG=dictE
				else:
					dictEnd[d]=dictD[d]
	else:
		dictEnd[i]=dictC[i]


这样的话,我们就已经将这个ECS的信息存储到diceEnd这个字典里面了,由于本人决定只把数据的值的部分输出到表格中,所以使用以下代码把刚刚生成的dict转换为一个list


listC=list(dictEnd.values())

3.输出到表格


这里使用openpyxl这个模块将内容输出到表格


wb = Workbook()
ws=wb.active
ws.append(listC)
wb.save('txt.xlsx')

4.完整代码


from aliyunsdkcore.client import AcsClient
from aliyunsdkecs.request.v20140526 import DescribeInstancesRequest
from openpyxl import Workbook
import json

#创建AcsClient实例
client = AcsClient(
	"你的AccessKey",
	"你的AccessKey secret",
	"地域"
);

# 创建request,并设置参数
request = DescribeInstancesRequest.DescribeInstancesRequest()
request.set_PageSize(10)

# 发起API请求并显示返回值
response = client.do_action_with_exception(request)

dictA=json.loads(response)

dictEnd={}
dictB=dictA['Instances']
listA=dictB['Instance']
dictC=listA[0]
for i in dictC:
	if(type(dictC[i])==dict):
		dictD=dictC[i]
		if(type(dictD)==dict):
			for d in dictD:
				dictE=dictD[d]
				if(type(dictE)==list):
					listB=dictE
					if listB:
						if(type(listB[0])==dict):
							dictF=listB[0]
							for f in dictF:
								dictEnd[f]=dictF[f]
					else:
						dictEnd[d] = dictD[d]

				elif(type(dictE)==dict):
					dictG=dictE
				else:
					dictEnd[d]=dictD[d]
	else:
		dictEnd[i]=dictC[i]


#转化为list
listC=list(dictEnd.values())
for i in range(len(listC)):
	if (type(listC[i])==list):
		listC[i]=""
for i in listC:
	print(i)

#excel
wb = Workbook()
ws=wb.active
ws.append(listC)
wb.save('txt.xlsx')

以上纯属本人理解,有什么错误的地方还望各位大神指正

上一篇:Android 自定义线程池的实战


下一篇:使用跟踪标记查看过滤统计信息是否被使用