Monitor data in zabbix and return errors to DingTalk for review

### Create a group chat in DingTalk (students in the same group create a group chat) and add a custom robot to the group

1. Access custom services through custom webhook

image.png

 
webhook: Remember the address of the webhook
Security settings: Set up signature. Only the message content containing the signature will be sent by the robot.

2. Configure DingTalk alarm script

#### **Install python dependency module python-requests**

```

yum  install python3 python3-requests

#### Configure DingTalk alarm configuration script zabbix_ding.conf 

##### First create the zabbix_ding.conf file in the creation directory /etc/zabbix/


[root@qfedu ~]# vim /etc/zabbix/zabbix_ding.conf
[config]
log_path=/var/log/zabbix/zabbix_ding.log
webhook=https://oapi.dingtalk.com/robot/send?access_token=c1d11ecf6704f008eb25de644ed5cead752c065c0d11f9f89b58273cf0c78a96
secret=SECc26e5bc55c64d454f15a8bdcce6825b7e5bb4f6fecc38025d2845837415192d7

##### Create the DingTalk alarm log file zabbix_ding.log in the directory /var/log/zabbix
 

[root@qfedu ~]# touch /var/log/zabbix/zabbix_ding.log 

##### Set ownership of the DingTalk alarm log file zabbix_ding.log

    [root@qfedu ~]# chown zabbix.zabbix /var/log/zabbix/zabbix_ding.log 

#### **Configure DingTalk alarm execution script dingding.py**

##### Configure the path of the alarm script in zabbix_server.conf

vim /etc/zabbix/zabbix_server.conf


Configure the path of the alert script in zabbix_server.conf
# AlertScriptsPath=/usr/lib/zabbix/alertscripts
I modified it here a>
AlertScriptsPath=/usr/lib/zabbix/alertscripts
 

##### Contents of the script dingding.py executed in the /usr/lib/zabbix/alertscripts directory

# cd /usr/lib/zabbix/alertscripts
# vim dingding.py
以下内容添加至dingding.py内
#!/usr/bin/env python3
# coding:utf8
#
import configparser
import os
import time
import hmac
import hashlib
import base64
import urllib.parse
import requests
import json
import sys

config = configparser.ConfigParser()
config.read('/etc/zabbix/zabbix_ding.conf', encoding='utf-8')
log_path = config.get('config', 'log_path')
api_url = config.get('config', 'webhook')
api_secret = config.get('config', 'secret')
log_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())


# 钉钉机器人文档说明
# https://ding-doc.dingtalk.com/doc#/serverapi2/qf2nxq
def get_timestamp_sign():
    timestamp = str(round(time.time() * 1000))
    secret = api_secret
    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 timestamp, sign

# 获取加签后的链接
def get_signed_url():
    timestamp, sign = get_timestamp_sign()
    webhook = api_url + "&timestamp=" + timestamp + "&sign=" + sign
    return webhook

# 定义消息模式
def get_webhook(mode):
    if mode == 0:  # only 关键字
        webhook = api_url
    elif mode == 1 or mode == 2:  # 关键字和加签 或 # 关键字+加签+ip
        webhook = get_signed_url()
    else:
        webhook = ""
        print("error! mode:   ", mode, "  webhook :  ", webhook)
    return webhook


def get_message(text, user_info):
    # 和类型相对应,具体可以看文档 :https://ding-doc.dingtalk.com/doc#/serverapi2/qf2nxq
    # 可以设置某个人的手机号,指定对象发送
    message = {
        "msgtype": "text",  # 有text, "markdown"、link、整体跳转ActionCard 、独立跳转ActionCard、FeedCard类型等
        "text": {
            "content": text  # 消息内容
        },
        "at": {
            "atMobiles": [
                user_info,
            ],
            "isAtAll": False  # 是否是发送群中全体成员
        }
    }
    return message


# 消息发送日志
def log(info):
    if os.path.exists(log_path):
        log_file = open(log_path, "a+")
    else:
        log_file = open(log_path, "w+")
    log_file.write(info)


def send_ding_message(text, user_info):
    # 请求的URL,WebHook地址
    # 主要模式有 0 : 关键字 1:# 关键字 +加签 3:关键字+加签+IP
    webhook = get_webhook(1)
    # 构建请求头部
    header = {
        "Content-Type": "application/json",
        "Charset": "UTF-8"
    }
    # 构建请求数据
    message = get_message(text, user_info)
    # 对请求的数据进行json封装
    message_json = json.dumps(message)
    # 发送请求
    info = requests.post(url=webhook, data=message_json, headers=header).json()
    code = info["errcode"]
    errmsg = info["errmsg"]
    if code == 0:
        log(log_time + ":消息已发送成功 返回信息:%s %s\n" % (code, errmsg))
    else:
        log(log_time + ":消息发送失败 返回信息:%s %s\n" % (code, errmsg))
        print(log_time + ":消息发送失败 返回信息:%s %s\n" % (code, errmsg))
        exit(3)


if __name__ == "__main__":
    text = sys.argv[3]
    user_info = sys.argv[1]
    send_ding_message(text, user_info)

##### Set ownership of script directory
 

chown -R zabbix.zabbix /usr/lib/zabbix/alertscripts/

##### Test after giving x permission to script

chmod +x dingding.py 
./dingding.py  user subject mesages

### Configure script alarm

#### Create media

Alert-->Media-->Create media type

##### Alarm media type


 

{ALERT.SENDTO}
{ALERT.SUBJECT}
{ALERT.MESSAGE}

##### Message template

The following message template will automatically populate

#### Add alarm media for users

#### Create action


主题:服务器报警
消息:
告警主机:{HOST.NAME}
告警地址:{HOST.IP}
监控项目:{ITEM.NAME}
监控取值:{ITEM.LASTVALUE}
告警等级:{TRIGGER.SEVERITY}
当前状态:{TRIGGER.STATUS}
告警信息:{TRIGGER.NAME}
告警时间:{EVENT.DATE} {EVENT.TIME}
事件ID:{EVENT.ID}
```

```
主题:服务器已恢复
消息:
告警主机:{HOST.NAME}
告警地址:{HOST.IP}
监控项目:{ITEM.NAME}
监控取值:{ITEM.LASTVALUE}
告警等级:{TRIGGER.SEVERITY}
当前状态:{TRIGGER.STATUS}
告警信息:{TRIGGER.NAME}
告警时间:{EVENT.DATE} {EVENT.TIME}
事件ID:{EVENT.ID}
```

Guess you like

Origin blog.csdn.net/weixin_69654831/article/details/134429821
Recommended