赞
踩
如有错误,敬请谅解!
此文章仅为本人学习笔记,仅供参考,如有冒犯,请联系作者删除!!
用python编写:
- [root@node1 alertscripts]# cat dingding.py
- #!/usr/bin/env python3
- #coding:utf-8
- #zabbix钉钉报警
- import requests,json,sys,os,datetime
- webhook="https://oapi.dingtalk.com/robot/send?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("/usr/lib/zabbix/logs/dingding.log"):
- f=open("/usr/lib/zabbix/logs/dingding.log","a+")
- else:
- f=open("/usr/lib/zabbix/logs/dingding.log","w+")
- f.write("\n"+"--"*30)
- if x.json()["errcode"] == 0:
- f.write("\n"+str(datetime.datetime.now())+" "+str(user)+" "+"发送成功"+"\n"+str(text))
- f.close()
- else:
- f.write("\n"+str(datetime.datetime.now()) + " " + str(user) + " " + "发送失败" + "\n" + str(text))
- f.close()
以bash格式编写:
- [root@node1 alertscripts]# mkdir -p /usr/lib/zabbix/logs/
- [root@node1 alertscripts]# touch /usr/lib/zabbix/logs/dingding.log
- [root@node1 alertscripts]# chown zabbix.zabbix dingding.py
- [root@node1 alertscripts]# chown zabbix.zabbix /usr/lib/zabbix/logs/dingding.log
- [root@node1 alertscripts]# chmod +x dingding.py
-
- 测试脚本:
- [root@node1 alertscripts]# ./dingding.py a b "zabbix: 这是测试"
zabbix_ding.conf
文件中以bash格式:
- # 安装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
/etc/zabbix/
下bash:
- [config]
- # 日志文件
- log_path=/var/log/zabbix/zabbix_ding.log
- #钉钉机器人 webhook 值
- webhook=https://oapi.dingtalk.com/robot/send?access_token=b3e6fa0f410e7ced04c81680f036xxxx
- # 安全设置 -- 加签
- secret=SEC64d20b4e9d2e2677f7aa01d2a7c2f9xxxx
AlertScriptsPath
路径下bash:
- # 查看zabbix的脚本默认路径,请注意使用您自己的zabbix_server.conf
- cat /etc/zabbix/zabbix_server.conf |grep AlertScriptsPath
- ### Option: AlertScriptsPath
- # AlertScriptsPath=${datadir}/zabbix/alertscripts
- AlertScriptsPath=/usr/lib/zabbix/alertscripts
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 + "×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)
bash:
- # 修改脚本权限
- chown zabbix.zabbix /lib/zabbix/alertscripts/zabbix_ding.py
- chmod u+x /lib/zabbix/alertscripts/zabbix_ding.py
bash:
- # 测试脚本内容
- [root@node1 alertscripts]# ./ding.py a b "这是监控测试"
ALERT.SENDTO
ALERT.SUBJECT
ALERT.MESSAGE
此处和微信报警类似,过程略。不同的是报警信息要添加之前定义的关键词。
如有错误,请联系作者删除
并恳请同行朋友予以斧正,万分感谢!
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。