ZABBIX API简介及使用

ZABBIX API简介及使用

2023年7月10日发(作者:)

ZABBIX API简介及使用

API简介

Zabbix API开始扮演着越来越重要的角色,尤其是在集成第三方软件和自动化日常任务时。很难想象管理数千台服务器而没有自动化是多么的困难。Zabbix API为批量操作、第三方软件集成以及其他作用提供可编程接口。

Zabbix API是在1.8版本中开始引进并且已经被广泛应用。所有的Zabbix移动客户端都是基于API,甚至原生的WEB前端部分也是建立在它之上。Zabbix API 中间件使得架构更加模块化也避免直接对数据库进行操作。它允许你通过JSON RPC协议来创建、更新和获取Zabbix对象并且做任何你喜欢的操作【当然前提是你拥有认证账户】。

Zabbix API提供两项主要功能:

远程管理Zabbix配置

远程检索配置和历史数据

使用JSON

API 采用JSON-RPC实现。这意味着调用任何函数,都需要发送POST请求,输入输出数据都是以JSON格式。大致工作流如下:

准备JSON对象,它描述了你想要做什么(创建主机,获取图像,更新监控项等)。

采用POST方法向/zabbix/api_发送此JSON对象. /zabbix/是Zabbix前端地址。api_是调用API的PHP脚本。可在安装可视化前端的目录下找到。

获取JSON格式响应。

注:请求除了必须是POST方法之外,HTTP Header Content-Type必须为【application/jsonrequest,application/json-rpc,application/json】其中之一。

可以采用脚本或者任何"手动"支持JSON RPC的工具来使用API。而首先需要了解的就是如何验证和如何使用验证ID来获取想要的信息。后面的演示会以Python脚本和基于Curl的例子来呈现API的基本使用。

基本请求格式

Zabbix API 简化的JSON请求如下:

1. {

2. "jsonrpc": "2.0",

3. "method": "",

4. "params": {

5. "param_1_name": "param_1_value",

6. "param_2_name": "param_2_value"

7. },

8. "id": 1, 9. "auth": "159121b60d19a9b4b55d49e30cf12b81",

10. }

下面一行一行来看:

"jsonrpc": "2.0"-这是标准的JSON RPC参数以标示协议版本。所有的请求都会保持不变。

"method": ""-这个参数定义了真实执行的操作。例如:、等等

• "params"-这里通过传递JSON对象来作为特定方法的参数。如果你希望创建监控项,"name"和"key_"参数是需要的,每个方法需要的参数在Zabbix API文档中都有描述。

• "id": 1-这个字段用于绑定JSON请求和响应。响应会跟请求有相同的"id"。在一次性发送多个请求时很有用,这些也不需要唯一或者连续

• "auth": "159121b60d19a9b4b55d49e30cf12b81"-这是一个认证令牌【authentication token】用以鉴别用户、访问API。这也是使用API进行相关操作的前提-获取认证ID。

API 使用

• 环境准备

Zabbix API是基于JSON-RPC 2.0规格,具体实现可以选择任何你喜欢的编程语言或者手动方式。这里我们采用的Python和基于Curl的方式来做示例。Python 2.7版本已经支持JSON,所以不再需要其他模块组件。当然可以采用Perl、Ruby、PHP之类的语言,使用前先确保相应JSON模块的安装。

• 身份验证

任何Zabbix API客户端在真正工作之前都需要验证它自身。在这里是采用方法。这个方法接受一个用户名和密码作为参数并返回验证ID,一个安全哈希串用于持续的API调用(在使用之前该验证ID均有效)。具体Python代码如下:

1. #!/usr/bin/env python2.7

2. #coding=utf-8

3.

4. import json

5. import urllib2

6.

7. # based url and required header

8. url = "/api_"

9. header = {"Content-Type": "application/json"}

10. 11. # auth user and password

12. data = (

13. {

14. "jsonrpc": "2.0",

15. "method": "",

16. "params": {

17. "user": "Admin",

18. "password": "zabbix"

19. },

20. "id": 0

21. })

22.

23. # create request object

24. request = t(url,data)

25. for key in header:

