python調用zabbix api接口實時展示數據

關於API

zabbix擁有完善的API,基於JSON RPC提供資產,主機,主機組,監控項,告警等方面的接口。在做運維自動化時,需要用API功能對zabbix二次開發。本文我將介紹如何用python信使用zabbix的API。

API介紹:

API地址:http://你的zabbix域名/api_jsonrpc.php
API請求方法,採用POST
API請求數據結構
{
"jsonrpc": "2.0", // 版本
"method": "user.login", // 接口方法名
"params": {
//接口參數
},
"auth": "", // 登錄後的session,未登錄爲空
"id": 1 // 任意數
}

API常用的接口

user.login ,用戶登錄
host.get(create|delete|update),主機操作
hostgroup.get(create|delete|update),主機組操作
item.getcreate|delete|update),監控項目操作
history.get,歷史數據查詢
event.get,事件查詢
trigger.get ,觸發器查詢

近日公司準備自已做一個運維管理平臺,其中的監控部分,打算調用zabbix api接口來進行展示。

經過思考之後,計劃獲取如下內容:

1、 獲得認證密鑰

2、 獲取zabbix所有的主機組

3、 獲取單個組下的所有主機

4、 獲取某個主機下的所有監控項

5、 獲取某個監控項的歷史數據

6、 獲取某個監控項的最新數據
計劃最後展示框架如下內容(這只是值方面,其它的會再加):

主機組1 ----主機名1---監控項1----當前值

          ---監控項2----當前值

----主機名2----監控項1----當前值

         ----監控項2----當前值

主機組2 ----主機名3---監控項1----當前值

          ---監控項2----當前值

----主機名4----監控項1----當前值

          ----監控項2----當前值

進入正題

