欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Python 调用 zabbix api的方法示例

程序员文章站 2023-01-03 21:11:00
前提准备: 1.使用python requests模块 2.了解json 3.zabbix api的具体调用建议先浏览一下官网 先上代码: import...

前提准备:

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内容之所以这样写是的,json字符串里面千万不能使用tab键。

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

字符串建议先浏览一下官网的说明,要强调的是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查询:

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

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