Zabbix v3.1怎样使用微信报警及API
学习资料: ITIL培训基地专家讲堂直播 300期视频回放
[*]微信报警
配置微信企业号
[*]在组织架构中,新建二级组,并添加相关人员,注意添加人员的账号要记清楚。后期zabbix发送邮件时需要填写用户名(也可以填写@all发送给所有的人)
[*]点击"修改部门",获取ID
[*]去设置-->功能设置-->权限管理,最重要的是CorpID,Secret 两个密钥,后期脚本里会利用它俩生成一个token ,然后利用token 去发送消息
配置zabbix-server将weixin.py放到/usr/local/zabbix/alertscripts/目录下
$ vim /usr/local/zabbix/alertscripts/weixin.py
#!/usr/bin/env python# -*- co**: utf-8 -*-
import urllib,urllib2,jsonimport sysreload(sys)sys.setdefaultenco**( "utf-8" )
class WeChat(object): __token_id = '' # init attribute def __init__(self,url): self.__url = url.rstrip('/') self.__corpid = '' #微信企业号-设置-权限管理可查看 self.__secret = '' #微信企业号-设置-权限管理可查看
# Get TokenID def authID(self): params = {'corpid':self.__corpid, 'corpsecret':self.__secret} data = urllib.urlencode(params) content = self.getToken(data) try: self.__token_id = content['access_token'] # print content['access_token'] except KeyError: raise KeyError
# Establish a connection def getToken(self,data,url_prefix='/'): url = self.__url + url_prefix + 'gettoken?' try: response = urllib2.Request(url + data) except KeyError: raise KeyError result = urllib2.urlopen(response) content = json.loads(result.read()) return content
# Get sendmessage url def postData(self,data,url_prefix='/'): url = self.__url + url_prefix + 'message/send?access_token=%s' % self.__token_id request = urllib2.Request(url,data) try: result = urllib2.urlopen(request) except urllib2.HTTPError as e: if hasattr(e,'reason'): print 'reason',e.reason elif hasattr(e,'code'): print 'code',e.code return 0 else: content = json.loads(result.read()) result.close() return content
# send message def sendMessage(self,touser,message): self.authID() data = json.dumps({ 'touser':"@all", 'toparty':"@all", 'totag': "test", 'msgtype':"text", 'agentid':"2", 'text':{ 'content':message }, 'safe':"0" },ensure_ascii=False) response = self.postData(data) print response
if __name__ == '__main__': a = WeChat('cgi-bin') a.sendMessage(sys.argv,sys.argv)
$ chmod +x /usr/local/zabbix/alertscripts/weixin.py$ chown zabbix:zabbix /usr/local/zabbix/alertscripts/weixin.py$ python zabbix test test//$1联系人 $2主题$3正文{u'errcode': 0, u'errmsg': u'ok'}
配置zabbix UI
[*]【管理】-【报警媒介类型】-【创建媒介类型】 mmbiz_jpg/x63NLUqhL5HF5ezqicGcKnBRocQErLkBM8s2uq3sV4Xs9Bw427b0wvoFpGW2skuZTWHb0raUicQ41MCb2wGTDbtQ/640?wx_fmt=jpeg&tp=webp&wxfrom=5&wx_lazy=1
[*]【管理】-【用户】-【admin】-【报警媒介】 mmbiz_jpg/x63NLUqhL5HF5ezqicGcKnBRocQErLkBMQZD4MDTibKzrDJO8aem4zYvpc4KRnTWRqGvchI0eEx6travDx3aZ4XQ/640?wx_fmt=jpeg&tp=webp&wxfrom=5&wx_lazy=1
[*]【配置】-【动作】-【触发器】-【创建动作】
mmbiz_jpg/x63NLUqhL5HF5ezqicGcKnBRocQErLkBMjjNjQj5RWG976bZQLqxQpbPg7VoHZnVNFk7g7N2qSicMzfwdQn9ibcdA/640?wx_fmt=jpeg&tp=webp&wxfrom=5&wx_lazy=1
mmbiz_jpg/x63NLUqhL5HF5ezqicGcKnBRocQErLkBMV0lWlxmcnibiafAWb9ExPWuzkJWpVHux4u8IPJVpbsfKiaJnQNQaIN3vQ/640?wx_fmt=jpeg&tp=webp&wxfrom=5&wx_lazy=1
[*]API使用
API 采用JSON-RPC实现。这意味着调用任何函数,都需要发送POST请求,输入输出数据都是以JSON格式。大致工作流如下:
[*]准备JSON对象,它描述了你想要做什么(创建主机,获取图像,更新监控项等)。
[*]采用POST方法向 zabbix/api_jsonrpc.php发送此JSON对象,zabbix/是Zabbix前端地址 ,api_jsonrpc.php是调用API的PHP脚本。可在安装可视化前端的目录下找到。
[*]获取JSON格式响应。
[*]注:请求除了必须是POST方法之外,HTTP Header Content-Type必须为【application/jsonrequest,application/json-rpc,application/json】其中之一。
可以采用脚本或者任何"手动"支持JSON RPC的工具来使用API。而首先需要了解的就是如何验证和如何使用验证ID来获取想要的信息。后面的演示会以Python脚本和基于Curl的例子来呈现API的基本使用。
CLI Example:$ vim zbx_addhost.py
#!/usr/bin/env python2.7#co**=utf-8
import jsonimport urllib2import sysreload(sys)sys.setdefaultenco**( "utf-8" )
# based url and required headerurl = "http://10.0.0.1:8027/api_jsonrpc.php"header = {"Content-Type": "application/json"}
def zbxauth(): # auth user and password data = json.dumps( { "jsonrpc": "2.0", "method": "user.login", "params": { "user": "admin", "password": "123456" }, "id": 0 }) # create request object request = urllib2.Request(url,data) for key in header: request.add_header(key,header) # auth and get authid try: result = urllib2.urlopen(request) except URLError as e: print "Auth Failed, Please Check Your Name And Password:",e.code else: response = json.loads(result.read()) result.close() # return "Auth Successful. The Auth ID Is:",response['result'] return response['result']
def add_host(ip): authid = zbxauth() # request json data = json.dumps( { "jsonrpc":"2.0", "method":"host.create", "params":{ "host": ip, "interfaces": [ { "type": 1, "main": 1, "useip": 1, "ip": ip, "dns": "", "port": "10050" } ], "groups": [{"groupid": 8}], "templates": [{"templateid":10108}], }, "auth":"{0}".format(authid), # the auth id is what auth script returns, remeber it is string "id":0, }) # create request object request = urllib2.Request(url,data) for key in header: request.add_header(key,header) # add host try: result = urllib2.urlopen(request) except URLError as e: print "Error as ", e else: response = json.loads(result.read()) print response result.close() reutrn "Add host: {0} is ok.".format(ip)
print add_host('8.8.8.8')
OpsWorlder原创
页:
[1]