Zabbix告警调用呼叫接口

#!/usr/bin/python
# coding=utf-8
# author:zhangrongjie

import requests
import json
import sys
import datetime


def printToLog(file, info):
    with open(file, 'a+') as f:
        logtime = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S ")
        f.write(logtime)
        f.write(info)
        f.write('\n')

if __name__ == "__main__":
    call_num = sys.argv[1]
    call_content = sys.argv[2]
    data = {
        "*": "*",
        ...
    }
    data['call_num'] = call_num
    data['vox_content'] = call_content
    data_extend = {
	    "*": "*",
        ...
    }
    data.update(data_extend)
    headers = {'Content-Type': 'application/json'}
    url = "http://***/telecom-api/call/cServ"
    logLocation = "/usr/lib/zabbix/alertscripts/call.log"
    try:
        response = requests.post(
            url=url, headers=headers, data=json.dumps(data), timeout=5)
    except Exception as e:
        info = call_num + " " + str(e.message)
        printToLog(logLocation, info)
    else:
        if response.status_code == 200:
            info = "staus_code:200 " + call_num + " " + str(response.json())
            printToLog(logLocation, info)
        else:
            info = "status_code:" + str(response.status_code) + " " + call_num + " " + str(response.reason)
            printToLog(logLocation, info)

上传脚本至/usr/lib/zabbix/alertscripts(此路径取决于zabbix_server.conf中的配置),

chmod +x alertByPhone.py
chown zabbix:zabbix alertByPhone.py
touch call.log
chown zabbix:zabbix call.log

zabbix web页面新建“报警媒介类型”,填写如下参数:

名称phone
类型脚本
脚本名称alertByPhone.py
脚本参数{ALERT.SENDTO}、{ALERT.SUBJECT}
报警媒介

脚本本身很简单,直接post api产生呼叫即可。重要的是两点:

  • 尽量保证api的可用性,这样系统在发生重大故障时才能发出告警。我们本身公司是做呼叫中心,我脚本中原本调用的是平台内的api。后来才意识到,如果平台发生平台级故障,平台内的api也将不可用,告警自然无法送达。因此必须是用平台外的api。
  • 直接呼叫维护人员手机,对维护人员会造成很大压力。因此只有非常重大的告警项,才应该使用电话告警。而且告警项目不应多,否则发生平台级故障时,告警风暴会严重影响维护人员的工作效率。