Bootstrap

Zabbix钉钉机器人告警

目录

一. 环境准备

二. Zabbix-Server端主机操作

三. Zabbix-web页面配置

四. 测试


 

一. 环境准备

检查时间同步!

本篇实验环境前提基于该Zabbix动作与媒介-CSDN博客博文配置的环境进行本篇告警实验

需要下载钉钉软件,登录--->创建内部群--->添加自定义机器人--->设置机器人名与加签--->完成创建 

 

 

二. Zabbix-Server端主机操作

 

1. 安装python依赖模块python-requests

[root@zabbix ~]# yum install -y python3 python3-requests python3-pip
[root@zabbix ~]# pip3 install requests

2. 配置钉钉告警配置脚本zabbix_ding.conf

首先在创建目录/etc/zabbix/创建zabbix_ding.conf 文件

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

其中webhooki和secret需要修改成你的钉钉机器人参数 

在目录/var/log/zabbix中创建钉钉告警日志文件zabbix_ding.log

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

设置钉钉告警日志文件zabbix_ding.log的所有权

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

3. 配置钉钉告警执行脚本dingding.py

在zabbix_server.conf中配置告警脚本的路径

[root@zabbix ~]# vim /etc/zabbix/zabbix_server.conf +565
AlertScriptsPath=/usr/lib/zabbix/alertscripts

 

在/usr/lib/zabbix/alertscripts目录中执行的脚本dingding.py的内容

 

[root@zabbix ~]# cd /usr/lib/zabbix/alertscripts
[root@zabbix alertscripts]# vim dingding.py
#将下述代码python脚本代码全部复制粘贴到本文件里
#!/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)

设置脚本目录的所有权

[root@zabbix alertscripts]# chown -R zabbix.zabbix /usr/lib/zabbix/alertscripts/

给脚本x权限后测试

[root@zabbix alertscripts]# chmod +x dingding.py
[root@zabbix alertscripts]# ./dingding.py  user subject mesages

 

注: 以下是常见问题解决办法:

1. 以下报错是/etc/zabbix/zabbix_ding.conf该文件配置参数有问题,仔细检查单词拼写。

[root@zabbix alertscripts]# ./dingding.py  user subject mesages
Traceback (most recent call last):
  File "/usr/lib64/python3.9/configparser.py", line 789, in get
    value = d[option]
  File "/usr/lib64/python3.9/collections/__init__.py", line 941, in __getitem__
    return self.__missing__(key)            # support subclasses that define __missing__
  File "/usr/lib64/python3.9/collections/__init__.py", line 933, in __missing__
    raise KeyError(key)
KeyError: 'webhook'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/lib/zabbix/alertscripts/./dingding.py", line 18, in <module>
    api_url = config.get('config', 'webhook')
  File "/usr/lib64/python3.9/configparser.py", line 792, in get
    raise NoOptionError(option, section)
configparser.NoOptionError: No option 'webhook' in section: 'config'

 2. 该问题是未进行时间同步,主机时间和正常的windows电脑时间不一致

[root@zabbix alertscripts]# ./dingding.py  user subject hello
2024-07-05 06:35:56:消息发送失败 返回信息:310000 description:机器人发送签名过期;solution:签名生成时间和发送时间请保持在 timestampms 以内;

解决办法:进行时间同步

sudo dnf install chrony
sudo systemctl enable --now chronyd
sudo systemctl restart chronyd

 

三. Zabbix-web页面配置

来到server端的web页面

1. 创建媒介

 

脚本名称就是前面创建编辑的脚本名称,脚本传输参数复制下述进行粘贴:

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

消息模板也可以自定义 

 

2. 测试 

 

 

3. 触发器添加告警动作

该监控监控项目和触发器是准备好的,你也可以自定义,或根据我另一篇博文添加Zabbix动作与媒介-CSDN博客 

 

 

 

4. 用户配置告警媒介

收件人一栏可以随便写,用不到。 

下图中的更新一点别忘记点,不让就每添加上

 

 

四. 测试

现在来到Agent端,即客户端,被监控主机web1上,192.168.226.29

查看nginx服务和端口是正常状态

