钉钉机器人zabbix报警
跳转到导航
跳转到搜索
安装Python3、相关包以及创建钉钉发送消息日志文件
#这个看你自己的情况 # 安装python3,脚本是基于Python3写的 yum install -y python3 # 安装pip,pip是python的包管理器 # 下载pip安装脚本 curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py # 运行安装脚本 sudo python3 get-pip.py # 安装puthon包 pip3 install configparser pip3 install requests # 创建钉钉发送日志文件路径 touch /var/log/zabbix/zabbix_ding.log chown zabbix.zabbix /var/log/zabbix/zabbix_ding.log
首先在钉钉群聊里添加一个自定义的机器人
并复制webhook的内容 如下面 创建新建群手加入 机器人就可得到
还有一个 安全设置 -- 加签 时得到
创建脚本
在zabbix服务端的alertscripts目录下新建一个python脚本
py3 Oct 2021
#pre config
# 查看zabbix的脚本默认路径,请注意使用您自己的zabbix_server.conf 类似这个样子
cat /etc/zabbix/zabbix_server.conf |grep AlertScriptsPath
### Option: AlertScriptsPath
# AlertScriptsPath=${datadir}/zabbix/alertscripts
AlertScriptsPath=/usr/lib/zabbix/alertscripts
添加配置文件zabbix_ding.conf,并将文件上传至/etc/zabbix/下(进入容器) 或者放在母机指定的mount的目录中 例如下面的py3 脚本 ding.py
[config]
# 日志文件
log_path=/var/log/zabbix/zabbix_ding.log
#钉钉机器人 webhook 值
webhook=https://oapi.dingtalk.com/robot/send?access_token=b3e6fa0f410e7ced04c81680f036xxxx
# 安全设置 -- 加签 时得到
secret=SEC64d20b4e9d2e2677f7aa01d2a7c2f9xxxx
cat ding.py
#!/usr/bin/env python3
# coding:utf8
#pwd docker目录 zbx_env/usr/lib/zabbix/alertscripts
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 + "×tamp=" + 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)
zbx_env/usr/lib/zabbix/alertscripts
alertscripts]# chmod +x ding.py
https://www.jianshu.com/p/a3c62eb71ae3
py2 2018
#!/usr/bin/python
#-*- coding: utf-8 -*-
# Author evan this one f17 cat /usr/lib/zabbix/alertscripts/ding.py
import requests
import json
import sys
import os
headers = {'Content-Type': 'application/json;charset=utf-8'}
api_url="https://oapi.dingtalk.com/robot/send?access_token=709ea577d2cd4f8e6975be37fc177307b38fc1d32c322dded89723d3ff58e"
def msg(text):
json_text= {
"msgtype": "text",
"text": {
"content": text
},
"at": {
"atMobliles": [
"18520124378","18578776813"
],
"isAtAll": False
}
}
print requests.post(api_url,json.dumps(json_text),headers=headers).content
if __name__ == '__main__':
text = sys.argv[1]
msg(text)
#参考一下以前的爬虫 相关参考请看 自定义机器人
Web端配置
我没写详情 请见 状态 已启用 才行 see also参考中的 Zabbix5.0使用钉钉机器人报警 WEB界面配置详情good 发送消息给用户群组: Zabbix administrators 通过 所有介质 已启用 动作要选择为 触发器示警度 大于等等 警告 用户 --> 报警媒介--> 收件人 可以填写 ding手机号码 或者 dingding号 --> 被填写的会@ 报警媒介类型 最右边 测试
troubleshooting
trouble
readonly 是docker-compose 配置 直接去母机
zbx_env/usr/lib/zabbix/alertscripts
alertscripts]# chmod +x ding.py
Media type test failed.
Cannot execute command "/usr/lib/zabbix/alertscripts/ding.py": [2] No such file or directory
有时重启不成功
zabbix_zabbix-server_1
关掉机器人中的 自定义关键词
// 消息内容中不包含任何关键词
{
"errcode":310000,
"errmsg":"keywords not in content"
}
# python3 ding.py user subject message
2021-10-19 11:25:09:消息发送失败 返回信息:310000 keywords not in content, more: [https://ding-doc.dingtalk.com/doc#/serverapi2/qf2nxq]
/usr/lib/alertscripts # vi /etc/zabbix/zabbix_ding.conf
/usr/lib/alertscripts # python3 ding.py user subject message
https://developers.dingtalk.com/document/robots/custom-robot-access?spm=ding_open_doc.document.0.0.7f875e591WwbnS#topic-2026027
自己笨蛋 加多了一行只有 secret的字符 所以格式不对
usr/lib/alertscripts # python3 ding.py user subject message
Traceback (most recent call last):
File "ding.py", line 16, in <module>
config.read('/etc/zabbix/zabbix_ding.conf', encoding='utf-8')
File "/usr/lib/python3.8/configparser.py", line 697, in read
self._read(fp, filename)
File "/usr/lib/python3.8/configparser.py", line 1113, in _read
raise e
configparser.ParsingError: Source contains parsing errors: '/etc/zabbix/zabbix_ding.conf'
[line 4]: 'SEC55daeeadd5fe85c58550e5f19d63d50dd34a35859767dd315a3fd4538d54622a\n'
/usr/lib/alertscripts # vi /etc
log
/usr/lib/alertscripts # tail -f /var/log/zabbix_ding.log
2021-10-19 11:25:09:消息发送失败 返回信息:310000 keywords not in content, more: [https://ding-doc.dingtalk.com/doc#/serverapi2/qf2nxq]
2021-10-19 11:31:15:消息已发送成功 返回信息:0 ok
2021-10-19 11:32:45:消息已发送成功 返回信息:0 ok
脚本学习详情
come from chatgpt 2024
要使用 Python 将 Zabbix 告警通过钉钉(DingTalk)推送,可以通过钉钉的机器人 API 实现。这个流程与之前对接微信的方式相似,主要是通过调用钉钉机器人接口,将 Zabbix 的告警消息发送到指定的钉钉群聊。 1. 准备工作
创建钉钉机器人:登录钉钉并进入你想接收告警信息的群聊,创建一个群机器人。
点击群设置 -> 群机器人。
添加一个自定义机器人,并选择安全设置,比如设置一个“加签”或“关键词”等方式确保消息的安全性。
记下生成的 Webhook URL,它将用于在 Python 脚本中发送消息。
2. 编写 Python 脚本
下面是一个使用 Python 调用钉钉 API 的示例脚本,结合 Zabbix 告警的推送
import requests
import json
import hashlib
import hmac
import base64
import time
import urllib.parse
# 钉钉 Webhook URL,替换为你自己的 Webhook 地址
WEBHOOK_URL = 'https://oapi.dingtalk.com/robot/send?access_token=your_access_token'
# 如果启用了加签功能,请替换为你的加签密钥
SECRET = 'your_secret' # 如果没有加签功能可以忽略
# 生成带有加签的请求 URL
def generate_sign():
timestamp = str(round(time.time() * 1000))
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 f"×tamp={timestamp}&sign={sign}"
# 发送钉钉消息
def send_dingding_message(content):
headers = {
"Content-Type": "application/json"
}
data = {
"msgtype": "text",
"text": {
"content": content
},
"at": {
"isAtAll": False # 如果需要艾特所有人,将其设为 True
}
}
# 如果使用了加签,将签名加到 URL 上
if SECRET:
url_with_sign = WEBHOOK_URL + generate_sign()
else:
url_with_sign = WEBHOOK_URL
response = requests.post(url_with_sign, headers=headers, data=json.dumps(data))
result = response.json()
if result.get("errcode") == 0:
print("消息发送成功")
else:
print(f"消息发送失败: {result}")
# 示例主函数,发送告警
if __name__ == '__main__':
alert_message = "Zabbix 告警:某某服务器 CPU 使用率过高!" # 替换为你的告警内容
send_dingding_message(alert_message)
3. 在 Zabbix 中集成 Python 脚本
将 Python 脚本保存到 Zabbix 服务器,例如将其保存为 /usr/lib/zabbix/alertscripts/dingding.py。
修改脚本权限: 确保 Zabbix 用户对该脚本具有执行权限:
bash
chmod +x /usr/lib/zabbix/alertscripts/dingding.py
配置 Zabbix 的报警媒介类型:
登录 Zabbix Web 管理界面。
进入“管理(Administration)” -> “媒介类型(Media types)”。
点击“创建媒介类型(Create Media Type)”,选择脚本(Script)类型。
在脚本名称中填写你创建的 Python 脚本的名称(如 dingding.py),并定义参数:
参数1:{ALERT.SUBJECT}(告警标题)
参数2:{ALERT.MESSAGE}(告警内容)
为用户配置告警媒介:
进入“配置(Configuration)” -> “用户(Users)”页面。 选择要接收告警的用户,进入“告警媒介(Media)”选项卡。 点击“添加(Add)”,选择刚刚创建的钉钉媒介类型。
配置告警动作:
进入“配置(Configuration)” -> “动作(Actions)”页面。 创建或编辑一个动作(Action),设置触发条件。 在操作(Operation)中,选择发送告警到钉钉的用户和媒介。
4. 测试告警
配置完成后,触发一个测试告警,查看是否能够通过钉钉收到 Zabbix 的告警信息。你可以通过模拟系统资源异常或手动触发告警来进行测试。 5. 钉钉消息内容优化
你可以根据自己的需求对消息的格式进行调整。比如,可以将 msgtype 改为 markdown,以便支持更丰富的告警内容展示。下面是一个示例:
python
data = {
"msgtype": "markdown",
"markdown": {
"title": "Zabbix 告警",
"text": f"**Zabbix 告警**\n\n告警详情:\n{content}"
},
"at": {
"isAtAll": False
}
}
这样可以在钉钉中收到更直观的告警信息,包括标题和加粗的告警详情
see also
【Zabbix】5.0版本钉钉告警Python3脚本及配置 OK