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


Posted in Python onAugust 18, 2017

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

#!/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网站证书的问题
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'
    #监控获取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 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数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总》

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

Python 相关文章推荐
python端口扫描系统实现方法
Nov 19 Python
使用Python中的线程进行网络编程的入门教程
Apr 15 Python
python压缩文件夹内所有文件为zip文件的方法
Jun 20 Python
python中实现数组和列表读取一列的方法
Apr 03 Python
python实现从文件中读取数据并绘制成 x y 轴图形的方法
Oct 14 Python
对PyQt5的输入对话框使用(QInputDialog)详解
Jun 25 Python
解决python super()调用多重继承函数的问题
Jun 26 Python
python对验证码降噪的实现示例代码
Nov 12 Python
Python全面分析系统的时域特性和频率域特性
Feb 26 Python
python GUI库图形界面开发之PyQt5结合Qt Designer创建信号与槽的详细方法与实例
Mar 08 Python
Django实现whoosh搜索引擎使用jieba分词
Apr 08 Python
用python读取xlsx文件
Dec 17 Python
浅谈django开发者模式中的autoreload是如何实现的
Aug 18 #Python
Python绑定方法与非绑定方法详解
Aug 18 #Python
python字典DICT类型合并详解
Aug 17 #Python
Python时间的精准正则匹配方法分析
Aug 17 #Python
Python实现运行其他程序的四种方式实例分析
Aug 17 #Python
python进阶_浅谈面向对象进阶
Aug 17 #Python
Python 比较两个数组的元素的异同方法
Aug 17 #Python
You might like
mysql_fetch_assoc和mysql_fetch_row的功能加起来就是mysql_fetch_array
2007/01/15 PHP
使用JavaScript创建新样式表和新样式规则
2016/06/14 PHP
发现的以前不知道的函数
2006/09/19 Javascript
基于jquery的一个OutlookBar类,动态创建导航条
2010/11/19 Javascript
Javascript异步编程的4种方法让你写出更出色的程序
2013/01/17 Javascript
Javascript之this关键字深入解析
2013/11/12 Javascript
js通过iframe加载外部网页的实现代码
2015/04/05 Javascript
js实现表单及时验证功能 用户信息立即验证
2016/09/13 Javascript
Javascript中arguments对象的详解与使用方法
2016/10/04 Javascript
第一次接触Bootstrap框架
2016/10/24 Javascript
javascript实现去除HTML标签的方法
2016/12/26 Javascript
详解react-router 4.0 下服务器如何配合BrowserRouter
2017/12/29 Javascript
Angularjs之ngModel中的值验证绑定方法
2018/09/13 Javascript
玩转vue的slot内容分发
2018/09/22 Javascript
微信小程序实现跑马灯效果
2020/10/21 Javascript
NodeJS实现同步的方法
2019/03/02 NodeJs
动态实现element ui的el-table某列数据不同样式的示例
2021/01/22 Javascript
[50:17]Newbee vs Serenity 2018国际邀请赛小组赛BO2 第二场 8.17
2018/08/18 DOTA
Python Tkinter基础控件用法
2014/09/03 Python
在Django中同时使用多个配置文件的方法
2015/07/22 Python
Python使用剪切板的方法
2017/06/06 Python
Python 自动刷博客浏览量实例代码
2017/06/14 Python
java字符串格式化输出实例讲解
2021/01/06 Python
详解pandas apply 并行处理的几种方法
2021/02/24 Python
html5中使用hotcss.js实现手机端自适配的方法
2020/04/23 HTML / CSS
印度尼西亚综合购物网站:Lazada印尼
2016/09/07 全球购物
美国在线奢侈品寄售商店:Luxury Garage Sale
2018/08/19 全球购物
销售业务实习自我鉴定
2013/09/23 职场文书
教师求职推荐信范文
2013/11/20 职场文书
母亲节演讲稿
2014/05/27 职场文书
学校食品安全责任书
2015/01/29 职场文书
三峡大坝导游词
2015/01/31 职场文书
2016秋季运动会前导词
2015/11/25 职场文书
js实现自动锁屏功能
2021/06/02 Javascript
React列表栏及购物车组件使用详解
2021/06/28 Javascript
解决redis批量删除key值的问题
2022/03/23 Redis