python ---- zabbix配置企业微信告警

操作步骤:

  1. 首先要注册一个企业微信中的"企业".
  2. 登入至企业微信后台管理,在"应用管理" --> "创建应用"作为告警的zabbix.
  3. 记录创建的应用的Secret及"我的企业"中的"企业ID".
  4. 查看API文档开始撰写告警脚本.
  5. 测试告警是否生效.

一、企业微信中注册企业

略,可直接查询如何注册

二、创建Zabbix应用

注:
  记得可见范围要选择

三、查看API文档撰写脚本

API文档地址:
  https://work.weixin.qq.com/wework_admin/frame#apps/createApiApp
小编根据实际情况编写,脚本如下:

import requests
import json
import sys
# 此处的消息内容接收脚本后的参数
message = sys.argv[1]
# 此为固定地址(官方文档有说明)
API_URL = 'https://qyapi.weixin.qq.com/cgi-bin/'
class Wechat:
    def __init__(self):
        self.keys = {
      # corpid与corpsecret为应用的secret及企业ID;
            'corpid': 'ww97b8dfasdf1bdb4a55d6wqee',
            'corpsecret': '6yrP1nYUtPdsafdqfoCa0B9ofdsafdsafdsafop4Qv-OPdJlZJYxcmYaU3Ifg'
                }
      # touser默认为"@all"及所有人都能接收到消息,agentid为应用的信息,
        self.touser = '@all'
        self.agentid = '1000002'
   # 定义请求函数
    def http_get(self,url,method,**kwargs):
        headers = {'content-type': 'application/json'}
        if method == 'GET':
            request = requests.Session()
            response = request.get(''.join([API_URL, url]),headers = headers,**kwargs)
            return response.json()
        if method == 'POST':
            response = requests.post(''.join([API_URL, url]),headers = headers,**kwargs)
            return response

    def get_accesstoken(self):
        response = self.http_get('gettoken', 'GET', params=self.keys)
        if response and response['errcode'] == 0:
            return response['access_token']
        return 'Faild.'

    def send_message(self):
        data = {
            'touser': self.touser,
            'msgtype': "text",
            'agentid': self.agentid,
            'text': {
                'content': message
            }
        }
        response = self.http_get('message/send' + '?access_token=' + self.get_accesstoken(), 'POST', data = json.dumps(data))
        return response.json()
test = Wechat()
test2 = test.get_accesstoken()
print(test2)
test3 = test.send_message()
print(test3)
posted @ 2021-02-26 16:49  k-free  阅读(324)  评论(0编辑  收藏  举报