利用钉钉机器人发送告警信息

现在越来越多的人开始使用钉钉,对于运维告警来说,除了传统的邮件告警之外,短信告警、企业微信告警、钉钉机器人告警等也是首选考虑。这里介绍如果利用python+钉钉机器人 实现告警信息发送。


首先新增一个组专门用来接受告警信息,在组设置中看到组机器人Group robot,如下图:

 

点击“组机器人”,进入如下页面 然后点击 “添加机器人” 红色部分


 

在打开的页面中选择 “自定义(通过webhook接入自定义服务)” ;点击进去之后点击“添加Add”


 

在弹出的页面中输入“ChatBot Name” 这里起名字叫“告警测试” 然后点击下一步,得到如下图示


 

这里点击copy记住 webhook 的值,这个在接下来的脚本中要用到,很关键哦~
也可以点击“setting ins…” 打开帮助页面,关键的部分如下(我们告警信息选择text 类型即可)

 

最后就是脚本了

root@pts/1 $ cat dingding.py
#!/usr/bin/env python
#-*- coding: utf-8 -*-
#Author: Colin
#Date:
#Desc:
#

import os
import sys
import json
import datetime
import requests

## 钉钉组中创建机器人的时候给出的webhook
## 告警测试
webhook = 'https://oapi.dingtalk.com/robot/send?access_token=xxxxx'

## 定义接受信息的人和信息内容
user = sys.argv[1]
content = sys.argv[2]

## 组装内容
## refer to: https://open-doc.dingtalk.com/docs/doc.htm?spm=a219a.7629140.0.0.karFPe&treeId=257&articleId=105735&docType=1
data = {
    "msgtype": "text",
    "text": {
        "content": content
    },
    "at": {
        "atMobiles": [user],
        "isAtAll": True
    }
}

## 调用request.post发送json格式的参数
headers = {'Content-Type': 'application/json'}
result = requests.post(url=webhook, data=json.dumps(data), headers=headers)

print('--'*30)
print(result)
print(result.json())
print('--'*30)

if result.json()["errcode"] == 0:
     print("send ok")
else:
    print("send failed!")

测试发送结果如下:


 
 


原文地址:https://www.cnblogs.com/DataArt/p/10089456.html