首页 > 代码库 > 使用python程序监控云服务器的带宽

使用python程序监控云服务器的带宽

将一些不重要的服务迁移到云服务上,有些下载什么的,为了防止带宽超了,python做了一个监控程序。用python3写的,由于和python2有些区别,特记录下来备查。

代码如下:

#this is for monitor qingcloud
# coding=utf-8
import base64
import hmac
import urllib
import urllib.parse
from hashlib import sha256
import urllib.request
import datetime
import urllib.parse

utc = datetime.datetime.utcnow()
print(utc)
utcbefore5 = utc - datetime.timedelta(minutes =5)
print(utcbefore5)
time_str = datetime.datetime.strftime(utc, "%Y-%m-%dT%H:%M:%SZ")
time_strbefore5 = datetime.datetime.strftime(utcbefore5, "%Y-%m-%dT%H:%M:%SZ")
time_stamp = urllib.parse.quote(time_str)
starttime = urllib.parse.quote(time_strbefore5)
print(time_stamp)
print(starttime)

beiqianmingchuanstr = ‘GET\n/iaas/\naccess_key_id=XXXXXXXXXXXXXXX&action=GetMonitor&end_time=‘ + time_stamp + ‘&meters.1=traffic&resource=eip-w1pculur&signature_method=HmacSHA256&signature_version=1&start_time=‘ + starttime +‘&step=5m&time_stamp=‘ + time_stamp + ‘&zone=pek1‘
beiqianmingchuan = str.encode(beiqianmingchuanstr)
#需要做签名串的请求字符
#beiqianmingchuan = b‘GET\n/iaas/\naccess_key_id=XXXXXXXXXXXXXXX&action=GetMonitor&end_time=2014-07-31T10%3A47%3A00.820Z&meters.1=traffic&resource=eip-w1pculur&signature_method=HmacSHA256&signature_version=1&start_time=2014-07-31T09%3A47%3A00.820Z&step=5m&time_stamp=2014-08-01T15%3A30%3A10Z&zone=pek1‘
#beiqianmingchuan = b‘GET\n/iaas/\naccess_key_id=XXXXXXXXXXXXXXX&action=RunInstances&count=1&image_id=precisesrvx64&instance_name=demo&instance_type=small_b&signature_method=HmacSHA256&signature_version=1&time_stamp=2013-08-27T14%3A30%3A10Z&version=1&vxnets.1=vxnet-0&zone=pek1‘
#计算签名串
h = hmac.new(b‘XXXXXXXXXXXXXXXXXXXX‘, digestmod=sha256)
h.update(beiqianmingchuan)
sign = base64.b64encode(h.digest()).strip()
signature = urllib.parse.quote_plus(sign)
print(signature)

#https://api.qingcloud.com/iaas/?action=GetMonitor&resource=eip-w1pculur&meters.1=traffic&start_time==2014-07-31T09%3A47%3A00.820Z&end_time=2014-07-31T10%3A47%3A00.820Z&step=5m&zone=pek1
#url = "https://api.qingcloud.com/iaas/?access_key_id=XXXXXXXXXXXXXXX&action=GetMonitor&resource=eip-w1pculur&meters.1=traffic&signature_method=HmacSHA256&signature_version=1&time_stamp=2014-08-01T15%3A30%3A10Z&start_time=2014-07-31T09%3A47%3A00.820Z&end_time=2014-07-31T10%3A47%3A00.820Z&step=5m&zone=pek1&signature=" + signature
url = ‘https://api.qingcloud.com/iaas/?access_key_id=XXXXXXXXXXXXXXX&action=GetMonitor&end_time=‘ + time_stamp + ‘&meters.1=traffic&resource=eip-w1pculur&signature_method=HmacSHA256&signature_version=1&start_time=‘ + starttime +‘&step=5m&time_stamp=‘ + time_stamp + ‘&zone=pek1&signature=‘ + signature
print(url)
geturl = urllib.request.urlopen(url).read()
print(geturl)