python實現監控阿里雲賬戶餘額功能
阿新 • • 發佈:2020-01-09
背景
由於阿里雲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,滑鼠懸停到右上角
擼碼階段
要安裝的依賴
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,'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 = '[email protected]' # pwd為qq郵箱的授權碼 pwd = 'xxxxxx' # 發件人的郵箱 sender_qq_mail = '[email protected]' # 第一個引數確定任務的時間,返回從某個特定的時間到現在經歷的秒數 # 第二個引數以某種人為的方式衡量時間 schedule = sched.scheduler(time.time,time.sleep); def send_mail(receiver,name,balance,valve): # 收件人郵箱 # receiver = '[email protected]' # 郵件的正文內容 mail_content = '您好,目前賬戶%s,餘額為%s,低於閥值%s,請知悉!' % (name,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,'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,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("[email protected]","恭喜你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,perform_command,(cmd,inc)); os.system(cmd); start_check(); def timming_exe(cmd,inc=60): # enter用來安排某事件的發生時間,從現在起第n秒開始啟動 schedule.enter(inc,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":[email protected]}]
執行效果
如果是正式環境部署的話可以用這個命令,可以後臺執行,日誌輸出到 nohup.out:
nohup python -u monitor_balance.py > nohup.out 2>&1 &
總結
以上所述是小編給大家介紹的python實現監控阿里雲賬戶餘額功能,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回覆大家的。在此也非常感謝大家對我們網站的支援!
如果你覺得本文對你有幫助,歡迎轉載,煩請註明出處,謝謝!