欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

 更新時(shí)間:2017年08月18日 08:56:47   作者:水·域  
這篇文章主要介紹了Python3編程實(shí)現(xiàn)獲取阿里云ECS實(shí)例及監(jiān)控的方法,涉及Python URL登陸及請(qǐng)求處理相關(guān)操作技巧,需要的朋友可以參考下

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

#!/usr/bin/env python3.5
# -*- coding:utf8 -*-
try: import httplib
except ImportError:
  import http.client as httplib
import sys,datetime
import urllib
import urllib.request
import urllib.error
import urllib.parse
import time
import json
import base64
import hmac,ssl
import uuid
from hashlib import sha1
# 解決 訪問(wèn)ssl網(wǎng)站證書的問(wèn)題
try:
  _create_unverified_https_context = ssl._create_unverified_context
except AttributeError:
  # Legacy Python that doesn't verify HTTPS certificates by default
  pass
else:
  # Handle target environment that doesn't support HTTPS verification
  ssl._create_default_https_context = _create_unverified_https_context
class 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 instanlist
if __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

更多關(guān)于Python相關(guān)內(nèi)容可查看本站專題:《Python Socket編程技巧總結(jié)》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》、《Python入門與進(jìn)階經(jīng)典教程》及《Python文件與目錄操作技巧匯總

希望本文所述對(duì)大家Python程序設(shè)計(jì)有所幫助。

相關(guān)文章

最新評(píng)論