国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 編程 > Python > 正文

Python3編程實(shí)現(xiàn)獲取阿里云ECS實(shí)例及監(jiān)控的方法

2020-02-16 02:06:45
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

本文實(shí)例講述了Python3編程實(shí)現(xiàn)獲取阿里云ECS實(shí)例及監(jiān)控的方法。分享給大家供大家參考,具體如下:

#!/usr/bin/env python3.5# -*- coding:utf8 -*-try: import httplibexcept ImportError:  import http.client as httplibimport sys,datetimeimport urllibimport urllib.requestimport urllib.errorimport urllib.parseimport timeimport jsonimport base64import hmac,sslimport uuidfrom hashlib import sha1# 解決 訪問(wèn)ssl網(wǎng)站證書的問(wèn)題try:  _create_unverified_https_context = ssl._create_unverified_contextexcept AttributeError:  # Legacy Python that doesn't verify HTTPS certificates by default  passelse:  # Handle target environment that doesn't support HTTPS verification  ssl._create_default_https_context = _create_unverified_https_contextclass aliyunclient:  def __init__(self):    self.access_id = '阿里云access_id'    self.access_secret ='阿里云secret'    #監(jiān)控獲取ECS URL    self.url = 'https://ecs.aliyuncs.com'  # #簽名  def sign(self,accessKeySecret, parameters):    sortedParameters = sorted(parameters.items(), key=lambda parameters: parameters[0])    canonicalizedQueryString = ''    for (k,v) in sortedParameters:      canonicalizedQueryString += '&' + self.percent_encode(k) + '=' + self.percent_encode(v)    stringToSign = 'GET&%2F&' + self.percent_encode(canonicalizedQueryString[1:]) # 使用get請(qǐng)求方法    bs = accessKeySecret +'&'    bs = bytes(bs,encoding='utf8')    stringToSign = bytes(stringToSign,encoding='utf8')    h = hmac.new(bs, stringToSign, sha1)    # 進(jìn)行編碼    signature = base64.b64encode(h.digest()).strip()    return signature  def percent_encode(self,encodeStr):    encodeStr = str(encodeStr)    res = urllib.request.quote(encodeStr)    res = res.replace('+', '%20')    res = res.replace('*', '%2A')    res = res.replace('%7E', '~')    return res  # 構(gòu)建除共公參數(shù)外的所有URL  def make_url(self,params):    timestamp = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())    parameters = {      'Format' : 'JSON',      'Version' : '2014-05-26',      'AccessKeyId' : self.access_id,      'SignatureVersion' : '1.0',      'SignatureMethod' : 'HMAC-SHA1',      'SignatureNonce' : str(uuid.uuid1()),      'TimeStamp' : timestamp,    }    for key in params.keys():      parameters[key] = params[key]    signature = self.sign(self.access_secret,parameters)    parameters['Signature'] = signature    url = self.url + "/?" + urllib.parse.urlencode(parameters)    return url  def do_action(self,params):    url = self.make_url(params)    # print(url)    request = urllib.request.Request(url)    try:      conn = urllib.request.urlopen(request)      response = conn.read().decode()    except urllib.error.HTTPError as e:      print(e.read().strip())      raise SystemExit(e)    try:      res = json.loads(response)    except ValueError as e:      raise SystemExit(e)    return res# 繼承原始類class client(aliyunclient):  def __init__(self,InstanceIds):    aliyunclient.__init__(self)    self.InstanceIds = InstanceIds    # ECS 區(qū)域    self.RegionId = "cn-shanghai"  # 時(shí)間UTC轉(zhuǎn)換  def timestrip(self):    UTCC = datetime.datetime.utcnow()    utcbefore5 = UTCC - datetime.timedelta(minutes =5)    Endtime = datetime.datetime.strftime(UTCC, "%Y-%m-%dT%H:%M:%SZ")    StartTime = datetime.datetime.strftime(utcbefore5, "%Y-%m-%dT%H:%M:%SZ")    return (StartTime,Endtime)  def DescribeInstanceMonitorData(self):    '''    構(gòu)造實(shí)例監(jiān)控序列函數(shù)    '''    self.tt = self.timestrip()    action_dict ={"StartTime":self.tt[0],"Endtime":self.tt[1],"Action":"DescribeInstanceMonitorData","RegionId":self.RegionId,"InstanceId":self.InstanceId}    return action_dict  def DescribeInstances(self):    '''    構(gòu)建實(shí)例配置查詢函數(shù)    '''    action_dict = {"Action":"DescribeInstances","RegionId":self.RegionId,"InstanceIds":self.InstanceIds}    return action_dict  def alis_main(self):    res = self.do_action(self.DescribeInstances())    listarry = len(res["Instances"]["Instance"])    a = {}    cpu = 0    InternetBandwidth = 0    instanlist = {"data":a}    # 調(diào)用所有符合條件的實(shí)例配置數(shù)據(jù)    for i in range(0,listarry):      self.InstanceId = res["Instances"]["Instance"][i]["InstanceId"]      BandwidthOUT = res["Instances"]["Instance"][i]["InternetMaxBandwidthOut"]      # 調(diào)用計(jì)算該實(shí)例的監(jiān)控?cái)?shù)據(jù)      monitordata = self.do_action(self.DescribeInstanceMonitorData())      data = monitordata["MonitorData"]["InstanceMonitorData"]      for i in range(0,len(data)):        cpu += data[i]["CPU"]        InternetBandwidth += data[i]["InternetBandwidth"]      # 對(duì)該實(shí)例數(shù)據(jù)生成字典      arry = {"BandwidthOUT":BandwidthOUT,"cpu":cpu/len(data),"InternetBandwidth":InternetBandwidth/len(data)}      # 將新數(shù)據(jù)重構(gòu)到原字典數(shù)據(jù)      a.setdefault(self.InstanceId,arry)    return instanlistif __name__ == "__main__":  # 傳實(shí)例ID 列表進(jìn)去  clt= client(["i-11cy8adf2x"])  res = clt.alis_main()  print(res)# 獲取的結(jié)果如下:{'data': {'i-11cy8adf2x': {'InternetBandwidth': 0.0, 'cpu': 4.0, 'BandwidthOUT': 4}}}# 解釋 獲取所有實(shí)例的 當(dāng)前配置的帶寬值 當(dāng)前占用的CPU% 當(dāng)前占用的出口帶寬 kbps            
發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 宣城市| 谷城县| 伊吾县| 灌阳县| 蕉岭县| 鄂伦春自治旗| 廊坊市| 安阳市| 包头市| 宁都县| 乌兰县| 嘉荫县| 固镇县| 盐亭县| 广安市| 赤水市| 尼勒克县| 台东县| 邓州市| 灌南县| 曲阳县| 上蔡县| 镇远县| 张北县| 容城县| 武邑县| 陵水| 怀仁县| 祥云县| 榆中县| 舒城县| 湘西| 新邵县| 禄劝| 南安市| 四川省| 青神县| 沙洋县| 定远县| 太原市| 岚皋县|