zabbix 微信报警python脚本
时间: 2023-10-22 21:04:24 浏览: 201
zabbix微信告警python脚本
以下是一个基于 Python 实现的 Zabbix 微信报警脚本,需要先安装 WeixinBot 和 requests 库:
```python
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import requests
import json
import sys
class WeChat(object):
def __init__(self, corpid, corpsecret):
self.url = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken'
self.corpid = corpid
self.corpsecret = corpsecret
self.params = {
'corpid': self.corpid,
'corpsecret': self.corpsecret
}
self.access_token = self.get_access_token()
def get_access_token(self):
r = requests.get(self.url, params=self.params)
return r.json()['access_token']
def send_message(self, message, agentid, touser=None, toparty=None):
url = 'https://qyapi.weixin.qq.com/cgi-bin/message/send'
data = {
"touser": touser,
"toparty": toparty,
"msgtype": "text",
"agentid": agentid,
"text": {
"content": message
},
"safe": 0
}
params = {
'access_token': self.access_token
}
headers = {'Content-Type': 'application/json;charset=utf-8'}
r = requests.post(url, params=params, data=json.dumps(data), headers=headers)
return r.json()
if __name__ == "__main__":
corpid = 'YOUR_CORPID'
corpsecret = 'YOUR_CORPSECRET'
agentid = 'YOUR_AGENTID'
touser = sys.argv[1]
subject = sys.argv[2]
content = sys.argv[3]
message = u"收件人:%s\n主题:%s\n内容:%s" % (touser, subject, content)
wechat = WeChat(corpid, corpsecret)
response = wechat.send_message(message, agentid, touser=touser)
print(response)
```
使用方法:
1. 用企业微信扫描二维码,加入企业;
2. 创建一个应用,并记录下应用的 `corpid`、`corpsecret`和 `agentid`;
3. 安装 WeixinBot 和 requests 库;
4. 将上述代码保存到文件 `wechat.py` 中;
5. 在 Zabbix 中配置告警媒介,将 `wechat.py` 的路径作为脚本名,并在参数中依次填入收件人、主题和内容。例如:`/usr/bin/python /path/to/wechat.py {ALERT.SENDTO} "{ALERT.SUBJECT}" "{ALERT.MESSAGE}"`;
6. 测试告警是否正常发送。
阅读全文