26. _header(key,header[key])

27.

28. # auth and get authid

29. try:

30. result = n(request)

31. except URLError as e:

32. print "Auth Failed, Please Check Your Name And Password:",

33. else:

34. response = (())

35. ()

36. print "Auth Successful. The Auth ID Is:",response['result']

这里需要确保URL中的用户名和密码匹配。下面是运行结果:

可以看到,成功连接并认证。现在有了验证ID,它能够在新的API调用中被重用。

下面再来看基于CURL的方式来进行验证是如何实现的:

1. curl -i -X POST -H 'Content-Type:application/json' -d'{"jsonrpc": "2.0","method":"ticate","params":{"user":"Admin","password":"zabbix"},"auth": null,"id":0}' /api_ • 一般操作

这里举例说明如何获取监控主机列表【host list】。这段脚本需要采用中获取的验证ID并执行方法来获取主机列表。来看具体代码get_:

1. #!/usr/bin/env python2.7

2. #coding=utf-8

3.

4. import json

5. import urllib2

6.

7. # based url and required header

8. url = "/api_"

9. header = {"Content-Type": "application/json"}

10.

11. # request json

12. data = (

13. {

14. "jsonrpc":"2.0",

15. "method":"",

16. "params":{

17. "output":["hostid","name"],

18. "filter":{"host":""}

19. },

20. "auth":"2ee379e516f386ca4c24da7fd9fd5bb4", # the auth id is what auth

script returns, remeber it is string

21. "id":1,

22. })

23. 24. # create request object

25. request = t(url,data)

26. for key in header:

27. _header(key,header[key])

28.

29. # get host list

30. try:

31. result = n(request)

32. except URLError as e:

33. if hasattr(e, 'reason'):

34. print 'We failed to reach a server.'

35. print 'Reason: ',

36. elif hasattr(e, 'code'):

37. print 'The server could not fulfill the request.'

38. print 'Error code: ',

39. else:

40. response = (())

41. ()

42.

43. print "Number Of Hosts: ", len(response['result'])

44.

45. for host in response['result']:

46. print "Host ID:",host['hostid'],"Host Name:",host['name']

部分结果列表:

对比基于CURL的访问方式: curl -i -X POST -H 'Content-Type: application/json' -d

'{"jsonrpc":"2.0","method":"","params":{"output":["hostid","name"],"filter":{"host":""}},"auth":"ecc543db662930c122b5fbedee60cc63","id":1}'/api_ 结果太多,未予显示。比较来看,采用脚本可以有更多的灵活性,而基于CURL的方式,对结果的处理不是很方便。原理则都是相通的。

除了这些获取信息以外,采用API调用同样可以进行创建操作,更新操作和删除操作等等。这也很容易让我们联想起数据库操作,当然比较这些采用API调用获取结果的方式,也不能忘掉这种最直接而危险的方式。在开始讨论中已经提到,Zabbix现在自带的前端实现部分是采用数据库操作,部分是基于API调用。在API还不是很成熟的现在,具体采用哪种方式,需要根据业务需求再来确定。

• 数据流程

下面的流程图代表了Zabbix API 工作的典型工作流。验证(方法)是获取验证ID的强制步骤。这个ID又允许我们调用API提供的任何权限允许的方法来进行操作。在之前的例子中没有提到方法,这也是一次验证ID能够重复使用的原因所在。使用方法后将会使验证ID失效,后面的操作将不能再使用此ID。

[root@localhost ~]# vim

#!/usr/bin/env python2.7

#coding=utf-8

import json

import urllib2

# based url and required header

url = "192.168.30.64/zabbix/api_"

header = {"Content-Type": "application/json"}

# auth user and password

data = (

{

"jsonrpc": "2.0",

"method": "",

"params": {

"user": "admin",

"password": "zabbix"

},

"id": 0

})

# create request object

request = t(url,data)

for key in header:

_header(key,header[key])

# auth and get authid

try:

result = n(request)

except URLError as e:

print "Auth Failed, Please Check Your Name And Password:",

else:

response = (())

()

print "Auth Successful. The Auth ID Is:",response['result']

~

