温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

python实现监控阿里云账户余额功能

发布时间:2020-10-09 21:08:07 来源:脚本之家 阅读:276 作者:愤怒的苹果ext 栏目:开发技术

背景

由于阿里云oss,cdn消耗钱的速度比较快,在不知道的情况下,服务就被停了,影响比较大。所以想做个监控。百度一下阿里云账户余额 api 还真有;于是开启了踩坑之路。

查阅资料创建accessKeyId和accessKeySecret

  • 官方文档(感觉并不细致) https://help.aliyun.com/document_detail/87997.html?spm=a2c6h.13066369.0.0.59e4581eaxXH1O
  • sdk https://developer.aliyun.com/sdk?spm=5176.12818093.resource-links.dsdk_platform.488716d022QXo0
  • 看了官方文档后还是有点懵逼,后面Google了这个关键字QueryAccountBalanceRequest才看到真正的样例代码https://developer.aliyun.com/ask/132002(感觉这块资料很少呀,aliyun-python-sdk-bssopenapi居然没写在sdk安装列表里面,在社区找到的)。
  • 创建accessKeyId,鼠标悬停到右上角


python实现监控阿里云账户余额功能
python实现监控阿里云账户余额功能

撸码阶段

要安装的依赖

sudo pip install aliyun-python-sdk-core  -i https://mirrors.aliyun.com/pypi/simple/
sudo pip install  aliyun-python-sdk-bssopenapi -i https://mirrors.aliyun.com/pypi/simple/

from aliyunsdkcore import client
from aliyunsdkbssopenapi.request.v20171214 import QueryAccountBalanceRequest
from aliyunsdkcore.profile import region_provider
# 检查账户余额
def check_account(name, accessKeyId, accessKeySecret, valve, notify_emails):
  region_provider.add_endpoint('BssOpenApi', 'cn-hangzhou', 'business.aliyuncs.com')
  clt = client.AcsClient(accessKeyId, accessKeySecret, 'cn-hangzhou')
  request = QueryAccountBalanceRequest.QueryAccountBalanceRequest()
  request.set_accept_format("JSON")
  result = clt.do_action_with_exception(request)
  print(result)

下面是我封装的检查账户余额,如果低于阀值就给要通知的人发邮件。 monitor_balance.py

# -*-coding: UTF-8 -*-
'''
监控阿里云账户余额
zhouzhongqing
2019年12月14日20:21:11
sudo pip install aliyun-python-sdk-core  -i https://mirrors.aliyun.com/pypi/simple/
sudo pip install  aliyun-python-sdk-bssopenapi -i https://mirrors.aliyun.com/pypi/simple/
https://developer.aliyun.com/ask/132002
'''
import os
import time
import sched
import smtplib
from email.mime.text import MIMEText
from email.header import Header
from aliyunsdkcore import client
from aliyunsdkbssopenapi.request.v20171214 import QueryAccountBalanceRequest
from aliyunsdkcore.profile import region_provider
import json
from decimal import Decimal
# qq邮箱smtp服务器
host_server = 'smtp.qq.com'
# sender_qq为发件人的qq号码
sender_qq = '1030907690@qq.com'
# pwd为qq邮箱的授权码
pwd = 'xxxxxx'
# 发件人的邮箱
sender_qq_mail = '1030907690@qq.com'
# 第一个参数确定任务的时间,返回从某个特定的时间到现在经历的秒数
# 第二个参数以某种人为的方式衡量时间
schedule = sched.scheduler(time.time, time.sleep);
def send_mail(receiver, name, balance, valve):
  # 收件人邮箱
  # receiver = '1030907690@qq.com'
  # 邮件的正文内容
  mail_content = '您好,目前账户%s,余额为%s,低于阀值%s,请知悉!' % (name, balance, valve)
  # 邮件标题
  mail_title = '%s余额监控通知邮件' % (name)
  # ssl登录
  smtp = smtplib.SMTP_SSL(host_server)
  # set_debuglevel()是用来调试的。参数值为1表示开启调试模式,参数值为0关闭调试模式
  smtp.set_debuglevel(0)
  smtp.ehlo(host_server)
  smtp.login(sender_qq, pwd)
  msg = MIMEText(mail_content, "plain", 'utf-8')
  msg["Subject"] = Header(mail_title, 'utf-8')
  msg["From"] = sender_qq_mail
  msg["To"] = receiver
  smtp.sendmail(sender_qq_mail, receiver, msg.as_string())
  smtp.quit()
#解析配置
def parse_account():
  f = open("monitor.json")
  lines = f.read()
  data = json.loads(lines)
  f.close()
  return data
# 检查账户余额
def check_account(name, accessKeyId, accessKeySecret, valve, notify_emails):
  region_provider.add_endpoint('BssOpenApi', 'cn-hangzhou', 'business.aliyuncs.com')
  clt = client.AcsClient(accessKeyId, accessKeySecret, 'cn-hangzhou')
  request = QueryAccountBalanceRequest.QueryAccountBalanceRequest()
  request.set_accept_format("JSON")
  result = clt.do_action_with_exception(request)
  # print(result)
  res_json = json.loads(str(result, encoding="utf-8"))
  print(res_json)
  if res_json is not None and res_json["Code"] == "200":
    availableAmount = res_json["Data"]["AvailableAmount"]
    if Decimal(availableAmount) < Decimal(valve):
      print("%s低于阀值 " % name)
      notify_email_arr = notify_emails.split(",")
      for email in notify_email_arr:
        send_mail(email, name, availableAmount, valve)
def start_check():
  try:
    data = parse_account();
    for item in data:
      print("检查%s" % item["name"])
      check_account(item["name"], item["accessKeyId"], item['accessKeySecret'], item['valve'],
             item['notifyEmail'])
    # send_mail("1030907690@qq.com","恭喜你888","50","100")
  except Exception as e:
    print("program error %s " % e)
  finally:
    print("finally print!")
def perform_command(cmd, inc):
  # 安排inc秒后再次运行自己,即周期运行
  schedule.enter(inc, 0, perform_command, (cmd, inc));
  os.system(cmd);
  start_check();
def timming_exe(cmd, inc=60):
  # enter用来安排某事件的发生时间,从现在起第n秒开始启动
  schedule.enter(inc, 0, perform_command, (cmd, inc))
  # 持续运行,直到计划时间队列变成空为止
  schedule.run()
if __name__ == '__main__':
  print("start")
  print("show time after 60 seconds:");
  #timming_exe("echo %time%", 60); # 每间隔多少秒执行
  timming_exe("date", 60); # 每间隔多少秒执行
  print("end")
'''
AvailableAmount	String	可用额度
MybankCreditAmount	String	网商银行信用额度
AvailableCashAmount	String	现金余额
Currency	String	币种。取值范围:CNY:人民币,USD:美元,JPY:日元
CreditAmount	String	信控余额
'''
  • 还有个json文件配置monitor.json
  • 里面分别代表的是名称,发起邮件通知账户余额阀值,id,密钥,通知的邮箱(可以多个,逗号,分割)。
[{"name":"恭喜你888","valve": "100","accessKeyId":"xxx","accessKeySecret":"xxx","notifyEmail":1030907690@qq.com}]

运行效果


python实现监控阿里云账户余额功能
python实现监控阿里云账户余额功能

如果是正式环境部署的话可以用这个命令,可以后台运行,日志输出到 nohup.out:

nohup python -u monitor_balance.py > nohup.out 2>&1 &

 总结

以上所述是小编给大家介绍的python实现监控阿里云账户余额功能,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对亿速云网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI