Python 调用 zabbix api的方法示例

时间:2022-10-02 12:09:14

前提准备:

1.使用python requests模块

2.了解json

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

先上代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
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键。

?
1
2
3
4
5
6
7
8
9
login = {
  "jsonrpc": "2.0",
  "method": "user.login",
  "params": {
    "user": "Admin",     #根据自己的情况填
    "password": "zabbix"   #根据自己的条件填写
  },
  "id": 1
}

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

?
1
2
3
4
5
"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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
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

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

原文链接:http://blog.51cto.com/jackor/2339279