web code监控
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2023/7/4 14:00 # @Author : zk_linux # @File : monitoring_code.py # @Software: PyCharm # @Description: Monitoring verification code, SMS pin alarm import requests import urllib import logging import time import subprocess import datetime import json import hmac import hashlib import base64 import urllib.parse import socket import configparser 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('LTAI5tMZtgpcAPMvmbmJc', 'naFX7u8VtYlQty5BP6XRZWviV') logging.basicConfig(level=logging.INFO, # filename='../log/esl_business_code.log', filename='/server/scripts/log/esl_business_code.log', filemode='a', format='%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s' ) def get_digest(secret): timestamp = str(round(time.time() * 1000)) 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') hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest() sign = urllib.parse.quote_plus(base64.b64encode(hmac_code)) return f"×tamp={timestamp}&sign={sign}" def get_system_info(): os_date = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') public_net_ip = requests.get('http://ifconfig.me').text.strip() s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(('8.8.8.8', 80)) local_ip = s.getsockname()[0] s.close() host_name = socket.gethostname() return os_date, public_net_ip, local_ip, host_name class SendDingtalk: def __init__(self, webhook, secret, iphone_number, msg_title, msg_content): self.webhook = webhook self.secret = secret self.num = iphone_number self.msg_title = msg_title self.msg_content = msg_content def send_dingnding(self): MSG = "**告警主题**:" + "\n" + self.msg_title + "\n\n" \ " >当前主机名:" + "\n" + get_system_info()[3] + "\n\n" \ "> 当前时间:" + "\n" + get_system_info()[0] + "\n\n" \ " >当前服务器IP:" + "\n" + get_system_info()[1] + "(公)" + "\n" + get_system_info()[2] + "(私)" + "\n\n" \ "详细信息:" + "\n" + "\n" + str(self.msg_content) + "\n\n" \ data = { "msgtype": "markdown", "markdown": { "title": 'HK-集群01-验证码监控', "text": MSG, }, "at": { "atMobiles": [ "@83" ], "isAtAll": False } } request = requests.post(self.webhook + get_digest(self.secret), json=data) class WebCodeConfig: def __init__(self, config_file): self.config_file = config_file def web_code_config(self): config = configparser.ConfigParser() config.read(self.config_file) return config['Code'] def ding_taik_config(self): config = configparser.ConfigParser() config.read(self.config_file) return config['DingTalk'] def sms_config(self): config = configparser.ConfigParser() config.read(self.config_file) return config['sms'] class SmsAlarm: def __init__(self, phone, sign, template): self.phonenumbers = phone self.signname = sign self.templatecode = template def get_sms_code(self): 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) class RestartDocker: title = "" msg_content = "" sms = WebCodeConfig('config.ini').sms_config() send_sms = SmsAlarm(sms['phonenumbers'], sms['signname'], sms['templatecode']) @classmethod def restart_esl_business(cls): cls.title = "HK_集群01_重启esl-business通知" cls.msg_content = '验证码异常,当前esl-business容器状态Exited,正在启动.' res = subprocess.run(['docker restart zk-refactor-esl-business'], shell=True, stderr=subprocess.PIPE) cls.send_sms.get_sms_code() logging.info('Restart the esl-business container') if res.returncode != 0: cls.title = "HK_集群01_构建esl-business通知" cls.msg_content = '验证码异常,容器esl-business不存在,正在构建esl-business容器.' logging.error(f"Restart the zk-refactor-esl-business container failed, restart the state:{res.returncode}.") command = ( 'cd /usr/local/esl\n' './docker-compose up -d --build zk-refactor-esl-business >>/dev/null 2>&1 ' ) build_container = subprocess.run(command, shell=True, stdout=subprocess.PIPE) cls.send_sms.get_sms_code() logging.info("Build the zk-refactor-esl-business container") class MonitoringStatusCode: esl_business_status = 200 def __init__(self, *args): self.config = args def get_master_code_status(self): try: master_esl_business = requests.get(self.config[3]) if master_esl_business.status_code == self.esl_business_status: logging.info("Web is functioning properly") except requests.exceptions.RequestException as e: restart_cont = RestartDocker() restart_cont.restart_esl_business() ret = SendDingtalk(dingtalk['prod_webhook_url'], dingtalk['prod_secret'], dingtalk['mobile_number'], RestartDocker.title, RestartDocker.msg_content) ret.send_dingnding() logging.error(f'Error occurred while connecting to the web server: {str(e)}') if __name__ == '__main__': obj = WebCodeConfig('config.ini').web_code_config() dingtalk = WebCodeConfig('config.ini').ding_taik_config() res = MonitoringStatusCode( obj['mobile_phone_number'], obj['signature_name'], obj['template_code'], obj['master_monitor_address'] ) res.get_master_code_status()
[MySQL] master_host= master_port=3306 master_user=root master_password= slave_host= [DingTalk] #生产 prod_webhook_url = https://oapi.dingtalk.com/robot/send?access_token= prod_secret= #测试 dev_webhook_url= https://oapi.dingtalk.com/robot/send?access_token= dev_secret= mobile_number= [Redis] redis_master_host= redis_master_port= 6379 redis_master_password = zk123 redis_slave_host= [Code] mobile_phone_number = signature_name = template_code = master_monitor_address= slave_monitor_address= [sms] phonenumbers = signname = templatecode =