Python3編程實(shí)現(xiàn)獲取阿里云ECS實(shí)例及監(jiā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)文章
python實(shí)現(xiàn)簡(jiǎn)單加密解密機(jī)制
這篇文章主要為大家詳細(xì)介紹了python實(shí)現(xiàn)簡(jiǎn)單加密解密機(jī)制,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-03-03Python編程tkinter庫(kù)Canvas實(shí)現(xiàn)涂鴉顏色表及圍棋盤示例
這篇文章主要為大家介紹了Python編程中如何使用tkinter庫(kù)Canvas來(lái)實(shí)現(xiàn)涂鴉,顏色表及圍棋盤的示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助2021-10-10python基礎(chǔ)教程項(xiàng)目四之新聞聚合
這篇文章主要為大家詳細(xì)介紹了python基礎(chǔ)教程項(xiàng)目四之新聞聚合,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-04-04Python遠(yuǎn)程創(chuàng)建docker容器的方法
這篇文章主要介紹了Python遠(yuǎn)程創(chuàng)建docker容器的方法,如果docker??ps找不到該容器,可以使用?docker?ps?-a查看所有的,然后看剛才創(chuàng)建的容器的STATUS是EXIT0還是EXIT1如果是1,那應(yīng)該是有報(bào)錯(cuò),使用?docker?logs?容器id命令來(lái)查看日志,根據(jù)日志進(jìn)行解決,需要的朋友可以參考下2024-04-04Python的Pandas時(shí)序數(shù)據(jù)詳解
這篇文章主要為大家詳細(xì)介紹了Pandas時(shí)序數(shù)據(jù),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來(lái)幫助2022-03-03