Zabbix v3.1怎样使用微信报警及API
学习资料:IT运维管理社区专家讲堂直播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/envpython#-*-co**:utf-8-*-
importurllib,urllib2,jsonimportsysreload(sys)sys.setdefaultenco**("utf-8")
classWeChat(object):__token_id=''#initattributedef__init__(self,url):self.__url=url.rstrip('/')self.__corpid=''#微信企业号-设置-权限管理可查看self.__secret=''#微信企业号-设置-权限管理可查看
#GetTokenIDdefauthID(self):params={'corpid':self.__corpid,'corpsecret':self.__secret}data=urllib.urlencode(params)content=self.getToken(data)try:self.__token_id=content['access_token']#printcontent['access_token']exceptKeyError:raiseKeyError
#EstablishaconnectiondefgetToken(self,data,url_prefix='/'):url=self.__url+url_prefix+'gettoken?'try:response=urllib2.Request(url+data)exceptKeyError:raiseKeyErrorresult=urllib2.urlopen(response)content=json.loads(result.read())returncontent
#GetsendmessageurldefpostData(self,data,url_prefix='/'):url=self.__url+url_prefix+'message/send?access_token=%s'%self.__token_idrequest=urllib2.Request(url,data)try:result=urllib2.urlopen(request)excepturllib2.HTTPErrorase:ifhasattr(e,'reason'):print'reason',e.reasonelifhasattr(e,'code'):print'code',e.codereturn0else:content=json.loads(result.read())result.close()returncontent
#sendmessagedefsendMessage(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)printresponse
if__name__=='__main__':a=WeChat('cgi-bin')a.sendMessage(sys.argv,sys.argv)
$chmod+x/usr/local/zabbix/alertscripts/weixin.py$chownzabbix:zabbix/usr/local/zabbix/alertscripts/weixin.py$pythonzabbixtesttest//$1联系人$2主题$3正文{u'errcode':0,u'errmsg':u'ok'}
配置zabbixUI
[*]【管理】-【报警媒介类型】-【创建媒介类型】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方法之外,HTTPHeaderContent-Type必须为【application/jsonrequest,application/json-rpc,application/json】其中之一。
可以采用脚本或者任何"手动"支持JSONRPC的工具来使用API。而首先需要了解的就是如何验证和如何使用验证ID来获取想要的信息。后面的演示会以Python脚本和基于Curl的例子来呈现API的基本使用。
CLIExample:$vimzbx_addhost.py
#!/usr/bin/envpython2.7#co**=utf-8
importjsonimporturllib2importsysreload(sys)sys.setdefaultenco**("utf-8")
#basedurlandrequiredheaderurl="http://10.0.0.1:8027/api_jsonrpc.php"header={"Content-Type":"application/json"}
defzbxauth():#authuserandpassworddata=json.dumps({"jsonrpc":"2.0","method":"user.login","params":{"user":"admin","password":"123456"},"id":0})#createrequestobjectrequest=urllib2.Request(url,data)forkeyinheader:request.add_header(key,header)#authandgetauthidtry:result=urllib2.urlopen(request)exceptURLErrorase:print"AuthFailed,PleaseCheckYourNameAndPassword:",e.codeelse:response=json.loads(result.read())result.close()#return"AuthSuccessful.TheAuthIDIs:",response['result']returnresponse['result']
defadd_host(ip):authid=zbxauth()#requestjsondata=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),#theauthidiswhatauthscriptreturns,remeberitisstring"id":0,})#createrequestobjectrequest=urllib2.Request(url,data)forkeyinheader:request.add_header(key,header)#addhosttry:result=urllib2.urlopen(request)exceptURLErrorase:print"Erroras",eelse:response=json.loads(result.read())printresponseresult.close()reutrn"Addhost:{0}isok.".format(ip)
printadd_host('8.8.8.8')
OpsWorlder原创
页:
[1]