"" [新] 31L, 773C 已写入

[root@localhost ~]# python

Auth Successful. The Auth ID Is: 1315f0020aa8a8acd7df098e13d4506c

[root@localhost ~]# curl -i -X POST -H 'Content-Type:application/json' -d'{"jsonrpc":

"2.0","method":"ticate","params":{"user":"Admin","password":"zabbix"},"auth":

null,"id":0}' 192.168.30.64/zabbix/api_

HTTP/1.1 200 OK

Date: Wed, 24 Apr 2013 07:01:26 GMT

Server: Apache/2.2.15 (CentOS)

X-Powered-By: PHP/5.3.3

Content-Length: 68

Connection: close

Content-Type: application/json

{"jsonrpc":"2.0","result":"c61b079167baa4741aa642df7ae4c002","id":0}[root@localhost ~]#

[root@localhost ~]#

有效的auth token 为 681e51633ccbd5cabeea19ec5d3e4e19。

[root@localhost ~]# vim

根据auth token 获取host列表

#!/usr/bin/env python2.7

#coding=utf-8

import json

import urllib2

# based url and required header

url = "192.168.30.64/zabbix/api_" header = {"Content-Type": "application/json"}

# request json

data = (

{

"jsonrpc":"2.0",

"method":"",

"params":{

"output":["hostid","name"],

"filter":{"host":""}

},

"auth":"2ee379e516f386ca4c24da7fd9fd5bb4", # the auth id is what auth script returns,

remeber it is string

"id":1,

})

# create request object

request = t(url,data)

for key in header:

_header(key,header[key])

# get host list

try:

result = n(request)

except URLError as e:

if hasattr(e, 'reason'):

print 'We failed to reach a server.'

print 'Reason: ',

elif hasattr(e, 'code'):

print 'The server could not fulfill the request.'

print 'Error code: ',

else:

response = (())

()

print "Number Of Hosts: ", len(response['result'])

for host in response['result']:

print "Host ID:",host['hostid'],"Host Name:",host['name']

"" [新] 39L, 1147C 已写入

[root@localhost ~]# python

Auth Successful. The Auth ID Is: 681e51633ccbd5cabeea19ec5d3e4e19

[# 681e51633ccbd5cabeea19ec5d3e4e19^C

[root@localhost ~]# curl -i -X POST -H 'Content-Type:application/json' -d'{"jsonrpc":

"2.0","method":"ticate","params":{"user":"admin","password":"zabbix"},"auth":

null,"id":0}' 192.168.30.64/zabbix/api_

HTTP/1.1 200 OK

Date: Wed, 24 Apr 2013 07:05:01 GMT

Server: Apache/2.2.15 (CentOS) X-Powered-By: PHP/5.3.3

Content-Length: 68

Connection: close

Content-Type: application/json

{"jsonrpc":"2.0","result":"6cecc5779b94de6cc834d074aa90e41f","id":0}[root@localhost ~]#

[root@localhost ~]# vim

# request json

data = (

{

"jsonrpc":"2.0",

"method":"",

"params":{

"output":["hostid","name"],

"filter":{"host":""}

},

"auth":"681e51633ccbd5cabeea19ec5d3e4e19", # the auth id is what auth script returns,

remeber it is string

"id":1,

})

# create request object

request = t(url,data)

for key in header:

_header(key,header[key])

# get host list

try:

result = n(request)

except URLError as e:

if hasattr(e, 'reason'):

print 'We failed to reach a server.'

print 'Reason: ',

elif hasattr(e, 'code'):

print 'The server could not fulfill the request.'

print 'Error code: ',

else:

response = (())

()

print "Number Of Hosts: ", len(response['result'])

for host in response['result']:

print "Host ID:",host['hostid'],"Host Name:",host['name']

"" 39L, 1147C 已写入

[root@localhost ~]# python

Number Of Hosts: 3

Host ID: 10084 Host Name: IMS Server

Host ID: 10085 Host Name: test

Host ID: 10086 Host Name: 172.16.1.2

采用错误的auth token不能获取host 列表。

[root@localhost ~]# curl -i -X POST -H 'Content-Type: application/json' -d

