使用钉钉机器人实现Zabbix报警信息推送的python脚本

1.先安装Python3.9

[root@Zabbix6 ~]# yum install python39 -y

2.编辑文件/etc/zabbix/zabbix_server.conf
AlertScriptsPath=/usr/lib/zabbix/alertscripts
上面这行,取消注释

3.创建脚本文件

[root@Zabbix6 ~]# cd /usr/lib/zabbix/alertscripts/
[root@Zabbix6 alertscripts]# ls
[root@Zabbix6 alertscripts]# vim dingding.py

使用了python语言。
这里直接上源码

#!/usr/bin/python3.9
#coding:utf-8
import requests,json,sys,os,datetime
webhook1="https://oapi.dingtalk.com/robot/send?access_token="
access_token="911c1df9088888"  # 这里直接改成你机器人的token
webhook = webhook1 + access_token
user=sys.argv[1]
text=sys.argv[3]
data={
    "msgtype": "text",
    "text": {
        "content": text
    },  
    "at": {
        "atMobiles": [
            user
        ],  
        "isAtAll": False
    }   
}
headers = {'Content-Type': 'application/json'}
x=requests.post(url=webhook,data=json.dumps(data),headers=headers)
if os.path.exists("/var/log/zabbix/dingding.log"):
    f=open("/var/log/zabbix/dingding.log","a+")
else:
    f=open("/var/log/zabbix/dingding.log","w+")
f.write("\n"+"--"*30)
if x.json()["errcode"] == 0:
    f.write("\n"+str(datetime.datetime.now())+"    "+str(user)+"    "+"Send Success"+"\n"+str(text))
    f.close()
else:
    f.write("\n"+str(datetime.datetime.now()) + "    " + str(user) + "    " + "Send Fail" + "\n" + str(text))
    f.close()

4.对脚本添加执行权,再创建log文件并修改所有者

[root@Zabbix6 alertscripts]# chmod +x dingding.py 
[root@Zabbix6 alertscripts]# ll
总用量 4
-rwxr-xr-x. 1 root root 1232 12月  7 23:59 dingding.py
[root@Zabbix6 alertscripts]# touch /var/log/zabbix/dingding.log
[root@Zabbix6 alertscripts]# chown zabbix.zabbix /var/log/zabbix/dingding.log 

5.安装requests第三方python库

[root@Zabbix6 alertscripts]# pip3 install requests
WARNING: Running pip install with root privileges is generally not a good idea. Try `pip3 install --user` instead.
Collecting requests
  Downloading requests-2.28.1-py3-none-any.whl (62 kB)
     |████████████████████████████████| 62 kB 64 kB/s 
Collecting charset-normalizer<3,>=2
  Downloading charset_normalizer-2.1.1-py3-none-any.whl (39 kB)
Collecting idna<4,>=2.5
  Downloading idna-3.4-py3-none-any.whl (61 kB)
     |████████████████████████████████| 61 kB 8.2 kB/s 
Collecting certifi>=2017.4.17
  Downloading certifi-2022.9.24-py3-none-any.whl (161 kB)
     |████████████████████████████████| 161 kB 8.4 kB/s 
Collecting urllib3<1.27,>=1.21.1
  Downloading urllib3-1.26.13-py2.py3-none-any.whl (140 kB)
     |████████████████████████████████| 140 kB 15 kB/s 
Installing collected packages: charset-normalizer, idna, certifi, urllib3, requests
Successfully installed certifi-2022.9.24 charset-normalizer-2.1.1 idna-3.4 requests-2.28.1 urllib3-1.26.13

6.测试

[root@Zabbix6 alertscripts]# python3 dingding.py 189xxx(钉钉号) 主题 内容(内容里需要包含钉钉上确认的关键字)

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注