Zabbix使用Python脚本实现微信告警

一、注意事项

  参考"Zabbix遇到的问题集锦"中的第三点"利用Python发送告警注意细节"

  https://www.cnblogs.com/lisenlin/p/10075275.html#3

 

二、微信侧准备

  1.企业微信ID

  2.AgentID

    3.Secret

 

  

 

三、Python代码

#!/usr/bin/python3
# -*- coding:utf-8 -*-
import requests
import json
import sys




# 存放access_token文件路径
file_path = '4_access_token.log'



def get_access_token_from_file():
    try:
        f = open(file_path,'r+')
        this_access_token = f.read()
        print('get success %s' % this_access_token)
        f.close()
        return this_access_token
    except Exception as e:
        print(e)

# 获取token函数,文本里记录的token失效时调用
def get_access_token():
    get_token_url = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=%s&corpsecret=%s' % (corp_id, corp_secret)
    print(get_token_url)
    r = requests.get(get_token_url)
    request_json = r.json()
    this_access_token = request_json['access_token']
    print(this_access_token)
    r.close()
    # 把获取到的access_token写入文本
    try:
        f = open(file_path,'w+')
        f.write(this_access_token)
        f.close()
    except Exception as e:
        print(e)
        save_log(e)

    # 返回获取到的access_token值
    return this_access_token


def save_log(content):
    with open(log,'a+') as f:
        content +='\n'
        f.write(content)

try:
    # 获取输入参数
    list1 = sys.argv
    for i in list1:
        if "-corp_id" in i:
            corp_id = i.strip().split('corp_id=')[1]
        elif "-msg" in i:
            message = i.strip().split('=')[1]
        elif '-log' in i:
            log = i.strip().split('=')[1]
        elif '-corp_secret' in i:
            corp_secret = i.strip().split('=')[1]
        elif '-agent_id' in i:
            agent_id = int(i.strip().split('=')[1])

except Exception as e:
    print('错误:%s'%e)
    save_log(e)




# snedMessage
# 死循环,直到消息成功发送
flag = True
while(flag):
    # 从文本获取access_token
    access_token = get_access_token_from_file()
    try:

        to_user = '@all'
        #message = sys.argv[3]
        # message = "test"
        send_message_url = 'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=%s' % access_token
        print(send_message_url)
        message_params = {
                            "touser":to_user,
                            "msgtype":"text",
                            "agentid":agent_id,
                            "text":{
                                "content" : message
                            },
                            "safe":0
                        }
        r = requests.post(send_message_url, data=json.dumps(message_params))
        print('post success %s ' % r.text)
        # 判断是否发送成功,如不成功则跑出异常,让其执行异常处理里的函数
        request_json = r.json()
        errmsg = request_json['errmsg']
        if errmsg != 'ok':
            raise ValueError("错误:%s\n"%errmsg)
        # 消息成功发送,停止死循环
        flag = False
    except ValueError as e:
        print(e)
        access_token = get_access_token()
        save_log(e)
    except Exception as e:
        flag =False
        print('错误:%s' % e)
        save_log(e)

 

四、Zabbix侧告警媒介类型

 

 

 五、告警格式

  5.1 告警信息

告警原因: {EVENT.NAME}
告警时间:{EVENT.DATE} {EVENT.TIME}
恢复时间:
当前值: {ITEM.VALUE1}
告警时长:
告警主机: {HOST.NAME}
告警IP: {HOST.IP}
Severity: {EVENT.SEVERITY}

Original problem ID: {EVENT.ID}
{TRIGGER.URL}

 

  5.2恢复信息

告警原因: {EVENT.NAME}
告警时间:{EVENT.DATE} {EVENT.TIME}
恢复时间:{EVENT.RECOVERY.DATE} {EVENT.RECOVERY.TIME}
当前值: {ITEM.VALUE1}
告警时长:{EVENT.AGE}
告警主机: {HOST.NAME}
告警IP: {HOST.IP}
Severity: {EVENT.SEVERITY}

Original problem ID: {EVENT.ID}
{TRIGGER.URL}

 

posted @ 2021-04-14 22:51  森林326  阅读(170)  评论(0编辑  收藏  举报