配置飞书机器人

zabbix接入飞书报警媒介_签名验证


zabbix接入飞书报警媒介_签名验证_02

zabbix接入飞书报警媒介_json_03

这里使用签名校验的方式创建飞书机器人


zabbix dashbord配置报警媒介,配置触发器,配置报警媒介附属到用户

zabbix接入飞书报警媒介_服务器_04

zabbix接入飞书报警媒介_json_05


zabbix接入飞书报警媒介_服务器_06

zabbix接入飞书报警媒介_json_07


编写feishu.py报警脚本

将该脚本放入zabbix server服务器/usr/lib/zabbix/alertscripts目录下

chmod +x feishu.py

feishu.py

#!/usr/bin/python3
# -*- coding: utf-8 -*-
import requests
import json
import sys
import os
import datetime
import base64
import hashlib
import hmac
from time import time


class FeiShuNotify:
    def __init__(self, subject, message, access_token=None):
        timestamp, sign = FeiShuNotify.encode(access_token)
        self.content = {'timestamp': timestamp, 'sign': sign}
        self.subject = subject
        self.message = message
        self.timestamp = timestamp
        self.sign = sign

    @staticmethod
    def encode(access_token):
        """
        飞书机器人webhook签名验证加密方法
        :return:
        """
        # timestamp = str(round(time() * 1000))
        timestamp = str(int(time()))
        # 拼接timestamp和secret
        string_to_sign = '{}\n{}'.format(timestamp, access_token)
        hmac_code = hmac.new(string_to_sign.encode("utf-8"), digestmod=hashlib.sha256).digest()
        # 对结果进行base64处理
        sign = base64.b64encode(hmac_code).decode('utf-8')
        return timestamp, sign

    def to_json(self):
        """
        飞书消息卡片返回格式
        :return:
        """
        return {
            "msg_type": "interactive",
            "card": {
                "config": {
                    "wide_screen_mode": True
                },
                "header": {
                    "title": {
                        "tag": "plain_text",
                        "content": self.subject
                    },
                    "template": "blue"
                },
                "elements": [
                    {
                        "tag": "markdown",
                        "content": self.message,
                    }
                ]
            },
            'timestamp': self.timestamp,
            'sign': self.sign
        }


def send_message(message, subject):
    """
    向飞书webhook url发送告警消息
    :param message:
    :param subject:
    :return:
    """
    payload_message = FeiShuNotify(subject, message, access_token="你自己的机器人token").to_json()
    headers = {
        'Content-Type': 'application/json'
    }

    response = requests.request("POST",
                                "你自己的机器人webhook url",
                                headers=headers, data=json.dumps(payload_message))
    return response


if __name__ == '__main__':
    text = sys.argv[1]
    subject = sys.argv[3]
    send_message(text, subject)


实现效果

zabbix接入飞书报警媒介_签名验证_08