环境验证:一键安装包
pip3 install aliyun-python-sdk-core
pip3 install aliyunsdkcore
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2023/5/23 5:32 PM
# @Author : zk
# @File : sms.py
# @Software: PyCharm
import requests
import urllib
import logging
import os
import time
import datetime
import socket
import json
import hmac
import hashlib
import base64
import urllib.parse
# from time import time
import requests
import socket
from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.acs_exception.exceptions import ClientException
from aliyunsdkcore.acs_exception.exceptions import ServerException
from aliyunsdkcore.auth.credentials import AccessKeyCredential
from aliyunsdkcore.auth.credentials import StsTokenCredential
from aliyunsdkdysmsapi.request.v20170525.SendSmsRequest import SendSmsRequest
credentials = AccessKeyCredential('', '')
logging.basicConfig(level=logging.INFO,
filename='log/my_code.log',
filemode='a',
format='%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s'
)
def get_digest():
timestamp = str(round(time.time() * 1000))
#测试
secret = ''
#生产
#secret = ''
secret_enc = secret.encode('utf-8') # utf-8编码
string_to_sign = '{}\n{}'.format(timestamp, secret) # 字符串格式化拼接
string_to_sign_enc = string_to_sign.encode('utf-8') # utf-8编码
hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest() # HmacSHA256算法计算签名
sign = urllib.parse.quote_plus(base64.b64encode(hmac_code)) # Base64编码后进行urlEncode
# 返回时间戳和计算好的编码拼接字符串,后面直接拼接到Webhook即可
return f"×tamp={timestamp}&sign={sign}"
def get_system_info():
# 系统时间
dt = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
# 系统公网IP
ip = requests.get('http://ifconfig.me').text.strip()
# 内网IP
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(('8.8.8.8', 80))
local_ip = s.getsockname()[0]
s.close()
#系统load
system_load=os.popen("uptime|awk '{print $NF,$NF-1,$NF-2}'")
load=system_load.read().strip()
host_name=socket.gethostname()
return dt, ip, local_ip,load,host_name
def sed_dingding(title,Operational_behavior,code):
MSG = "**告警主题**:" + "\n" + title + "\n\n" \
"- 数据查询信息入下:" + "\n\n" "\n\n" \
">![]() 环境地址:**[一键安装包](https://www.zkong.com/)**\n\n" \
" >当前主机名:" + "\n" + get_system_info()[4] + "\n\n" \
" >当前服务器IP:" + "\n" + get_system_info()[1] + "\n" + get_system_info()[2] +"\n\n" \
" >当前系统load:" + "\n" + str(get_system_info()[3]) + "\n\n" \
" >系统操作行为:" + "\n" + Operational_behavior + "\n" + code + "\n\n" \
data = {
"msgtype": "markdown",
"markdown": {
"title": title,
"text": MSG,
},
"at": {
"atMobiles": [
"@15657199983" # 要@对象的手机号,在文本message里也需要加上@用户的手机号
],
"isAtAll": False # 是否要@所有人
}
}
# 机器人链接地址,发post请求 向钉钉机器人传递指令
#测试
webhook_url = 'https://oapi.dingtalk.com/robot/send?access_token='
#生产
#webhook_url = 'https://oapi.dingtalk.com/robot/send?access_token='
# 利用requests发送post请求
req = requests.post(webhook_url + get_digest(), json=data)
class SmsAlarm:
def __init__(self, phone, sign, template, ):
self.phonenumbers = phone
self.signname = sign
self.templatecode = template
def get_sms_code(self):
print(self.phonenumbers)
print(self.signname)
print(self.templatecode)
client = AcsClient(region_id='cn-hangzhou', credential=credentials)
request = SendSmsRequest()
request.set_accept_format('json')
request.set_PhoneNumbers(self.phonenumbers)
request.set_SignName(self.signname)
request.set_TemplateCode(self.templatecode)
response = client.do_action_with_exception(request)
# python2: print(response)
print(str(response, encoding='utf-8'))
# obj = SmsAlarm(, '', '')
# obj.get_sms_code()
class GetCode:
def __init__(self, url):
self.url = url
def get_url_code(self):
res = requests.get(self.url)
code = res.status_code
title="esl-business服务异常"
system_msg="正在重启,当前状态码为:"
#read old code
with open('log/status') as file:
files=str(file.read())
# old_code != new_code
if str(files) != str(12):
with open('log/status','w') as rw:
file_rw=rw.write(str(code))
logging.error("Program exception, restarting, sending restart alarm, current status code:{}".format(code))
logging.info("Stop for three minutes")
#res_zk = os.system("docker restart zk-refactor-esl-business >>/dev/null")
#钉钉通知
sed_dingding(title,system_msg,str(code))
#短信通知
Song = SmsAlarm(, '', '')
Song.get_sms_code()
else:
logging.info("The program is running normally. Current status code:{}".format(code))
if "__name__ == __main__":
obj = GetCode('http://:81/user/?loginType=1')
obj.get_url_code()