user.login方法獲取zabbix server的認證結果
官方地址:```
https://www.zabbix.com/documentation/2.2/manual/api/reference/user/login

python腳本:

[root@yang python]# cat auth.py
#!/usr/bin/env python2.7
#coding=utf-8
import json
import urllib2
# based url and required header
url = "http://1.1.1.1/zabbix/api_jsonrpc.php"
header = {"Content-Type":"application/json"}
# auth user and password
data = json.dumps(
{
   "jsonrpc": "2.0",
   "method": "user.login",
   "params": {
   "user": "Admin",
   "password": "zabbix"
},
"id": 0
})
# create request object
request = urllib2.Request(url,data)
for key in header:
   request.add_header(key,header[key])
# auth and get authid
try:
   result = urllib2.urlopen(request)
except URLError as e:
   print "Auth Failed, Please Check Your Name AndPassword:",e.code
else:
   response = json.loads(result.read())
   result.close()
print"Auth Successful. The Auth ID Is:",response['result']

python腳本運行結果:

[root@yang python]# python auth.py
Auth Successful. The Auth ID Is: a0b82aae0842c2041386a61945af1180

curl命令:

curl -i -X POST -H 'Content-Type:application/json' -d '{"jsonrpc":
"2.0","method":"user.login","params":{"user":"admin","password":"zabbix"},"auth":
null,"id":0}' http://1.1.1.1/zabbix/api_jsonrpc.php

curl命令運行結果:

{"jsonrpc":"2.0","result":"b895ce91ba84fe247e444817c6773cc3","id":0}
  1. hostgroup.get方法獲取所有主機組ID

把認證密鑰放到腳本中,每次獲取數據時都需要認證。此處是獲取zabbix server上的所有主機組名稱與ID號。

官方地址:https://www.zabbix.com/documentation/2.2/manual/api/reference/hostgroup/get

python腳本:

[root@yang python]# catget_hostgroup_list.py

!/usr/bin/env python2.7
coding=utf-8
import json
import urllib2

based url and required header
url = "http://1.1.1.1/zabbix/api_jsonrpc.php"
header = {"Content-Type":"application/json"}

request json
data = json.dumps(
{
"jsonrpc":"2.0",
"method":"hostgroup.get",
"params":{
"output":["groupid","name"],
},
"auth":"3c0e88885a8cf8af9502b5c850b992bd", # theauth id is what auth script returns, remeber it is string
"id":1,
})

create request object
request = urllib2.Request(url,data)
for key in header:
request.add_header(key,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()
print "Number Of Hosts: ", len(response['result'])
#print response
for group in response['result']:
print "Group 
ID:",group['groupid'],"\tGroupName:",group['name']

python腳本執行結果:

[root@yang python]# pythonget_hostgroup_list.py
Number Of Hosts:  12
Group ID: 11    Group Name: DB Schedule
Group ID: 14    Group Name: DG-WY-KD-Server
Group ID: 5     Group Name: Discovered hosts
Group ID: 7     Group Name: Hypervisors
Group ID: 2     Group Name: Linux servers
Group ID: 8     Group Name: monitored_linux
Group ID: 9     Group Name: qsmind
Group ID: 12    Group Name: qssec
Group ID: 13    Group Name: switch
Group ID: 1     Group Name: Templates
Group ID: 6     Group Name: Virtual machines
Group ID: 4     Group Name: Zabbix servers

curl命令:

curl -i -X POST -H 'Content-Type:application/json' -d '{"jsonrpc": "2.0","method":"hostgroup.get","params":{"output":["groupid","name"]},"auth":"11d2b45415d5de6770ce196879dbfcf1","id": 0}' http://1.1.1.1/zabbix/api_jsonrpc.php

curl執行結果:

{"jsonrpc":"2.0","result":[{"groupid":"11","name":"DBSchedule"},{"groupid":"14","name":"DG-WY-KD-Server"},{"groupid":"5","name":"Discoveredhosts"},{"groupid":"7","name":"Hypervisors"},{"groupid":"2","name":"Linuxservers"},{"groupid":"8","name":"monitored_linux"},{"groupid":"9","name":"qsmind"},{"groupid":"12","name":"qssec"},{"groupid":"13","name":"switch"},{"groupid":"1","name":"Templates"},{"groupid":"6","name":"Virtualmachines"},{"groupid":"4","name":"Zabbixservers"}],"id":0}
  1. host.get方法獲取單個主機組下所有的主機ID。

根據標題2中獲取到的主機組id,把主機組id填入到下邊腳本中,就可以獲得該主機組下所有的主機id。

官方地址:https://www.zabbix.com/documentation/2.2/manual/api/reference/host/get

python腳本:

[root@yang python]# cat get_group_one.py
#!/usr/bin/env python2.7
#coding=utf-8
import json
import urllib2
# based url and required header
url = "http://1.1.1.1/zabbix/api_jsonrpc.php"
header = {"Content-Type":"application/json"}
# request json
data = json.dumps(
{
   "jsonrpc":"2.0",
   "method":"host.get",
   "params":{
       "output":["hostid","name"],
       "groupids":"14",
   },
   "auth":"3c0e88885a8cf8af9502b5c850b992bd", # theauth id is what auth script returns, remeber it is string
   "id":1,
})
# create request object
request = urllib2.Request(url,data)
for key in header:
   request.add_header(key,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()
   print "Number Of Hosts: ", len(response['result'])
   for host in response['result']:
       print "Host ID:",host['hostid'],"HostName:",host['name']

python腳本執行結果:

[root@yang python]# pythonget_group_one.py  
Number Of Hosts:  4
Host ID: 10146 Host Name: DG-WY-KD-3F3B-00
Host ID: 10147 Host Name: DG-WY-KD-3F3B-01
Host ID: 10148 Host Name: DG-WY-KD-3F3B-02
Host ID: 10149 Host Name: DG-WY-KD-3F3B-03

curl命令:

curl -i -X POST -H'Content-Type: application/json' -d '{"jsonrpc":"2.0","method":"host.get","params":{"output":["hostid","name"],"groupids":"14"},"auth":"11d2b45415d5de6770ce196879dbfcf1","id": 0}' 
http://1.1.1.1/zabbix/api_jsonrpc.php

curl命令執行結果:

{"jsonrpc":"2.0","result":[{"hostid":"10146","name":"DG-WY-KD-3F3B-00"},{"hostid":"10147","name":"DG-WY-KD-3F3B-01"},{"hostid":"10148","name":"DG-WY-KD-3F3B-02"},{"hostid":"10149","name":"DG-WY-KD-3F3B-03"}],"id":0}

itemsid.get方法獲取單個主機下所有的監控項ID
根據標題3中獲取到的所有主機id與名稱,找到你想要獲取的主機id,獲取它下面的所有items。

官方地址:https://www.zabbix.com/documentation/2.2/manual/api/reference/item

python腳本:

[root@yang python]# cat get_items.py
#!/usr/bin/env python2.7
#coding=utf-8
import json
import urllib2
# based url and required header
url = "http://1.1.1.1/zabbix/api_jsonrpc.php"
header = {"Content-Type":"application/json"}
# request json
data = json.dumps(
{
   "jsonrpc":"2.0",
   "method":"item.get",
   "params":{
       "output":["itemids","key_"],
       "hostids":"10146",
   },
   "auth":"3c0e88885a8cf8af9502b5c850b992bd", # theauth id is what auth script returns, remeber it is string
   "id":1,
})
# create request object
request = urllib2.Request(url,data)
for key in header:
   request.add_header(key,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()
   print "Number Of Hosts: ", len(response['result'])
   for host in response['result']:
       print host
       #print "Host ID:",host['hostid'],"HostName:",host['name']

python腳本運行結果:

[root@yang python]# python get_items.py
Number Of Hosts: 54
{u'itemid': u'24986', u'key_':u'agent.hostname'}
{u'itemid': u'24987', u'key_':u'agent.ping'}
{u'itemid': u'24988', u'key_':u'agent.version'}
{u'itemid': u'24989', u'key_':u'kernel.maxfiles'}
{u'itemid': u'24990', u'key_':u'kernel.maxproc'}
{u'itemid': u'25157', u'key_':u'net.if.in[eth0]'}
{u'itemid': u'25158', u'key_':u'net.if.in[eth1]'}
… …

curl命令:

curl -i -X POST -H 'Content-Type:application/json' -d '{"jsonrpc":"2.0","method":"item.get","params":{"output":"itemids","hostids":"10146","search":{"key_":"net.if.out[eth2]"}},"auth":"11d2b45415d5de6770ce196879dbfcf1","id": 0}' http://1.1.1.1/zabbix/api_jsonrpc.php
#此處加上了單個key的名稱

curl命令執行結果:

{"jsonrpc":"2.0","result":[{"itemid":"25154"}],"id":0}

history.get方法獲取單個監控項的歷史數據
根據第4項的獲取到的所有items id的值,找到想要監控的那項,獲取它的歷史數據。

官方地址:https://www.zabbix.com/documentation/2.2/manual/api/reference/history/get

python腳本:

[root@yang python]# catget_items_history.py
#!/usr/bin/env python2.7
#coding=utf-8
import json
import urllib2
# based url and required header
url = "http://1.1.1.1/zabbix/api_jsonrpc.php"
header = {"Content-Type":"application/json"}
# request json
data = json.dumps(
{
   "jsonrpc":"2.0",
   "method":"history.get",
   "params":{
       "output":"extend",
       "history":3,
       "itemids":"25159",
       "limit":10
   },
   "auth":"3c0e88885a8cf8af9502b5c850b992bd", # theauth id is what auth script returns, remeber it is string
   "id":1,
})
# create request object
request = urllib2.Request(url,data)
for key in header:
   request.add_header(key,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()
   print "Number Of Hosts: ", len(response['result'])
   for host in response['result']:
       print host
       #print "Host ID:",host['hostid'],"HostName:",host['name']

python腳本執行結果:

[root@yang python]# pythonget_items_history.py
Number Of Hosts:  10
{u'itemid': u'25159', u'ns': u'420722133',u'value': u'3008', u'clock': u'1410744079'}
{u'itemid': u'25159', u'ns': u'480606614',u'value': u'5720', u'clock': u'1410744139'}
{u'itemid': u'25159', u'ns': u'40905600',u'value': u'6144', u'clock': u'1410744200'}
{u'itemid': u'25159', u'ns': u'175337062',u'value': u'2960', u'clock': u'1410744259'}
{u'itemid': u'25159', u'ns': u'202705084',u'value': u'3032', u'clock': u'1410744319'}
{u'itemid': u'25159', u'ns': u'263158421',u'value': u'2864', u'clock': u'1410744379'}
{u'itemid': u'25159', u'ns': u'702285081',u'value': u'7600', u'clock': u'1410744439'}
{u'itemid': u'25159', u'ns': u'231191890',u'value': u'3864', u'clock': u'1410744499'}
{u'itemid': u'25159', u'ns': u'468566742',u'value': u'3112', u'clock': u'1410744559'}
{u'itemid': u'25159', u'ns': u'421679098',u'value': u'2952', u'clock': u'1410744619'}

curl命令:

curl -i -X POST -H 'Content-Type:application/json' -d '{"jsonrpc":"2.0","method":"history.get","params":{"history":3,"itemids":"25154","output":"extend","limit":10},"auth":"11d2b45415d5de6770ce196879dbfcf1","id": 0}' http://1.1.1.1/zabbix/api_jsonrpc.php

curl命令運行結果:

{"jsonrpc":"2.0","result":[{"itemid":"25154","clock":"1410744134","value":"4840","ns":"375754276"},{"itemid":"25154","clock":"1410744314","value":"5408","ns":"839852515"},{"itemid":"25154","clock":"1410744374","value":"7040","ns":"964558609"},{"itemid":"25154","clock":"1410744554","value":"4072","ns":"943177771"},{"itemid":"25154","clock":"1410744614","value":"8696","ns":"995289716"},{"itemid":"25154","clock":"1410744674","value":"6144","ns":"992462863"},{"itemid":"25154","clock":"1410744734","value":"6472","ns":"152634327"},{"itemid":"25154","clock":"1410744794","value":"4312","ns":"479599424"},{"itemid":"25154","clock":"1410744854","value":"4456","ns":"263314898"},{"itemid":"25154","clock":"1410744914","value":"8656","ns":"840460009"}],"id":0}

history.get方法獲取單個監控項最後的值
只需把上個腳本中或curl中的limit參數改爲1就可。

此時監控項的數據已拿到了,接下來的把它傳給前臺展示就行了。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章