通过钉钉发送报警信息

author:headsen  chen

date:2019-03-05  18:06:53

 

1,网友的

import json,requests 
def info():
  url = 'https://oapi.dingtalk.com/robot/send?access_token=xxxxxxxxxxxxxxxx'
  headers = { 'Content-Type': 'application/json;charset=utf-8' }
  formdata = { "msgtype": "text", "text": {"content":str('测试钉钉')} }
  hhh = requests.post(url=url, data=json.dumps(formdata), headers=headers)
  print hhh.text if __name__ == '__main__':
  info()

 2,实际使用的:

import json,requests
def Alert(msg):
        headers = {"Content-Type": "application/json"}
        data = {"msgtype": "text", "text": {"content": msg}}
        r = requests.post(
            "https://oapi.dingtalk.com/robot/send?access_token= xxx ",
            data=json.dumps(data), headers=headers)
Alert(msg)

3,网友的钉钉报警设置:

3.1,申请钉钉账号,登录账号。
3.2,创建一个告警群组,添加一个机器人。

记录下来这个webhook地址。

3.3,脚本配置
在/usr/local/zabbix/share/zabbix/alertscripts目录下面创建脚本,名称为zabbix_dingding.py
脚本的内容如下:

    #!/usr/bin/python
    # -*- coding: utf-8 -*-
     
    import requests
    import json
    import sys
    import os
     
    headers = {'Content-Type': 'application/json;charset=utf-8'}
    api_url = "刚才复制的"
     
    def msg(text):
        json_text= {
         "msgtype": "text",
            "text": {
                "content": text
            },
            "at": {
                "atMobiles": [
                    "1xxxxxxxxxxxxx"
                ],
                "isAtAll": False
            }
        }
        print requests.post(api_url,json.dumps(json_text),headers=headers).content
         
    if __name__ == '__main__':
        text = sys.argv[1]
        msg(text)

3.4 给脚本添加执行权限测试脚本

    [root alertscripts]# chmod +x zabbix_dingding.py
    [root alertscripts]# ll
    total 4
    -rwxr-xr-x 1 zabbix zabbix 933 Aug 17 10:05 zabbix_dingding.py
    [root alertscripts]# ./zabbix_dingding.py test
    {"errmsg":"ok","errcode":0}
    [root alertscripts]#

钉钉正确的收到了我们的测试告警,证明监控脚本生效了。

posted @ 2019-03-05 17:42  开始认识  阅读(5522)  评论(0编辑  收藏  举报