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魔术方法详解
Feb 14 Python
浅谈Python中copy()方法的使用
May 21 Python
python图像处理之镜像实现方法
May 30 Python
Python实现的摇骰子猜大小功能小游戏示例
Dec 18 Python
Django框架教程之正则表达式URL误区详解
Jan 28 Python
Python数据分析之双色球统计两个红和蓝球哪组合比例高的方法
Feb 03 Python
用python3教你任意Html主内容提取功能
Nov 05 Python
python使用Turtle库绘制动态钟表
Nov 19 Python
深入了解Python枚举类型的相关知识
Jul 09 Python
基于matplotlib xticks用法详解
Apr 16 Python
Python-jenkins模块之folder相关操作介绍
May 12 Python
pandas按照列的值排序(某一列或者多列)
Dec 13 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
php单例模式的简单实现方法
2016/06/10 PHP
PHP设置images目录不充许http访问的方法
2016/11/01 PHP
php获取给定日期相差天数的方法分析
2017/02/20 PHP
cakephp2.X多表联合查询join及使用分页查询的方法
2017/02/23 PHP
php的无刷新操作实现方法分析
2020/02/28 PHP
jQuery 鼠标经过(hover)事件的延时处理示例
2014/04/14 Javascript
jquery处理json数据实例分析
2014/06/03 Javascript
jQuery siblings()用法实例详解
2016/04/26 Javascript
js监听键盘事件的方法_原生和jquery的区别详解
2016/10/10 Javascript
了解VUE的render函数的使用
2017/06/08 Javascript
NodeJS实现视频转码的示例代码
2017/11/18 NodeJs
JS中常用的消息框总结
2018/02/24 Javascript
vue父组件向子组件传递多个数据的实例
2018/03/01 Javascript
浅谈angular4.0中路由传递参数、获取参数最nice的写法
2018/03/12 Javascript
Vue环境搭建+VSCode+Win10的详细教程
2020/08/19 Javascript
记录Django开发心得
2014/07/16 Python
Python实现的爬虫刷回复功能示例
2018/06/07 Python
numpy matrix和array的乘和加实例
2018/06/28 Python
python 解决flask uwsgi 获取不到全局变量的问题
2019/12/22 Python
深入了解python列表(LIST)
2020/06/08 Python
基于Python 的语音重采样函数解析
2020/07/06 Python
html5 CSS过度-webkit-transition使用介绍
2013/07/02 HTML / CSS
如何在Canvas上的图形/图像绑定事件监听的实现
2020/09/16 HTML / CSS
纽约现代艺术博物馆商店:MoMA STORE(室内家具和杂货商品)
2016/08/02 全球购物
英国最全面的橄榄球联盟门票网站:Live Rugby Tickets
2018/10/06 全球购物
《雨霖铃》听课反思
2014/02/13 职场文书
幼儿园门卫岗位职责
2014/02/14 职场文书
一帮一活动总结
2014/05/08 职场文书
企业文化口号
2014/06/12 职场文书
2014党员民主评议个人总结
2014/09/10 职场文书
迎国庆横幅标语
2014/10/08 职场文书
工商行政处罚决定书
2015/06/24 职场文书
2016年党建工作简报
2015/11/26 职场文书
职场领导同事生日简短祝福语
2019/08/06 职场文书
php将xml转化对象的实例详解
2021/11/17 PHP
CSS精灵图的原理与使用方法介绍
2022/03/17 HTML / CSS