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

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

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

本文實例講述了Python3編程實現(xiàn)獲取阿里云ECS實例及監(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
# 解決 訪問ssl網(wǎng)站證書的問題
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請求方法
    bs = accessKeySecret +'&'
    bs = bytes(bs,encoding='utf8')
    stringToSign = bytes(stringToSign,encoding='utf8')
    h = hmac.new(bs, stringToSign, sha1)
    # 進行編碼
    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
  # 構建除共公參數(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"
  # 時間UTC轉換
  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):
    '''
    構造實例監(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):
    '''
    構建實例配置查詢函數(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}
    # 調用所有符合條件的實例配置數(shù)據(jù)
    for i in range(0,listarry):
      self.InstanceId = res["Instances"]["Instance"][i]["InstanceId"]
      BandwidthOUT = res["Instances"]["Instance"][i]["InternetMaxBandwidthOut"]
      # 調用計算該實例的監(jiān)控數(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"]
      # 對該實例數(shù)據(jù)生成字典
      arry = {"BandwidthOUT":BandwidthOUT,"cpu":cpu/len(data),"InternetBandwidth":InternetBandwidth/len(data)}
      # 將新數(shù)據(jù)重構到原字典數(shù)據(jù)
      a.setdefault(self.InstanceId,arry)
    return instanlist
if __name__ == "__main__":
  # 傳實例ID 列表進去
  clt= client(["i-11cy8adf2x"])
  res = clt.alis_main()
  print(res)
# 獲取的結果如下:
{'data': {'i-11cy8adf2x': {'InternetBandwidth': 0.0, 'cpu': 4.0, 'BandwidthOUT': 4}}}
# 解釋 獲取所有實例的 當前配置的帶寬值 當前占用的CPU% 當前占用的出口帶寬 kbps

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

希望本文所述對大家Python程序設計有所幫助。

相關文章

  • python實現(xiàn)簡單加密解密機制

    python實現(xiàn)簡單加密解密機制

    這篇文章主要為大家詳細介紹了python實現(xiàn)簡單加密解密機制,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2019-03-03
  • Python編程tkinter庫Canvas實現(xiàn)涂鴉顏色表及圍棋盤示例

    Python編程tkinter庫Canvas實現(xiàn)涂鴉顏色表及圍棋盤示例

    這篇文章主要為大家介紹了Python編程中如何使用tkinter庫Canvas來實現(xiàn)涂鴉,顏色表及圍棋盤的示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助
    2021-10-10
  • 詳解Python中with語句的用法

    詳解Python中with語句的用法

    這篇文章主要介紹了Python中with語句的用法,with語句的使用是Python學習過程當中的基礎知識,本文來自于IBM官方技術文檔,需要的朋友可以參考下
    2015-04-04
  • python基礎教程項目四之新聞聚合

    python基礎教程項目四之新聞聚合

    這篇文章主要為大家詳細介紹了python基礎教程項目四之新聞聚合,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2018-04-04
  • python的dict判斷key是否存在的方法

    python的dict判斷key是否存在的方法

    在本篇內容里小編給大家整理的是一篇關于python的dict判斷key是否存在的方法,有需要的朋友們可以參考下。
    2020-12-12
  • Python遠程創(chuàng)建docker容器的方法

    Python遠程創(chuàng)建docker容器的方法

    這篇文章主要介紹了Python遠程創(chuàng)建docker容器的方法,如果docker??ps找不到該容器,可以使用?docker?ps?-a查看所有的,然后看剛才創(chuàng)建的容器的STATUS是EXIT0還是EXIT1如果是1,那應該是有報錯,使用?docker?logs?容器id命令來查看日志,根據(jù)日志進行解決,需要的朋友可以參考下
    2024-04-04
  • Python的Pandas時序數(shù)據(jù)詳解

    Python的Pandas時序數(shù)據(jù)詳解

    這篇文章主要為大家詳細介紹了Pandas時序數(shù)據(jù),文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助
    2022-03-03
  • pycharm 批量修改變量名稱的方法

    pycharm 批量修改變量名稱的方法

    這篇文章主要介紹了pycharm 批量修改變量名稱的方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2019-08-08
  • Python參數(shù)的傳遞幾種情況實例詳解

    Python參數(shù)的傳遞幾種情況實例詳解

    這篇文章主要給大家介紹了關于Python參數(shù)的傳遞的相關資料,在Python中傳遞參數(shù)指的是函數(shù)或方法中的參數(shù)傳輸方式,文中給出了詳細的代碼示例,需要的朋友可以參考下
    2023-09-09
  • python簡單猜數(shù)游戲實例

    python簡單猜數(shù)游戲實例

    這篇文章主要介紹了python簡單猜數(shù)游戲,涉及Python隨機數(shù)及流程控制的相關技巧,需要的朋友可以參考下
    2015-07-07

最新評論