现在的云服务有很多服务都是后付费按使用量支付,使用的账户需要保障有一定的余额以防止业务因欠费而受到中断影响。
下面一段脚本可获取阿里云的可用额度:
# -*- coding:utf8 -*-
# from mns.mns_exception
# import MNSExceptionBase
try:
import httplib
except ImportError:
import http.client as httplib
import base64
from hashlib import sha1
import hmac, ssl
import json
import sys, datetime
import time
import urllib
import urllib.error
import urllib.parse
import urllib.request
import uuid
# 解决 访问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(object):
def __init__(self, access_id, access_secret, region, url, case=0):
self.access_id = access_id
self.access_secret = access_secret
self.RegionId = region
self.url = url
self.case = case
# #签名
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': '2017-12-14',
'AccessKeyId': self.access_id,
'SignatureVersion': '1.0',
'SignatureMethod': 'HMAC-SHA1',
'SignatureNonce': str(uuid.uuid1()),
}
if self.case == 1:
parameters['TimeStamp'] = timestamp
else:
parameters['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)
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, access_id, access_secret, region, url, case=0):
super().__init__(access_id, access_secret, region, url, case)
def DescribeInstanceMonitorData(self):
action_dict = {"Action": "QueryAccountBalance", "RegionId": self.RegionId, 'BillingCycle': '2018-08'}
result = self.do_action(action_dict)
return result
if __name__ == "__main__":
a = client('AccessKey ID', 'AccessKey', 'cn-beijing', 'https://business.aliyuncs.com')
b = a.DescribeInstanceMonitorData()['Data']['AvailableAmount']
print(b)
以下是微信消息发送的脚本:
#coding=utf8
import itchat
from flask import Flask,request
itchat.auto_login(enableCmdQR=2)
itchat.get_chatrooms(update=True)
group = itchat.search_chatrooms(name='阿里云费用……自定义群名')
print(group)
toUserName = group[0]['UserName']
app = Flask(__name__)
@app.route("/wx/sendMessage")
def send_wechat_message():
message = request.args.get('message')
#test_message = request.args.get('test_message')
itchat.send(message, toUserName=toUserName)
return 'message sent successfully'
if __name__ == '__main__':
app.run(host='0.0.0.0', port='8888')