'{"jsonrpc":"2.0","method":"","params":{"output":["hostid","name"],"filter":{"host":""}},"auth":"ecc543db662930c122b5fbedee60cc63","id":1}'

192.168.30.64/zabbix/api_

HTTP/1.1 200 OK

Date: Wed, 24 Apr 2013 07:07:35 GMT

Server: Apache/2.2.15 (CentOS)

X-Powered-By: PHP/5.3.3

Content-Length: 100

Connection: close

Content-Type: application/json

{"jsonrpc":"2.0","error":{"code":-32602,"message":"Invalid params.","data":"Not

authorized"},"id":1}[root@localhost ~]#

使用正确的认证token才能获取host类型。

[root@localhost ~]# curl -i -X POST -H 'Content-Type: application/json' -d

'{"jsonrpc":"2.0","method":"","params":{"output":["hostid","name"],"filter":{"host":""}},"auth":"681e51633ccbd5cabeea19ec5d3e4e19","id":1}'

192.168.30.64/zabbix/api_

HTTP/1.1 200 OK

Date: Wed, 24 Apr 2013 07:07:58 GMT

Server: Apache/2.2.15 (CentOS)

X-Powered-By: PHP/5.3.3

Content-Length: 146

Connection: close

Content-Type: application/json

{"jsonrpc":"2.0","result":[{"hostid":"10084","name":"IMS

Server"},{"hostid":"10085","name":"test"},{"hostid":"10086","name":"172.16.1.2"}],"id":1}[root@localhost ~]#

[root@localhost ~]#

Curl命令获取zabbix信息

Monitoring Zabbix API Curl-based examples of using Zabbix JSON RPC

This document includes some examples which are based on cURL to invoke Zabbix

API through JSON RPC. Through command-line-based scripts, Zabbix API is

invoked to provide resource monitoring information. The output of the executed

shell scripts are the monitoring information results as responses to JSON RPC

queries. To be noticed that a resource is called “item” by Zabbix API. Before

monitoring any resource, user authentication information is required.

To get user authentication information, “ticate” method is used in the

JSON RPC query. The following shell script is used to get user authentication

information:

#!/bin/bash

curl -i -X POST -H 'Content-Type:application/json' -d'{"jsonrpc":

"2.0","method":"ticate","params":{"user":"Admin","password":"zabbix"},"auth": null,"id":0}' 127.0.0.1/zabbix/api_

The response to this query has the following result, which is the output of the

executed shell script “”:

{"jsonrpc":"2.0","result":"6705db5c5bdbd1d02a1f53857be6b200","id":0}

This result is used for further JSON RPC queries. To get information about a

specific host, in addition to user authentication information, the name of the host

should be given in the JSON RPC query. “” method is used to get information about a specific host. Use the parameter “host” to give the host name,

in the following example the host name is “Zabbix server”:

#!/bin/bash

curl -i -X POST -H 'Content-Type: application/json' -d

'{"jsonrpc":"2.0","method":"","params":{"output":"extend","filter":{"host":"Zabbix

server"}},"auth":"6705db5c5bdbd1d02a1f53857be6b200","id":1}'

127.0.0.1/zabbix/api_

After executing the “” script, the response to the JSON RPC query has

the following result:

{"jsonrpc":"2.0","result":[{"maintenances":[{"maintenanceid":"0"}],"hostid":"10017","proxy_hostid":"0","host":"Zabbix

server","dns":"","useip":"1","ip":"127.0.0.1","port":"10050","status":"0","disable_until":"0","error":"","available":"1","errors_from":"0","lastaccess":"0","inbytes":"0","outbytes":"0","useipmi":"0","ipmi_port":"623","ipmi_authtype":"0","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_ip":"","ipmi_errors_from":"0","snmp_errors_from":"0","ipmi_error":"","snmp_error":""}],"id":1}

This result includes information about the host. The “hostid”:”10017”, is one of

the information parameters, which can be used for further request along with user

authentication results.

To monitor any resource (item), “” is used as the method of JSON RPC

query. The authentication result and the host ID received from the previous JSON

RPC queries are used as input to some parameters of the JSON RPC query in the following script, which is used to get item ID. However, when using

JSON RPC to invoke Zabbix API, the parameter “key_” is used for filtering

monitoring information. For instance, to get only the monitoring information

about the item “Used disk space on /usr”, the “key_” should be set to

“[/usr,used]”.

#!/bin/bash

curl -i -X POST -H 'Content-Type: application/json' -d

'{"jsonrpc":"2.0","method":"","params":{"output":"extend","filter":{"key_":"[/usr,used]","hostid":"10017"}},"auth":"6705db5c5bdbd1d02a1f53857be6b200","id":2}'

127.0.0.1/zabbix/api_

After executing the “” script, the response to the JSON RPC query has

the following result:

{"jsonrpc":"2.0","result":[{"hosts":[{"hostid":"10017"}],"itemid":"18527","type":"0","snmp_community":"","snmp_oid":"","snmp_port":"161","hostid":"10017","description":"Used disk space on

$1","key_":"[usr,used]","delay":"30","history":"7","trends":"365","lastvalue":"9679056896","lastclock":"1309102427","prevvalue":"9679060992","status":"0","value_type":"3","trapper_hosts":"","units":"B","multiplier":"0","delta":"0","prevorgvalue":null,"snmpv3_securityname":"","snmpv3_securitylevel":"0","snmpv3_authpassphrase":"","snmpv3_privpassphrase":"","formula":"","error":"","lastlogsize":"0","logtimefmt":"","templateid":"10416","valuemapid":"0","delay_flex":"","params":"","ipmi_sensor":"","data_type":"0","authtype":"0","username":"","password":"","publickey":"","privatekey":"","mtime":"0"}],"id":2}

If one needs to know a list of all available items and their corresponding keys

before looking for a specific item, one can find this in two ways: 1. On the Zabbix GUI: go to Configuration/Hosts/ then click on the items of

the target host, you will find the description of items (e.g. “Used disk space

on /usr”) with their corresponding keys (e.g. “[/usr,used]”).

2. If you don’t have the ability to see the GUI, which means that you only use

remote calls (JSON-RPC) through Zabbix API using curl, you can execute,

for example, the following shell script:

#!/bin/bash

curl -i -X POST -H 'Content-Type: application/json' -d

'{"jsonrpc":"2.0","method":"","params":{"output":"extend","filter":{"hostid":"10017"}},"auth":"6705db5c5bdbd1d02a1f53857be6b200","id":2}' 127.0.0.1/zabbix/api_

When you execute this shell script, you will get all items (their descriptions and

keys) as a response to the JSON-RPC request.

Since the returned result as a response to the JSON RPC query is too long, the

following is the last part of that result:

{"jsonrpc":"2.0","result":[{".......................":"................."},{"hosts":[{"hostid":"10017"}],"itemid":"18535","type":"0","snmp_community":"","snmp_oid":"","snmp_port":"161","hostid":"10017","description":"Shared

memory","key_":"[shared]","delay":"30","history":"7","trends":"365","lastvalue":"0","lastclock":"1310472865","prevvalue":"0","status":"0","value_type":"3","trapper_hosts":"","units":"B","multiplier":"0","delta":"0","prevorgvalue":null,"snmpv3_securityname":"","snmpv3_securitylevel":"0","snmpv3_authpassphrase":"","snmpv3_privpassphrase":"","formula":"0","error":"","lastlogsize":"0","logtimefmt":"","templateid":"10027","valuemapid":"0","delay_flex":"","params":"","ipmi_sensor":"","data_type":"0","authtype":"0","username":"","password":"","publickey":"","privatekey":"","mtime":"0"},{"hosts":[{"hostid":"10017"}],"itemid":"18536","type":"0","snmp_community":"","snmp_oid":"","snmp_port":"161","hostid":"10017","description":"Total

memory","key_":"[total]","delay":"1800","history":"7","trends":"365","lastvalue":"1038831616","lastclock":"1310472536","prevvalue":"1038831616","status":"0","value_type":"3","trapper_hosts":"","units":"B","multiplier":"0","delta":"0","prevorgvalue":null,"snmpv3_securityname":"","snmpv3_securitylevel":"0","snmpv3_authpassphrase":"","snmpv3_privpassphrase":"","formula":"0","error":"","lastlogsize":"0","logtimefmt":"","templateid":"10026","valuemapid":"0","delay_flex":"","params":"","ipmi_sensor":"","data_type":"0","authtype":"0","username":"","password":"","publickey":"","privatekey":"","mtime":"0"}],"id":2}

To monitor the history of the any item, the “” method is used in the JSPN

RPC queries. If we want to monitor the history of, for instance, the item “Used disk

space on /usr”, the JSON RPC query should include user authentication result, host

ID and item IDs gained from previous JSON RPC queries. The “” script

can be executed to get history information about the “Used disk space on /usr”

within the period of time [26.06.2011/01:00 pm, 26.06.2011/01:10 pm] (Note:

this period of time is converted to UNIX timestamps through UNIX timestamp

converter). Moreover, the parameter “history” of the “” JSON RPC query

should set to the item value type. This value is included in the response to the

“” JSON RPC query under the name “value_type”.

In Zabbix, the following value_types are defined:

1. define(‘ITEM_VALUE_TYPE_FLOAT’, 0);

2. define(‘ITEM_VALUE_TYPE_STR’, 1);

3. define(‘ITEM_VALUE_TYPE_LOG’, 2);

4. define(‘ITEM_VALUE_TYPE_UINT64’, 3); 5. define(‘ITEM_VALUE_TYPE_TEXT’, 4);

#!/bin/bash

curl -i -X POST -H 'Content-Type: application/json' -d

'{"jsonrpc":"2.0","method":"","params":{"itemids":[18527],"history":3,"output":"extend","time_from":"1309086000","time_till":"1309086600"},"auth":"6705db5c5bdbd1d02a1f53857be6b200","id":2}'

127.0.0.1/zabbix/api_

The response to “” query after executing “” has the

following result:

{"jsonrpc":"2.0","result":[{"itemid":"18527","clock":"1309086017","value":"9675649024"},{"itemid":"18527","clock":"1309086047","value":"9675649024"},{"itemid":"18527","clock":"1309086077","value":"9675665408"},{"itemid":"18527","clock":"1309086107","value":"9675665408"},{"itemid":"18527","clock":"1309086137","value":"9675685888"},{"itemid":"18527","clock":"1309086167","value":"9675698176"},{"itemid":"18527","clock":"1309086197","value":"9675706368"},{"itemid":"18527","clock":"1309086227","value":"9675726848"},{"itemid":"18527","clock":"1309086257","value":"9675751424"},{"itemid":"18527","clock":"1309086287","value":"9675739136"},{"itemid":"18527","clock":"1309086317","value":"9675739136"},{"itemid":"18527","clock":"1309086347","value":"9675751424"},{"itemid":"18527","clock":"1309086377","value":"9675763712"},{"itemid":"18527","clock":"1309086407","value":"9675759616"},{"itemid":"18527","clock":"1309086437","value":"9675767808"},{"itemid":"18527","clock":"1309086467","value":"9675776000"},{"itemid":"18527","clock":"1309086497","value":"9675796480"},{"itemid":"18527","clock":"1309086527","value":"9675833344"},{"itemid":"18527","clock":"1309086557","value":"9675833344"},{"itemid":"18527","clock":"1309086587","value":"9675837440"}],"id":2}

Important things to be noticed regarding “”: 1. “” functionality is not implemented only since version: 1.8.3. If

you use, lower version of Zabbix, like 1.8.2, the response to the

“” JSON RPC query will be:

{"jsonrpc":"2.0","error":{"code":-32602,"message":"Invalid

params.","data":"Resource (history) does not exist"},"id":2}

2. Fetching history info about multiple metrics is not possible using one JSON

RPC query. In Zabbix documentation, it’s clear written that “Getting values

for multiple items of different types (history parameter) is not supported at

this time”.

3. Link to these

infos: /documentation/1.8/api/history/get

发布者:admin,转转请注明出处:http://www.yc00.com/xiaochengxu/1688931207a184776.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信