侯体宗的博客
  • 首页
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

Python3编程实现获取阿里云ECS实例及监控的方法

Python  /  管理员 发布于 7年前   176

本文实例讲述了Python3编程实现获取阿里云ECS实例及监控的方法。分享给大家供大家参考,具体如下:

#!/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# 解决 访问ssl网站证书的问题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'    #监控获取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  # 构建除共公参数外的所有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 区域    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):    '''    构造实例监控序列函数    '''    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):    '''    构建实例配置查询函数    '''    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}    # 调用所有符合条件的实例配置数据    for i in range(0,listarry):      self.InstanceId = res["Instances"]["Instance"][i]["InstanceId"]      BandwidthOUT = res["Instances"]["Instance"][i]["InternetMaxBandwidthOut"]      # 调用计算该实例的监控数据      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"]      # 对该实例数据生成字典      arry = {"BandwidthOUT":BandwidthOUT,"cpu":cpu/len(data),"InternetBandwidth":InternetBandwidth/len(data)}      # 将新数据重构到原字典数据      a.setdefault(self.InstanceId,arry)    return instanlistif __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数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总》

希望本文所述对大家Python程序设计有所帮助。


  • 上一条:
    Python 中 Virtualenv 和 pip 的简单用法详解
    下一条:
    Python绑定方法与非绑定方法详解
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 在python语言中Flask框架的学习及简单功能示例(0个评论)
    • 在Python语言中实现GUI全屏倒计时代码示例(0个评论)
    • Python + zipfile库实现zip文件解压自动化脚本示例(0个评论)
    • python爬虫BeautifulSoup快速抓取网站图片(1个评论)
    • vscode 配置 python3开发环境的方法(0个评论)
    • 近期文章
    • 在windows10中升级go版本至1.24后LiteIDE的Ctrl+左击无法跳转问题解决方案(0个评论)
    • 智能合约Solidity学习CryptoZombie第四课:僵尸作战系统(0个评论)
    • 智能合约Solidity学习CryptoZombie第三课:组建僵尸军队(高级Solidity理论)(0个评论)
    • 智能合约Solidity学习CryptoZombie第二课:让你的僵尸猎食(0个评论)
    • 智能合约Solidity学习CryptoZombie第一课:生成一只你的僵尸(0个评论)
    • 在go中实现一个常用的先进先出的缓存淘汰算法示例代码(0个评论)
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(95个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2016-11
    • 2018-04
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2022-01
    • 2023-07
    • 2023-10
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客