Python教程

Python 调用 zabbix api的方法示例

本文主要是介绍Python 调用 zabbix api的方法示例,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

前提准备:

1.使用python requests模块

2.了解json

3.zabbix api的具体调用建议先浏览一下官网

先上代码:

import requests,json
#
#url一定要正确,IP地址换成自己zabbix服务器的
zbx_url = "http://192.168.60.130:3080/zabbix/api_jsonrpc.php"

#在post请求头部必须要有 'Content-Type': 'application/json-rpc'
headers = {'Content-Type': 'application/json-rpc'}

#传递json 数据到api;登录
login = {
  "jsonrpc": "2.0",
  "method": "user.login",
  "params": {
    "user": "Admin",
    "password": "zabbix"
  },
  "id": 1
}
#首次登陆不用在json字段中写 auth,否则会有相关的报错

#将数据发送到api
ret = requests.post(zbx_url, data=json.dumps(login), headers=headers)

#对结果进行序列化
ret = ret.json()
auth = ret['result']

#获取问题主机json
data = {
  "jsonrpc": "2.0",
  "method":"trigger.get",
  "params": {
    # output表示输出结果包含参数有哪些
    "output": [
      "triggerid",
      "description",
      "status",
      "value",
      "priority",
      "lastchange",
      "recovery_mode",
      "hosts",
      "state",
    ],
    "selectHosts": "hosts", # 需包含主机ID信息,以便于根据主机ID查询主机信息
    "selectItems":"items",
    "filter": {
      # 筛选条件
       "value": 1,#value值为1表示有问题
       "status": 0#status为0表示已启用的trigger
    },
  },
  "auth":auth,#这里的auth就是登录后获取的
  'id':'1'#这个id可以随意
}

#将查询数据发送到zabbix-server
ret = requests.post(zbx_url,data=json.dumps(data),headers=headers)

respone_result = ret.json()['result']#对结果进行json序列化

print(respone_result)

下面简单介绍一下上诉代码:

要调用zabbix api获取数据,首先要获得auth这一串字符用户后续的内容获取,auth可以看做是一种你与zabbix-server之间的"暗号";

登录的json内容之所以这样写是zabbix官方规定的,json字符串里面千万不能使用tab键。

login = {
  "jsonrpc": "2.0",
  "method": "user.login",
  "params": {
    "user": "Admin",     #根据自己的情况填
    "password": "zabbix"   #根据自己的条件填写
  },
  "id": 1
}

获取问题主机的json字符串建议先浏览一下官网的说明,要强调的是output和filter这两个key,output就是zabbix api返回来的内容,filter相当于是过滤条件:

"filter": {
      # 筛选条件
       "value": 1,       #value值为1表示有问题
       "status": 0       #status为0表示已启用的trigger
    },

上诉代码表示 value=1 and status=0,是一种与关系,很像查数据库表时候的过滤操作。

强烈建议先大概浏览一下官网文档

PS:Python通过Zabbix API获得数据的方法

Zabbix API查询:https://www.zabbix.com/documentation/2.0/manual/appendix/api/api

import json,urllib2
from urllib2 import Request, urlopen, URLError, HTTPError
#url and url header
#zabbix的api 地址,用户名,密码,这里修改为自己实际的参数
zabbix_url="http://10.16.2.40/zabbix/api_jsonrpc.php"
zabbix_header = {"Content-Type":"application/json"}
zabbix_user  = "admin"
zabbix_pass  = "password"
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[key])

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())
  print response
  result.close()

#判断SESSIONID是否在返回的数据中
if 'result' in response:
  auth_code=response['result']
else:
  print response['error']['data']
                                                                                          
# request json
#用得到的SESSIONID去通过验证,获取主机的信息(用http.get方法)
if len(auth_code) <> 0:
  host_list=[]
  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[key])

  # 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()                                                                                    
    #将所有的主机信息显示出来
    for r in response['result']:
    #  print r['hostid'],r['host']
      host_list.append(r['hostid'])
    #显示主机的个数
    print "Number Of Hosts: ", len(host_list)

  

  #返回所有hostid==10251的主机,并只查询name包含“CPU Usage”字段的item,并按照name排序
  get_item_data = json.dumps({
    "jsonrpc": "2.0",
    "method": "item.get",
    "params": {
      "output": "extend",
      "hostids": "10251"
      "search": {
        #"key_": 'perf_counter[\Processor Information(_Total)\% Processor Time]'
        "name": "CPU Usage"
      },
      "sortfield": "name"
    },
    "auth": auth_code,
    "id": 1
  })

  request = urllib2.Request(zabbix_url,get_item_data)
  for key in zabbix_header:
    request.add_header(key,zabbix_header[key])
  result = urllib2.urlopen(request)

  try:
    result = urllib2.urlopen(request)  
    response = json.loads(result.read())
    for r in response['result']:
      print r['itemid'],r['hostid']
    result.close()  
  except:
    pass

  #通过hostid获取相应的graphid
  get_graph_data = json.dumps({
    "jsonrpc": "2.0",
    "method": "graphitem.get",
    "params": {
      "output": "extend",
      "expandData": 1,
      "itemids": "33712"
    },
    "auth": auth_code,
    "id": 1
  })
  request = urllib2.Request(zabbix_url,get_graph_data)
  for key in zabbix_header:
    request.add_header(key,zabbix_header[key])
  result = urllib2.urlopen(request)

  try:
    result = urllib2.urlopen(request)  
    response = json.loads(result.read())
    for r in response['result']:
      print r['itemid'],r['graphid']
    result.close()  
  except:
    pass

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持找一找教程网。

这篇关于Python 调用 zabbix api的方法示例的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!