python使用AliyunOpenApi获取ecs监控数据
作者:互联网
python使用AliyunOpenApi获取ecs监控数据
ecs.py
#!/usr/bin/env python
#coding=utf-8
import json
import datetime,time
from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.acs_exception.exceptions import ClientException
from aliyunsdkcore.acs_exception.exceptions import ServerException
from aliyunsdkecs.request.v20140526.DescribeInstanceMonitorDataRequest import DescribeInstanceMonitorDataRequest
from aliyunsdkecs.request.v20140526.DescribeInstancesRequest import DescribeInstancesRequest
client = AcsClient('AK_ID', 'AK_SRT', 'cn-beijing')
# 时间处理函数
def time2iso(dt):
"""本地时间转UTC时间(-8:00)"""
cr_date = datetime.datetime.strptime(dt, '%Y-%m-%d %H:%M:%S')
# print(cr_date)
time_struct = time.mktime(cr_date.timetuple())
utc_st = datetime.datetime.utcfromtimestamp(time_struct)
utc_st = str(utc_st).replace(' ','T') + 'Z'
return utc_st
# return datetime.datetime.utcfromtimestamp(timestamp).strftime(format).replace('{-FF-}',sec)
# 获取运维监控信息
def get_ecs_eni(starttime,endtime,ins,timesp):
request = DescribeInstanceMonitorDataRequest()
request.set_accept_format('json')
request.set_StartTime(starttime)
request.set_EndTime(endtime)
request.set_Period(timesp)
ecs_mo = {}
for eid in ins.keys():
ins_mo = {}
request.set_InstanceId(eid)
response = json.loads(str(client.do_action_with_exception(request),encoding='utf-8'))
cpu = []
net = []
rio = []
wio = []
for mons in response["MonitorData"]["InstanceMonitorData"]:
if "CPU" in mons and "IOPSWrite" in mons and "IOPSRead" in mons and "IntranetBandwidth" in mons:
cpu.append(mons['CPU'])
wio.append(mons['IOPSWrite'])
rio.append(mons['IOPSRead'])
net.append(mons['IntranetBandwidth'])
ins_mo["CPU"] = str(max(cpu)) + '%'
ins_mo["net"] = str(float("%.2f" % (max(net) /1024 ))) #+'MB/s'
ins_mo["wio"] = str(max(wio))+'次/s'
ins_mo["rio"] = str(max(rio))+'次/s'
ins_mo["InstanceId"] = eid
ins_mo["InstanceName"] = ins[eid][0]
ins_mo["IpAddress"] = ins[eid][1]
ecs_mo[eid] = ins_mo
print(ecs_mo)
# 获取ecs 实例基本信息
def get_ecs_instance():
request = DescribeInstancesRequest()
request.set_accept_format('json')
request.set_VpcId("vpc-id")
request.set_VSwitchId("vsw-id")
request.set_PageSize(50)
response = json.loads(str(client.do_action_with_exception(request),encoding='utf-8'))
inss = {}
for ins in response["Instances"]["Instance"]:
data = []
# print(ins["InstanceName"],ins["InstanceId"],ins["VpcAttributes"]["PrivateIpAddress"]["IpAddress"][0])
data.append(ins["InstanceName"])
data.append(ins["VpcAttributes"]["PrivateIpAddress"]["IpAddress"][0])
inss[ins["InstanceId"]] = data
return inss
if __name__ == '__main__':
starttime = time2iso("2021-06-22 00:00:01")
endtime = time2iso("2021-06-29 23:59:50")
print(starttime,endtime)
# ecsid = "i-idssssssssssss"
timesp = 3600
inss = get_ecs_instance()
get_ecs_eni(starttime,endtime,inss,timesp)
标签:set,python,mo,request,ins,ecs,AliyunOpenApi,mons 来源: https://www.cnblogs.com/pgy674477230/p/16351509.html