tset123 发表于 2018-8-4 07:07:50

Zabbix api的使用方法(python版)


Zabbix API简介
  时间2013-12-21
  作者 itnihao
  邮箱 itnihao@qq.com
  博客 http://www.itnihao.com
  如需引用,请注明以上信息,谢谢合作
  Zabbix API具有重要的功能,为第三方调用zabbix,批量操作提供可编程接口,,从而轻松的用于自己的业务系统,运维系统相集成。
  Zabbix API是基于前端http协议实现的,也就是可以通过HTTP请求实现的API。API数据传输采用JSON RPC协议。
  由于Zabbix的web前端是PHP语言编程的,而PHP的性能和相关配置参数有极大关系,因此,如果在大型的环境使用,可以对php进行负载均衡,例如开启php多进程等方式来解决负载问题。除了对服务器本身进行优化,尽量减少对API的调用,也是集成第三方系统应该遵循的一个原则。
  在最新的2.2版本中,所有的API都有对应的官方文档和详细说明。对应的地址是
  https://www.zabbix.com/documentation/2.2/manual/api/reference,这里有全部的API用法。
API基本步骤
  A,连接http://x.x.x.x/api_jsonrpc.php,提供用户名密码,并标示HTTP头部Content-Type":"application/json",HTTP方法为post。
  B.获取SESSIONID
  C.通过SESSIONID建立后续的连接
  D.提交POST数据,格式为json,里面放对应的方法,获取需要的数据
  zabbix api usepython的例子,在这个例子中,主要是通过API去获取主机的信息。
#!/usr/bin/env python  
#coding=utf-8
  
#导入模块,urllib2是一个模拟浏览器HTTP方法的模块
  
import json
  
import urllib2
  
import sys
  
from urllib2 import Request, urlopen, URLError, HTTPError
  
#url and url header
  
#zabbix的api 地址,用户名,密码,这里修改为自己实际的参数
  
zabbix_url="http://192.168.0.200/zabbix/api_jsonrpc.php"
  
zabbix_header = {"Content-Type":"application/json"}
  
zabbix_user   = "admin"
  
zabbix_pass   = "zabbix"
  
auth_code   = ""
  
#auth user and password
  
#用户认证信息的部分,最终的目的是得到一个SESSIONID
  
#这里是生成一个json格式的数据,用户名和密码
  
auth_data = json.dumps(
  {
  "jsonrpc":"2.0",
  "method":"user.login",
  "params":
  {
  "user":zabbix_user,
  "password":zabbix_pass
  },
  "id":0
  })
  
# create request object
  
request = urllib2.Request(zabbix_url,auth_data)
  
for key in zabbix_header:
  request.add_header(key,zabbix_header)
  
#auth and get authid
  
try:
  
  result = urllib2.urlopen(request)
  
#对于出错新的处理
  
except HTTPError, e:
  print 'The server couldn\'t fulfill the request, Error code: ', e.code
  
except URLError, e:
  print 'We failed to reach a server.Reason: ', e.reason
  
else:
  response=json.loads(result.read())
  result.close()
  
  '''
  
  如果访问成功或者失败,这里的数据会显示如下
  sucess result:
  {"jsonrpc":"2.0",
  "result":"0d225d8d2a058625f814f3a0749cd218",
  #result后面的值是SESSIONID,每次去访问都会发生变化的
  "id":0}
  errorresult:
  {'code': -32602,
  'data': 'Login name or password is incorrect.',
  'message': 'Invalid params.'}
  
  '''
  
  #判断SESSIONID是否在返回的数据中
  if'result'inresponse:
  auth_code=response['result']
  else:
  printresponse['error']['data']
  
# request json
  
#用得到的SESSIONID去通过验证,获取主机的信息(用http.get方法)
  
if len(auth_code) == 0:
  sys.exit(1)
  
if len(auth_code) != 0:
  get_host_data = json.dumps(
  {
  "jsonrpc":"2.0",
  "method":"host.get",
  "params":{
  "output": "extend",
  },
  "auth":auth_code,
  "id":1,
  })
  # create request object
  request = urllib2.Request(zabbix_url,get_host_data)
  for key in zabbix_header:
  request.add_header(key,zabbix_header)
  # get host list
  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 response
  #显示主机的个数
  print "Number Of Hosts: ", len(response['result'])
  将以上代码保存运行,结果如下:
  {"jsonrpc":"2.0","result":[{
  "maintenances":[],
  "hostid":"10084",
  "proxy_hostid":"0",
  "host":"Zabbix server",
  "status":"0",
  "disable_until":"0",
  "error":"",
  "available":"1",
  "errors_from":"0",
  "lastaccess":"0",
  "ipmi_authtype":"-1",
  "ipmi_privilege":"2",
  "ipmi_username":"",
  "ipmi_password":"",
  "ipmi_disable_until":"0",
  "ipmi_available":"0",
  "snmp_disable_until":"0",
  "snmp_available":"0",
  "maintenanceid":"0",
  "maintenance_status":"0",
  "maintenance_type":"0",
  "maintenance_from":"0",
  "ipmi_errors_from":"0",
  "snmp_errors_from":"0",
  "ipmi_error":"",
  "snmp_error":"",
  "jmx_disable_until":"0",
  "jmx_available":"0",
  "jmx_errors_from":"0",
  "jmx_error":"",
  "name":"Zabbix server"}
  ],
  "id":1}
  好了,一个简单的API使用例子就完成了。
  关于更多的API使用,可以阅读官方文档,学习更多的方法,用API的前提是对zabbix操作熟悉,不然很多API你不知道是干嘛用的。
  本文仅作抛砖引玉之用,希望大家举一反三,欢迎交流。
页: [1]
查看完整版本: Zabbix api的使用方法(python版)