一、环境配置:
首先在钉钉创建一个用于告警的群组并添加一个自定义机器人
说明:
安全设置的作用就是在调用时需要加的限制;有三种,分别是自定义关键词、加签、IP地址段。
1.其中加签是通过算法,算出一段类似密钥段放到机器接口中进行调用;
2.ip地址段就是限制机器人接口能从那些地址发出;
3.最常用的就是自定义关键词:这个作用是第三方脚本调用机器人接口发通知信息时,内容必须要包含的关键字。
配置好钉钉机器人,就得到了一个WebHook 地址,这个就是调用机器人发送通知的接口。
钉钉机器人接口文档链接:https://open.dingtalk.com/document/org/application-types
二、调用机器人API发信息代码:
1.shell
#!/bin/bash
log_file='/usr/local/zabbix/share/zabbix/alertscripts/dingding.log'
url=`cat /usr/local/zabbix/share/zabbix/alertscripts/webhook`
subject=`echo $1`
message=`echo $2|tr '\r\n' '\n'`
function send_msg() {
info=`echo -e "告警描述:\n$subject\n\n告警内容:\n$message"`
send=$( curl "$url" -H 'Content-Type: application/json' -d "
{
\"msgtype\": \"text\",
\"text\":
{
\"content\": \"$info\"
}
}" )
send_status=$(echo $send|awk -F ',' '{print $2}'|awk -F ':' '{print $2}'|awk -F '}' '{print $1}')
if [ $send_status = '"ok"' ]
then
`cat >> $log_file << EOF
--------Send Success--------
$info
---------------End---------------
EOF`
else
`cat >> $log_file << EOF
---------Send Error---------
$info
---------------End---------------
EOF`
fi
}
send_msg
效果如下:
2.Python
#!/bin/python3
# -*- coding:utf-8 -*-
import json
import requests
import sys
alert_subject = sys.argv[1]
alert_message = sys.argv[2].replace('\r\n','\n')
# "\r\n"为windows中的回车换行符,linux中会显示为^M(不替换的话,钉钉中显示可能会有多余空行)
def send_msg(url):
headers = {'Content-Type': 'application/json; charset=utf-8'}
data = {
"msgtype": "text",
"text": {
"content": f"告警描述:\n{alert_subject}\n\n告警内容:\n{alert_message.strip()}"
}
}
r = requests.post(url, data=json.dumps(data), headers=headers)
return r.text
if __name__ == '__main__':
end = 'End'.center(30,'-')
url = 'https://oapi.dingtalk.com/robot/send?access_token=xxxxxx'
info = send_msg(url)
if eval(info)['errmsg'] == 'ok':
status = 'Send Sussess'
else:
status = 'Send Error!'
f = open(file='/usr/local/zabbix/share/zabbix/alertscripts/DingDing.log',mode='a')
f.write(f'''
{status.center(25,'-')}
告警描述:
{alert_subject}
告警内容:
{alert_message}
{end}
'''
)
f.close()
效果如下:
三、Zabbix配置:
1.告警媒介
2.配置触发器动作
3.配置用户报警媒介