目前每个脚本中都有钉钉告警和获取服务器信息,为了减少编写鸡肋封装系统信息和告警信息,后续方便监控脚本去调用
config.ini
[DingTalk]
#生产
prod_webhook_url = https://oapi.dingtalk.com/robot/send?access_token=94790bbfa97ccbab8855d241bacf5b1d7ed868afd4d863e14f04b04cd8d06
prod_secret=SEC859f1cefff0c3c20231c8743fdf524222d05c65ac8ffb4ec7da3ecfbe5257
#测试
dev_webhook_url= https://oapi.dingtalk.com/robot/send?access_token=39095661819c1b83433a52a59a827a87f84af8d14321919536e71e43f90488
dev_secret= SEC35942f08286efb1fc5b90ef46bd7d2e3063a1aad29b55b98e0e8519bd
mobile_number=
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2023/7/7 10:48
# @File : temp.py
# @Author : zk_linux
# @Software: PyCharm
# @Description:
import datetime
import json
import socket
import os
import requests
import configparser
import base64
import hmac
import urllib
import hashlib
import time
class GetDigest:
@staticmethod
def get_digest(secret):
# secret= "SEC359c7842f08286efb1fc5d8b7b90ef46bd7d2e3063a1aad29b55b98e0e8519bd"
timestamp = str(round(time.time() * 1000))
secret_enc = secret.encode('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}"
class GetSysyemInfo:
@staticmethod
def get_system_info():
"""
:return: system info dt, ip, local_ip, load, host_name
"""
system_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
host_name = socket.gethostname()
system_load = os.popen("uptime|awk '{print $NF,$NF-1,$NF-2}'")
load = system_load.read().strip()
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()
return system_time, host_name, load, local_ip ,ip
class DingTalkUrl:
def __init__(self, config_file):
self.config_file = config_file
def get_config(self):
"""
获取DingDing webhook
"""
config = configparser.ConfigParser()
config.read(self.config_file)
return config['DingTalk']
class Send_Dingding(GetSysyemInfo):
# system_info = GetSysyemInfo.get_system_info()
def __init__(self, *args, **kwargs):
'''
:param title,mobile_number
:param web_url,secret,msg
'''
self.args = args
self.kwargs = kwargs
def send_dingnding(self):
'''
:return: requests web_url,secret data
'''
MSG = (
"**告警主题**:" + "\n" + str(self.args[0]) + "\n\n"
" >当前时间:" + "\n" + str(GetSysyemInfo.get_system_info()[0]) + "\n\n"
" >当前主机名:" + "\n" + str(GetSysyemInfo.get_system_info()[1]) + "\n\n" \
" >当前系统load:" + "\n" + str(GetSysyemInfo.get_system_info()[2]) + "\n\n" \
" >当前服务器IP:" + "\n" + str(GetSysyemInfo.get_system_info()[3]) + "\n" + str(GetSysyemInfo.get_system_info()[4]) +"\n\n" \
" >详细信息:" + "\n" + self.kwargs['msg'] + "\n")
data={
"msgtype": "markdown",
"markdown": {
"title": str(self.args[0]),
"text": MSG,
},
"at": {
"atMobiles": [
self.args[1]
],
"isAtAll": False
}
}
headers = {
'Content-Type': 'application/json'
}
req = requests.post(self.kwargs['web_url'] + GetDigest.get_digest(self.kwargs['secret']),json=data,headers=headers)
- 脚本去调用并发送告警
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2023/7/6 17:15
# @File : emqx_mon.py
# @Author : zk_linux
# @Software: PyCharm
# @Description:
import os
import sys
from tmp import temp
os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
if "__name__ == __main__":
'''
调用告警模版
'''
webhook = temp.DingTalkUrl('/server/scripts/config.ini').get_config()
ding_msg = temp.Send_Dingding('集群环境01', webhook['mobile_number'], web_url=webhook['dev_webhook_url'],
secret=webhook['dev_secret'], msg="磁盘满了,快速清理吧")
ding_msg.send_dingnding()