学习资料: ITIL培训基地专家讲堂直播 300期视频回放
配置微信企业号在组织架构中,新建二级组,并添加相关人员,注意添加人员的账号要记清楚。后期zabbix发送邮件时需要填写用户名(也可以填写@all发送给所有的人) 点击"修改部门",获取ID 去设置-->功能设置-->权限管理,最重要的是CorpID,Secret 两个密钥,后期脚本里会利用它俩生成一个token ,然后利用token 去发送消息
[url=][/url]配置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,json import sys reload(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[1],sys.argv[3])
$ 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'}
[url=][/url]配置zabbix UI【管理】-【报警媒介类型】-【创建媒介类型】 【管理】-【用户】-【admin】-【报警媒介】
API 采用JSON-RPC实现。这意味着调用任何函数,都需要发送POST请求,输入输出数据都是以JSON格式。大致工作流如下: 可以采用脚本或者任何"手动"支持JSON RPC的工具来使用API。而首先需要了解的就是如何验证和如何使用验证ID来获取想要的信息。后面的演示会以Python脚本和基于Curl的例子来呈现API的基本使用。
CLI Example: $ vim zbx_addhost.py
#!/usr/bin/env python2.7 #co**=utf-8
import json import urllib2 import sys reload(sys) sys.setdefaultenco**( "utf-8" )
# based url and required header url = "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[key]) # 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[key]) # 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原创
|