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
python3 获取阿里云ECS 实例及监控的方法的更多相关文章
- 阿里云ECS 实例Centos7系统磁盘扩容
需求:一台阿里云的数据盘磁盘空间不足,需要扩容,我这里只有一个主分区,ext4文件系统. 因为磁盘扩容场景不同,阿里云的文档比较全面一些,所以先奉上阿里云的文档,下面开始我的操作步骤: 1.登录控制台 ...
- 【转载】阿里云ECS服务器监控资源使用情况
在阿里云Ecs服务器运维过程中,无论是Centos系统还是Windows系统,有时候我们需要监控分析最新的服务器资源利用率等运行情况,例如最近3个小时CPU使用率情况.内存使用率.网络流入带宽.网络流 ...
- 使用jvisualvm远程监控tomcat(阿里云ECS)
写在前面: 使用jvisualvm远程监控tomcat(阿里云ECS),连接是报错:service:jmx:rmi:////jndi/rmi:IP:端口// 连接到 IP:端口,网上找了很多资料, ...
- 阿里云ECS搭建开源跳板机jumpserver无法获取验证邮件的问题及解决办法
这段时间自己在阿里云上搭建了jumpserver3.0,在安装过程中需要输入邮箱smtp地址,输入之后会有一封验证邮件的,但是在阿里云ECS服务器上却无法收到邮件.查阅了阿里云官方的说明: 为什么无法 ...
- 在阿里云ECS CentOS7上部署基于MongoDB+Node.js的博客
前言:这是一篇教你如何在阿里云的ECS CentOS 7服务器上搭建一个个人博客的教程,教程比较基础,笔者尽可能比较详细的把每一步都罗列下来,包括所需软件的下载安装和域名的绑定,笔者在此之前对Linu ...
- Mac电脑 阿里云ECS(ContentOS) Apache+vsftpd+nodejs+mongodb建站过程总结
简介:我这里采用的阿里云免费提供的6个月ECS服务器:制作了一个简单的爬虫程序:里面很多功能还么做:搜索里面功能回去的数据未做处理会崩溃(大家不要点搜索功能):地址:http://loldragon. ...
- 不服跑个分:ARM鲲鹏云服务器实战评测——华为云鲲鹏KC1实例 vs. 阿里云G5实例【华为云技术分享】
原文链接:https://m.ithome.com/html/444828.htm 今年一月份,华为正式发布了鲲鹏920数据中心高性能处理器,该处理器兼容ARM架构,采用7纳米制造,最高支持64核,主 ...
- [转帖]华为鲲鹏云服务器实战:华为云鲲鹏KC1实例 vs. 阿里云G5实例
鲲鹏云服务器实战:华为云鲲鹏KC1实例 vs. 阿里云G5实例 https://m.ithome.com/html/444828.htm 2019-09-12 15:25IT之家 (阿迷) 今年一月份 ...
- 阿里云ECS(linux)磁盘满触发的mysql的表异常修复案例
阿里云ECS(linux)磁盘满触发的mysql的表异常修复案例 阿里云技术支持:完颜镇江 问题现象: 磁盘空间满了,第一想到的就是删除无用的服务日志或者升级数据盘. 通常是使用du –sh去分析目录 ...
随机推荐
- iOS基础 - 手势识别 与 手势说明
一.使用手势识别的四个步骤 1> 实例化手势识别 - (id)initWithTarget:(id)target action:(SEL)action; 2> 设置手势识别属性 3> ...
- 10-18 noip提高组模拟赛(codecomb)T1倍增[未填]
T1只想到了找环,> <倍增的思想没有学过,所以看题解看得雨里雾里的(最近真的打算学一下! 题目出的挺好的,觉得noip极有可能出现T1T2T3,所以在此mark 刚开始T1以为是模拟,还 ...
- nginx 重定向到index.php
location /keywords { index index.php; try_files $uri $uri/ /keywords/i ...
- AppBox_v3.0
AppBox_v2.0完整版免费下载,暨AppBox_v3.0正式发布! AppBox 是基于 FineUI 的通用权限管理框架,包括用户管理.职称管理.部门管理.角色管理.角色权限管理等模块. Ap ...
- wxWidgets的安装编译、相关配置、问题分析处理
wxWidgets的安装编译.相关配置.问题分析处理 一.介绍部分 (win7 下的 GUI 效果图见 本篇文章的最后部分截图2张) wxWidgets是一个开源的跨平台的C++构架库(framewo ...
- NHibernate Session-per-request and MiniProfiler.NHibernate
NHibernate Session-per-request and MiniProfiler.NHibernate 前言 1.本文以mvc3为例,借鉴开源项目 NerdDnner项目完成nhiber ...
- LoadTest中内存和线程Troubleshooting实战
LoadTest中内存和线程Troubleshooting实战 在端午节放假的三天中,我对正在开发的Service进行了LoadTest,尝试在增大压力的条件下发现问题. 该Service为独立进程的 ...
- 采用SOLR进行全文索引的完整解决方案,设计图
- 深入浅出 ThreadLocal(一)
本文参考http://lavasoft.blog.51cto.com/62575/51926/,对其中的程序进行了改写 一.概述 ThreadLocal是什么呢?其实ThreadLocal并非是一个线 ...
- C#新功能--命名参数与可选参数
C#新功能--命名参数与可选参数 可能是篇幅太短了,又被打入冷宫了.先重发一篇加上可选参数.本来不想加这个呢,因为可选参数可能大家用的会多点.其实这 两个在VB中早就有了,在C#中,只有在.net4以 ...