zabbix:设置企业微信告警(python3脚本)

一、代码

#!/usr/local/python3.3/bin/python3  #python环境位置
# coding: utf-8 

import urllib.request
import json
import sys
import time
import os
import shutil
import logging

def gettoken(corp_id,corp_secret):
    gettoken_url = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=' + corp_id + '&corpsecret=' + corp_secret
    try:
        token_file = urllib.request.urlopen(gettoken_url)
    except urllib.error.HTTPError as e:
        print(e.code)
        print(e.read().decode("utf8"))

    token_data = token_file.read().decode('utf-8')
    token_json = json.loads(token_data)
    token_json.keys()
    token = token_json['access_token']
    return token


def senddata(access_token,user,content):
    try:
        send_url = 'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=' + access_token
        send_values = {
            "touser":user,   #企业号中的用户帐号,在zabbix用户Media中配置,如果配置不正常,将按部门发送。 
            "msgtype":"text",
            "agentid":"1000002",
            "text":{
                "content":content
                },
            "safe":"0"
            }

        send_data = json.dumps(send_values,ensure_ascii=False).encode(encoding='UTF8')
        send_request = urllib.request.Request(send_url, send_data)
        response = urllib.request.urlopen(send_request)
        msg = response.read()
        print("returned value : " + str(msg))
    except:
        print("returned value : " + str(msg))


default_encoding = 'utf-8'

if sys.getdefaultencoding() != default_encoding:
    reload(sys)
    sys.setdefaultencoding(default_encoding)
user = str(sys.argv[1])
title = str(sys.argv[2])
content = str(sys.argv[3])

corpid = 'wwb22899d2f5c8c1114' #'微信公众平台管理组的ID' 
corpsecret = 'deSiAIR4_cLV4J222p6vQYbFoVDNi1WbULugAhyW2dc' #'微信公众平台管理组的凭证密钥' 
accesstoken = gettoken(corpid,corpsecret)
senddata(accesstoken,user,content)

测试格式:python3+脚本名+收件人+ ‘主题’ +‘内容’
注意事项:
1、python环境为python3以上。
2、空格和制表符出错查看:set list TAB

二、媒体参数
在这里插入图片描述

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值