简介
因为alertmanager并没有原生关于企业微信的告警插件,所以就想着使用python写一个脚本去接收alertmanager的webhook信息,然后发送到企业微信机器人
操作
首先思路很简单,就是配置alertmanager webhook的receiver,配置如下
receivers:
- name: 'webhook'
webhook_configs:
- url: 'http://192.168.18.12:8080/connect'
之后使用脚本去接收,脚本如下
import requests
import logging
import falcon
import json
# 微信机器人链接
wechat_boot_url = ""
# 日志模块
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
fileHandler = logging.FileHandler('log.log', mode='w', encoding='UTF-8')
fileHandler.setLevel(logging.NOTSET)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fileHandler.setFormatter(formatter)
logger.addHandler(fileHandler)
# 处理从alertmanager接收过来的信息
def message_handler(message):
message = eval(message)
alerts = message["alerts"]
alert_message = []
# 多台机器的时候处理
for i in range(len(alerts)):
alert = alerts[i]
alert = eval(str(alert))
status = alert["status"]
labels = alert["labels"]
annotations = alert["annotations"]
startsAt = alert["startsAt"]
endsAt = alert["endsAt"]
alertname = eval(str(labels))["alertname"]
instance = eval(str(labels))["instance"]
status = eval(str(labels))["status"]
description = eval(str(annotations))["description"]
message = "------------------------------" + '\n' \
+ " 告警来了" + '\n' \
+ "------------------------------" + '\n' \
+ "状态: " + status + '\n' \
+ "告警名字: " + alertname + '\n' \
+ "告警实例: " + instance + '\n' \
+ "告警等级: " + status + '\n' \
+ "告警描述: " + description + '\n' \
+ "开始时间: " + startsAt + '\n' \
+ "结束时间: " + endsAt + '\n' \
+ "------------------------------"
alert_message.append(message)
return alert_message
# 发送到微信里的函数
def send_wechat(message):
headers = {'Content-Type': 'application/json;charset=utf-8'}
logger.debug(message)
body = {
"msgtype": "text",
"text": {
"content": message
}
}
print(str(body))
requests.post(wechat_boot_url, json.dumps(body), headers=headers)
# alertmanager post请求处理函数
class Connect(object):
def on_post(self, req, resp):
messages = req.stream.read()
logger.debug(messages)
try:
messages = str(bytes.decode(messages))
logger.debug(messages)
messages = message_handler(messages)
for i in range(len(messages)):
send_wechat(str(messages[i]))
except Exception as e:
logger.debug(e)
app = falcon.API()
connect = Connect()
app.add_route('/connect', connect)
wechat_boot_url = ""
定义了企业微信机器人的url
message_handler
是用来处理alertmanager发送过来的信息的
send_wechat
就是把格式化的信息发送到微信中
之后使用falcon框架去启动一个http服务
脚本使用下面命令启动
waitress-serve --port=8080 main:app
脚本github地址
https://github.com/bboysoulcn/wechatalert
最后说几句
国内的通信软件是真的不行,有一个机器人就很ok了,如果是telegram的话完全可以写一个牛逼的机器人去替你简单的管理服务器,什么重启等操作都可以
欢迎关注我的博客www.bboy.app
Have Fun