[root@web1 ~]# ss -tnlp
State                Recv-Q                Send-Q                               Local Address:Port                                Peer Address:Port               Process                                                                                                                                                           
LISTEN               0                     4096                                       0.0.0.0:10050                                    0.0.0.0:*                   users:(("zabbix_agentd",pid=3878,fd=4),("zabbix_agentd",pid=3877,fd=4),("zabbix_agentd",pid=3876,fd=4),("zabbix_agentd",pid=3875,fd=4),("zabbix_agentd",pid=3874,fd=4),("zabbix_agentd",pid=3873,fd=4))
LISTEN               0                     511                                        0.0.0.0:80                                       0.0.0.0:*                   users:(("nginx",pid=4039,fd=6),("nginx",pid=4038,fd=6),("nginx",pid=4037,fd=6))                                                                                  
LISTEN               0                     128                                        0.0.0.0:22                                       0.0.0.0:*                   users:(("sshd",pid=825,fd=3))                                                                                                                                    
LISTEN               0                     4096                                          [::]:10050                                       [::]:*                   users:(("zabbix_agentd",pid=3878,fd=5),("zabbix_agentd",pid=3877,fd=5),("zabbix_agentd",pid=3876,fd=5),("zabbix_agentd",pid=3875,fd=5),("zabbix_agentd",pid=3874,fd=5),("zabbix_agentd",pid=3873,fd=5))
LISTEN               0                     511                                           [::]:80                                          [::]:*                   users:(("nginx",pid=4039,fd=7),("nginx",pid=4038,fd=7),("nginx",pid=4037,fd=7))                                                                                  
LISTEN               0                     128                                           [::]:22                                          [::]:*                   users:(("sshd",pid=825,fd=4))                                                                                                                                    

现在关停nginx服务

[root@web1 ~]# systemctl stop nginx
[root@web1 ~]# ss -tnlp
State                Recv-Q                Send-Q                               Local Address:Port                                Peer Address:Port               Process                                                                                                                                                           
LISTEN               0                     4096                                       0.0.0.0:10050                                    0.0.0.0:*                   users:(("zabbix_agentd",pid=3878,fd=4),("zabbix_agentd",pid=3877,fd=4),("zabbix_agentd",pid=3876,fd=4),("zabbix_agentd",pid=3875,fd=4),("zabbix_agentd",pid=3874,fd=4),("zabbix_agentd",pid=3873,fd=4))
LISTEN               0                     128                                        0.0.0.0:22                                       0.0.0.0:*                   users:(("sshd",pid=825,fd=3))                                                                                                                                    
LISTEN               0                     4096                                          [::]:10050                                       [::]:*                   users:(("zabbix_agentd",pid=3878,fd=5),("zabbix_agentd",pid=3877,fd=5),("zabbix_agentd",pid=3876,fd=5),("zabbix_agentd",pid=3875,fd=5),("zabbix_agentd",pid=3874,fd=5),("zabbix_agentd",pid=3873,fd=5))
LISTEN               0                     128                                           [::]:22                                          [::]:*                   users:(("sshd",pid=825,fd=4))  

耐心等待一会观察web监控页面的图形信息和问题告警,需要耐心一会,在钉钉中就会收到消息

  

此时回到客户端查看nginx端口是否开启

[root@web1 ~]# ss -tnlp
State                Recv-Q                Send-Q                               Local Address:Port                                Peer Address:Port               Process                                                                                                                                                           
LISTEN               0                     4096                                       0.0.0.0:10050                                    0.0.0.0:*                   users:(("zabbix_agentd",pid=3878,fd=4),("zabbix_agentd",pid=3877,fd=4),("zabbix_agentd",pid=3876,fd=4),("zabbix_agentd",pid=3875,fd=4),("zabbix_agentd",pid=3874,fd=4),("zabbix_agentd",pid=3873,fd=4))
LISTEN               0                     511                                        0.0.0.0:80                                       0.0.0.0:*                   users:(("nginx",pid=4385,fd=6),("nginx",pid=4384,fd=6),("nginx",pid=4383,fd=6))                                                                                  
LISTEN               0                     128                                        0.0.0.0:22                                       0.0.0.0:*                   users:(("sshd",pid=825,fd=3))                                                                                                                                    
LISTEN               0                     4096                                          [::]:10050                                       [::]:*                   users:(("zabbix_agentd",pid=3878,fd=5),("zabbix_agentd",pid=3877,fd=5),("zabbix_agentd",pid=3876,fd=5),("zabbix_agentd",pid=3875,fd=5),("zabbix_agentd",pid=3874,fd=5),("zabbix_agentd",pid=3873,fd=5))
LISTEN               0                     511                                           [::]:80                                          [::]:*                   users:(("nginx",pid=4385,fd=7),("nginx",pid=4384,fd=7),("nginx",pid=4383,fd=7))                                                                                  
LISTEN               0                     128                                           [::]:22                                          [::]:*                   users:(("sshd",pid=825,fd=4))  

 到此就成功配置好了。

;