本文共 19301 字,大约阅读时间需要 64 分钟。
今天介绍跟实验两种方法调用api接口去批量添加批量管理zabbix客户端主机:
首先看官网介绍:概观Zabbix API允许您以编程方式检索和修改Zabbix的配置,并提供对历史数据的访问。它被广泛用于:创建新的应用程序以使用Zabbix;
将Zabbix与第三方软件集成;自动执行日常任务。Zabbix API是基于Web的API,作为Web前端的一部分提供。它使用JSON-RPC 2.0协议,这意味着两件事:该API由一组独立的方法的;
客户端和API之间的请求和响应使用JSON格式进行编码。有关协议和JSON的更多信息可以在JSON-RPC 2.0规范和JSON格式主页中找到。结构体
该API由许多的方法,这些方法名义上分为不同的API。每种方法执行一个特定任务。例如,该host.create方法属于主机 API,用于创建新主机。从历史上看,API有时被称为“类”。大多数API包含至少四种方法:get,create,update和delete为恭敬地检索,创建,更新和删除数据,但某些API可以提供一个完全不同的一套方法。
执行请求设置前端后,可以使用远程HTTP请求来调用API。为此,您需要将HTTP POST请求发送到api_jsonrpc.php位于前端目录中的文件。例如,如果您的Zabbix前端安装在http://company.com/zabbix下,则调用该apiinfo.version方法的HTTP请求可能如下所示:POST HTTP / 1.1
Content-Type:application / json-rpc{ “jsonrpc”: “2.0”, “方法”: “apiinfo.version”, “ID”:1, “AUTH”:NULL, “PARAMS”:{}}
该请求必须具有Content-Type标头集合至这些值中的一个:application/json-rpc,application/json或application/jsonrequest。
您可以使用任何HTTP客户端或JSON-RPC测试工具手动执行API请求,但是对于开发应用程序,我们建议您使用社区维护的库之一。
示例工作流程以下部分将向您详细介绍一些用法示例。认证
在您可以访问Zabbix内部的任何数据之前,您需要登录并获取身份验证令牌。这可以使用该user.login方法完成。我们假设您要以标准Zabbix Admin用户身份登录。然后您的JSON请求将如下所示:{
“jsonrpc” : “2.0” ,“method” : “user.login” ,“params” : { “user” : “Admin” ,“password” : “zabbix” } ,“id” : 1 ,“auth” : null }~~让我们仔细看看请求对象。它具有以下属性:
jsonrpc- API使用的JSON-RPC协议版本; Zabbix API实现了JSON-RPC 2.0版;
method- 被调用的API方法;params- 将传递给API方法的参数;id - 请求的任意标识符;auth - 用户认证令牌; 因为我们还没有,所以它设置为null。如果您正确提供了凭据,则API返回的响应将包含用户身份验证令牌:{
“jsonrpc” : “2.0” ,“result” : “0424bd59b807674191e7d77572075f33” ,“id” : 1 }响应对象又包含以下属性:
jsonrpc - 再次,JSON-RPC协议的版本;
result - 方法返回的数据;id - 相应请求的标识符。检索主机我们现在有一个有效的用户身份验证令牌,可用于访问Zabbix中的数据。例如,让我们使用该host.get方法检索所有已配置主机的ID,主机名和接口:{
“jsonrpc” : “2.0” ,“method” : “host.get” ,“params” : { “output” : [ “hostid” ,“host” ] ,“selectInterfaces” : [ “interfaceid” ,“ip” ] } ,“id” : 2 ,“auth” : “0424bd59b807674191e7d77572075f33” }请注意,该auth属性现在设置为我们通过调用获得的身份验证令牌user.login。响应对象将包含有关主机的请求数据:{
“jsonrpc” : “2.0” ,“result” : [ { “hostid” : “10084” ,“host” : “Zabbix server” ,“interfaces” : [ { “interfaceid” : “1” ,“ip” : “127.0.0.1” } ] } ] ,“id” : 2 }出于性能原因,我们建议始终列出要检索的对象属性,并避免检索所有内容。创建一个新项目让我们使用从前一个请求获得的数据在“Zabbix服务器”上创建一个新项目host.get。这可以通过使用以下item.create方法完成:{
“jsonrpc” : “2.0” ,“method” : “item.create” ,“params” : { “name” : “$ 1上的可用磁盘空间” ,“key_ ” : “vfs.fs.size [/ home / joe /,free]“ ,”hostid“ : ”10084“ ,”type“ : 0 ,”value_type“ : 3 ,”interfaceid“ : ”1“ ,”delay“ : 30 } ,”auth“: “0424bd59b807674191e7d77572075f33” ,“id” : 3 }成功的响应将包含新创建的项的ID,可用于在以下请求中引用该项:
{
“jsonrpc” : “2.0” ,“result” : { “itemids” : [ “24759” ] } ,“id” : 3 }该item.create方法以及其他创建方法也可以接受对象数组,并通过一次API调用创建多个项目。创建多个触发器因此,如果create方法接受数组,我们可以添加多个触发器,如下所示:{
“jsonrpc” : “2.0” ,“method” : “trigger.create” ,“params” : [ { “description” : “{HOST.NAME}上的处理器负载过高” ,“表达式” : “{Linux server:system.cpu.load [percpu,avg1] .last()}> 5“ ,} ,{ ”description“ : ”{HOST.NAME}上的进程太多“ ,”表达式“ : ”{Linux server:proc .num []。avg(5m)}> 300“ ,} ] ,”auth“: “0424bd59b807674191e7d77572075f33” ,“id”: 4 }成功的响应将包含新创建的触发器的ID:{
“jsonrpc” : “2.0” ,“result” : { “triggerids” : [ “17369” ,“17370” ] } ,“id” : 4 }更新项目启用项目,即将其状态设置为“0”:{
“jsonrpc” : “2.0” ,“method” : “item.update” ,“params” : { “itemid” : “10092” ,“status” : 0 } ,“auth” : “0424bd59b807674191e7d77572075f33” ,“id” : 5 }成功的响应将包含更新项的ID:{
“jsonrpc” : “2.0” ,“result” : { “itemids” : [ “10092” ] } ,“id” : 5 }该item.update方法以及其他更新方法也可以接受对象数组并使用一个API调用更新多个项目。更新多个触发器启用多个触发器,即将其状态设置为0:{
“jsonrpc” : “2.0” ,“method” : “trigger.update” ,“params” : [ { “triggerid” : “13938” ,“status” : 0 } ,{ “triggerid” : “13939” ,“状态“ : 0 } ” ,“auth” : “0424bd59b807674191e7d77572075f33” ,“id” : 6 }成功的响应将包含更新的触发器的ID:{
“jsonrpc” : “2.0” ,“result” : { “triggerids” : [ “13938” ,“13939” ] } ,“id” : 6 }这是更新的首选方法。一些API方法host.massupdate允许编写更简单的代码,但不建议使用这些方法,因为它们将在未来的版本中删除。错误处理到目前为止,我们所尝试的一切都运行良好。但是如果我们尝试对API进行不正确的调用会发生什么?让我们尝试通过调用创建另一个主机,host.create但省略必需groups参数。{
“jsonrpc” : “2.0” ,“method” : “host.create” ,“params” : { “host” : “Linux server” ,“interfaces” : [ { “type” : 1 ,“main” : 1 ,“useip” : 1 ,“ip” : “192.168.3.1” ,“dns” : “” ,“port” : “10050”} ] } ,“id” : 7 ,“auth”: “0424bd59b807674191e7d77572075f33” }然后,响应将包含一条错误消息:{
“jsonrpc” : “2.0” ,“error” : { “code” : - 32602 ,“message” : “无效的参数。” ,“data” : “没有主机组” Linux服务器\“。” } ,“id” : 7 }如果发生错误,而不是result属性,响应对象将包含error具有以下数据的属性:
code - 错误代码;
message - 简短的错误摘要;data - 更详细的错误消息。错误可能在不同情况下发生,例如,使用不正确的输入值,会话超时或尝试访问不存在的对象。您的应用程序应该能够优雅地处理这些类型的错误。API版本
为了简化API版本控制,从Zabbix 2.0.4开始,API的版本与Zabbix本身的版本相匹配。您可以使用该apiinfo.version方法找出您正在使用的API的版本。这对于调整应用程序以使用特定于版本的功能非常有用。我们保证主要版本内部的功能向后兼容性。在主要版本之间进行向后不兼容的更改时,我们通常会在下一版本中将旧功能保留为已弃用,并且仅在之后的版本中将其删除。有时,我们可能会删除主要版本之间的功能而不提供任何向后兼容性。重要的是,您永远不要依赖任何已弃用的功能,并尽快迁移到更新的替代方案。
您可以在API更改日志中跟踪对API所做的所有更改。
上边在官网上介绍的是几个调用方法结合上边的我们自己来根据需求写一个py脚本:
Zabbix可以通过自发现添加主机,不过有时候不准确,通过API添加会更加准确!使用效果:
Excel 格式:
cat zabbix_hosts.py
#!/usr/local/bin/python
#coding:utf-8import json
import urllib2 from urllib2 import URLError import sys import xlrdclass ZabbixTools:
def init(self): self.url = '' self.header = {"Content-Type":"application/json"}def user_login(self): data = json.dumps({ "jsonrpc": "2.0", "method": "user.login", "params": { "user": "admin", "password": "zabbix" }, "id": 0 }) request = urllib2.Request(self.url, data) for key in self.header: request.add_header(key, self.header[key]) 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() self.authID = response['result'] return self.authID def host_get(self,hostName): data = json.dumps({ "jsonrpc":"2.0", "method":"host.get", "params":{ "output":["hostid","name"], "filter":{"host":hostName} }, "auth":self.user_login(), "id":1, }) request = urllib2.Request(self.url, data) for key in self.header: request.add_header(key, self.header[key]) try: result = urllib2.urlopen(request) except URLError as e: if hasattr(e, 'reason'): print 'We failed to reach a server.' print 'Reason: ', e.reason elif hasattr(e, 'code'): print 'The server could not fulfill the request.' print 'Error code: ', e.code else: response = json.loads(result.read()) result.close() print "Number Of %s: " % hostName, len(response['result']) lens=len(response['result']) if lens > 0: return response['result'][0]['name'] else: return ""def hostgroup_get(self, hostgroupName): data = json.dumps({ "jsonrpc":"2.0", "method":"hostgroup.get", "params":{ "output": "extend", "filter": { "name": [ hostgroupName, ] } }, "auth":self.user_login(), "id":1, }) request = urllib2.Request(self.url, data) for key in self.header: request.add_header(key, self.header[key]) try: result = urllib2.urlopen(request) except URLError as e: print "Error as ", e else: response = json.loads(result.read()) result.close() lens=len(response['result']) if lens > 0: self.hostgroupID = response['result'][0]['groupid'] return response['result'][0]['groupid'] else: print "no GroupGet result" return ""def template_get(self, templateName): data = json.dumps({ "jsonrpc":"2.0", "method": "template.get", "params": { "output": "extend", "filter": { "host": [ templateName, ] } }, "auth":self.user_login(), "id":1, }) request = urllib2.Request(self.url, data) for key in self.header: request.add_header(key, self.header[key]) try: result = urllib2.urlopen(request) except URLError as e: print "Error as ", e else: response = json.loads(result.read()) result.close() self.templateID = response['result'][0]['templateid'] return response['result'][0]['templateid'] def host_create(self, hostName,visibleName,hostIp,dnsName,proxyName, hostgroupName, templateName1, templateName2): data = json.dumps({ "jsonrpc":"2.0", "method":"host.create", "params":{ "host": hostName, "name": visibleName, "proxy_hostid": self.proxy_get(proxyName), "interfaces": [ { "type": 1, "main": 1, "useip": 1, "ip": hostIp, "dns": dnsName, "port": "10050" } ], "groups": [ { "groupid": self.hostgroup_get(hostgroupName) } ], "templates": [ { "templateid": self.template_get(templateName1) }, { "templateid": self.template_get(templateName2) } ], }, "auth": self.user_login(), "id":1 }) request = urllib2.Request(self.url, data) for key in self.header: request.add_header(key, self.header[key]) try: result = urllib2.urlopen(request) except URLError as e: print "Error as ", e else: response = json.loads(result.read()) result.close() print "host : %s is created! id is %s\n" % (hostip, response['result']['hostids'][0]) self.hostid = response['result']['hostids'] return response['result']['hostids'] def proxy_get(self, ProxyName): data = json.dumps({ "jsonrpc":"2.0", "method": "proxy.get", "params": { "output": "extend", "selectInterface": "extend", "filter": { "host": [ ProxyName, ] } }, "auth":self.user_login(), "id":1, }) request = urllib2.Request(self.url, data) for key in self.header: request.add_header(key, self.header[key]) try: result = urllib2.urlopen(request) except URLError as e: print "Error as ", e else: response = json.loads(result.read()) result.close() self.templateID = response['result'][0]['proxyid'] return response['result'][0]['proxyid']
if name == "main":
test = ZabbixTools() workbook = xlrd.open_workbook('test.xlsx')for row in xrange(workbook.sheets()[0].nrows): hostname=workbook.sheets()[0].cell(row,0).value visible=workbook.sheets()[0].cell(row,1).value hostip=workbook.sheets()[0].cell(row,2).value dnsname=workbook.sheets()[0].cell(row,3).value proxy=workbook.sheets()[0].cell(row,4).value hostgroup=workbook.sheets()[0].cell(row,5).value hosttemp=workbook.sheets()[0].cell(row,6).value hosttemp1=workbook.sheets()[0].cell(row,7).valuehostgroup=hostgroup.strip() hostnameGet=test.host_get(hostname) if hostnameGet.strip()=='': test.host_create(hostname,visible,hostip,dnsname,proxy,hostgroup,hosttemp,hosttemp1) else: print "%s have exist! Cannot recreate !\n" % hostnameGet
上述是根据表格来定义的那 自定义呢:
结合参考三个脚本:登陆脚本:#!/usr/bin/env pythonimport urllib2import json#定义URL账户密码url = ''username = 'admin'password = 'password'#定义通过HTTP方式访问API地址的函数,后面每次请求API的各个方法都会调用这个函数def requestJson(url,values): data = json.dumps(values)req = urllib2.Request(url, data, {'Content-Type': 'application/json-rpc'})response = urllib2.urlopen(req, data)output = json.loads(response.read())#print outputtry:message = output['result']except:message = output['error']['data']print messagequit()return output['result']
#API接口认证的函数,登录成功会返回一个Token
def authenticate(url, username, password):values = {'jsonrpc': '2.0','method': 'user.login','params': { 'user': username,'password': password},'id': '0'}idvalue = requestJson(url,values)return idvalue定义函数脚本:#!/usr/bin/env python#coding=utf-8 import sysimport argparseimport urllib2import json#定义更新action函数
def mediatypeupdate(mediatypeid,status,auth):values = {'jsonrpc': '2.0','method': 'mediatype.update','params': { "mediatypeid": mediatypeid,"status": status},'auth': auth,'id': '1'}output = requestJson(url,values)#定义读取状态函数def triggerget(auth):values = {'jsonrpc': '2.0',"method":"trigger.get","params": { "output": ["triggerid","description","priority"],"filter": { "value": 1},"expandData":"hostname","sortfield": "priority","sortorder": "DESC"},'auth': auth,'id': '2'}output = requestJson(url,values)return output#定义通过ip获取主机id的函数
def ipgetHostsid(ip,url,auth):values = {'jsonrpc': '2.0','method': 'host.get','params': { 'output': [ "host" ], 'filter': { 'ip': ip},},'auth': auth,'id': '3'}output = requestJson(url,values)return output#定义通过主机id获取开启关闭监控函数
def idupdatehost(status,hostid,url,auth):values = {'jsonrpc': '2.0','method': 'host.update','params': { "hostid": hostid, "status": status},'auth': auth,'id': '4'}output = requestJson(url,values)return output#定义通过项目hostid获取itemid函数def getHostsitemsid(hostid,itemsname,url,auth):values = {'jsonrpc': '2.0','method': "item.get","params": { "output": ["itemids"],"hostids": hostid,"filter":{ "key_": itemsname,},},'auth': auth, 'id': '5' }output = requestJson(url,values)if len(output)==0: return outputelse: return output[0]['itemid']
#定义通过项目id获取监控项目最近值信息的函数
def getHostsitemsvalue(itemid,url,auth):values = {'jsonrpc': '2.0','method': "history.get","params": { "output": "extend","history":3,"itemids":itemid,"sortfield": "clock","sortorder": "DESC","limit":1,},'auth': auth, 'id': '6' }output = requestJson(url,values)if len(output)==0: return outputelse: return output[0]["value"]
#定义更新读取状态action函数
def mediatypeget(mediatypeid,auth):values = {'jsonrpc': '2.0','method': 'mediatype.get','params': { "output": "extend","filter": { "mediatypeid":mediatypeid, }, }, 'auth': auth, 'id': '7' }output = requestJson(url,values)if len(output)==0: return outputelse: return output[0]['status']
#定义maintenance维修模式host函数
def maintenancecreate(maintenancename,active_since,active_till,hostid,auth):values = {'jsonrpc': '2.0','method': 'maintenance.create','params': { "name": maintenancename,"active_since": active_since,"active_till": active_till,"hostids": [hostid],"timeperiods": [{ "timeperiod_type": 0,"every": 1,"dayofweek": 64,"start_time": 64800,"period": 3600}]},'auth': auth,'id': '8'}output = requestJson(url,values)#定义通过模糊获取关闭主机信息函数
def disabledhostget(url,auth):values = {'jsonrpc': '2.0','method': 'host.get',"params": { "output": ["host"],'selectInterfaces': [ "ip" ],"filter": { "status":1}},'auth': auth,'id': '9'}output = requestJson(url,values)return output#定义maintenance维修模式group函数
def maintenancecreategroup(maintenancename,active_since,active_till,groupid,auth):values = {'jsonrpc': '2.0','method': 'maintenance.create','params': { "name": maintenancename,"active_since": active_since,"active_till": active_till,"groupids": [groupid],"timeperiods": [{ "timeperiod_type": 0,"every": 1,"dayofweek": 64,"start_time": 64800,"period": 3600}]},'auth': auth,'id': '10'}output = requestJson(url,values)#定义通过host groups named 获取groupid
def groupnameGroupid(groupname,auth):values = {'jsonrpc': '2.0','method': 'hostgroup.get',"params": { "output": "extend","filter": { "name": [groupname]}},'auth': auth,'id': '11'}output = requestJson(url,values)return output#定义模糊查询维护主机
def maintenanceget(url,auth):values = {'jsonrpc': '2.0','method': 'maintenance.get',"params": { "output": "extend",},'auth': auth,'id': '12'}output = requestJson(url,values)return output#定义批量恢复处于维护主机
def maintenancedelete(maintenanceid,url,auth):values = {'jsonrpc': '2.0','method': 'maintenance.delete',"params": [maintenanceid],'auth': auth,'id': '13'}output = requestJson(url,values)return output#定义通过hostid获取graphid的函数
def getgraphid(hostid,graphname,url,auth):values = {'jsonrpc': '2.0','method': 'graph.get','params': { "output": "name","hostids": hostid,"sortfield": "name",'filter': { "name": graphname},}, 'auth': auth, 'id': '14' } output = requestJson(url,values) return output
调用执行脚本:
#!/usr/bin/env python#coding=utf-8import urllib2import sysimport jsonimport argparsefrom login import from function import #登陆zabbix获取authauth = authenticate(url, username, password)#状态0是启用监控,1是禁用监控status=1#定义操作iphostip='192.168.1.100'#通过hostip获取zabbix hostidhostids=ipgetHostsid(hostip,url,auth)hostid=hostids[0]['hostid']#通过主机id开启关闭监控idupdatehost(status,hostid,url,auth)转载于:https://blog.51cto.com/13120271/2163782