prometheus使用企业微信告警

简介

因为alertmanager并没有原生关于企业微信的告警插件,所以就想着使用python写一个脚本去接收alertmanager的webhook信息,然后发送到企业微信机器人

操作

首先思路很简单,就是配置alertmanager webhook的receiver,配置如下

1
2
3
4
receivers:
  - name: 'webhook'
    webhook_configs:
    - url: 'http://192.168.18.12:8080/connect'

之后使用脚本去接收,脚本如下

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
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