使用python或工具调用Zabbix RESTful API

1 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方法向http://example.com/zabbix/api_jsonrpc.php发送此JSON对象. http://example.com/zabbix/是Zabbix前端地址。api_jsonrpc.php是调用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请求如下:


{
"jsonrpc": "2.0",
"method": "method.name", 
"params": {
"param_1_name": "param_1_value",
"param_2_name": "param_2_value" 
},
"id": 1,
"auth": "159121b60d19a9b4b55d49e30cf12b81",
}
下面一行一行来看:


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


"method": "method.name"-这个参数定义了真实执行的操作。例如:host.create、item.update等等


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


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


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


2 使用python urllib2 和 url调用 API

2.1 安装Zabbix

       参考:ubuntu下安装zabbix: http://blog.csdn.net/zhaihaifei/article/details/52944950

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


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

#!/usr/bin/env python2.7
#coding=utf-8
import json
import urllib2
# based url and required header
url = "http://monitor.example.com/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 And Password:",e.code
else:
response = json.loads(result.read())
result.close()
print "Auth Successful. The Auth ID Is:",response['result']


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


picture1


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


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


test@test:~$ curl -i -X POST -H 'Content-Type:application/json' 
-d'{"jsonrpc": "2.0","method":"user.authenticate","params":{"user":"Admin","password":"zabbix"},"auth": null,"id":0}' 
http://10.0.2.6/zabbix/api_jsonrpc.php


HTTP/1.1 200 OK
Date: Fri, 28 Oct 2016 06:53:54 GMT
Server: Apache/2.4.7 (Ubuntu)
X-Powered-By: PHP/5.5.9-1ubuntu4.20
Content-Length: 68
Content-Type: application/json


{"jsonrpc":"2.0","result":"30fee9c66836c336dd05ef571a95ec26","id":0}






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


#!/usr/bin/env python2.7
#coding=utf-8
import json
import urllib2
# based url and required header
url = "http://10.0.2.6/zabbix/api_jsonrpc.php"
header = {"Content-Type": "application/json"}
# request json
data = json.dumps(
	{
	"jsonrpc":"2.0",
	"method":"host.get",
	"params":{
		"output":["hostid","name"],
		"filter":{"host":""}
	},
	"auth":"533b10085734a507713d9ac36fc1f0eb", # the auth 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'],"Host Name:",host['name']



对比基于CURL的访问方式: 

curl -i -X POST -H 'Content-Type: application/json' -d '{"jsonrpc":"2.0","method":"host.get","params":{"output":["hostid","name"],"filter":{"host":""}},"auth":"533b10085734a507713d9ac36fc1f0eb","id":1}' http://10.0.2.6/zabbix/api_jsonrpc.php
test@test:~$ curl -i -X POST -H 'Content-Type: application/json' -d '{"jsonrpc":"2.0","method":"host.get","params":{"output":["hostid","name"],"filter":{"host":""}},"auth":"533b10085734a507713d9ac36fc1f0eb","id":1}' http://10.0.2.6/zabbix/api_jsonrpc.php
HTTP/1.1 200 OK
Date: Thu, 27 Oct 2016 10:03:21 GMT
Server: Apache/2.4.7 (Ubuntu)
X-Powered-By: PHP/5.5.9-1ubuntu4.20
Content-Length: 114
Content-Type: application/json


{"jsonrpc":"2.0","result":[{"hostid":"10084","name":"Zabbix server"},{"hostid":"10105","name":"10.0.2.7"}],"id":1}





比较来看,

采用脚本可以有更多的灵活性,

基于CURL的方式,对结果的处理不是很方便。

原理则都是相通的。


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


3 使用requests包来调用API

test@test:~$ python
Python 2.7.6 (default, Mar 22 2014, 22:59:56) 
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import requests
>>> url = "http://10.0.2.6/zabbix/api_jsonrpc.php"
>>> header = {"Content-Type": "application/json"}
>>> r.status_code
200
>>> r.text
u'{"jsonrpc":"2.0","error":{"code":-32700,"message":"Parse error","data":"Invalid JSON. An error occurred on the server while parsing the JSON text."},"id":null}'

>>> r = requests.get(url, headers=header, auth=('admin', 'zabbix'))
>>> r.status_code
200
>>> r.text
u'{"jsonrpc":"2.0","error":{"code":-32700,"message":"Parse error","data":"Invalid JSON. An error occurred on the server while parsing the JSON text."},"id":null}'
>>> import json
>>> payload = {"jsonrpc": "2.0","method":"user.login","params":{"user":"Admin","password":"zabbix"},"auth": "null","id": "0"}
>>> r = requests.post(url, headers=header, params=json.dumps(payload))
>>> r.text
u'{"jsonrpc":"2.0","error":{"code":-32700,"message":"Parse error","data":"Invalid JSON. An error occurred on the server while parsing the JSON text."},"id":null}'
>>> 
>>> 
>>> r = requests.get(url, headers=header, data=json.dumps(payload))
>>> 
>>> 
>>> r.text
u'{"jsonrpc":"2.0","error":{"code":-32602,"message":"Invalid params.","data":"Not authorized"},"id":"0"}'

>>> payload = {"jsonrpc": "2.0","method":"user.login","params":{"user":"Admin","password":"zabbix"},"id": 100}
>>> 
>>> r = requests.get(url, headers=header, data=json.dumps(payload))
>>> r.text
u'{"jsonrpc":"2.0","result":"d741dc8b1f9abfc04c5efd8a9d0f7375","id":100}'
>>> 
关于requests的使用, 参考:
1  python的requests初步使用 https://my.oschina.net/yangyanxing/blog/280029

2 http://cn.python-requests.org/zh_CN/latest/user/quickstart.html

ubuntu下安装zabbix: http://blog.csdn.net/zhaihaifei/article/details/52944950

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
使用Python调用Zabbix API批量查询主机的信息,您需要进行以下步骤: 1. 安装 `zabbix-api` 模块:您可以使用 `pip` 命令安装该模块,例如:`pip install zabbix-api` 2. 导入必要的库和模块: ```python from pyzabbix import ZabbixAPI import json ``` 3. 创建 `ZabbixAPI` 对象并登录: ```python zabbix_server = "http://zabbix.example.com" zabbix_user = "username" zabbix_password = "password" zapi = ZabbixAPI(url=zabbix_server, user=zabbix_user, password=zabbix_password) zapi.login() ``` 4. 使用 `host.get` 方法批量查询主机信息: ```python hosts = zapi.host.get(output=['hostid', 'host', 'name', 'status', 'ip']) ``` 此时,变量 `hosts` 将包含所有主机的信息。在这个示例中,我们查询了每个主机的 `hostid`、`host`、`name`、`status` 和 `ip` 信息。 5. 处理查询结果: ```python for host in hosts: print("Host ID:", host['hostid']) print("Host Name:", host['name']) print("Host Status:", host['status']) print("Host IP:", host['ip']) print("------------------------") ``` 以上代码将遍历每个主机,并打印出其 ID、名称、状态和 IP 地址。 完整代码示例: ```python from pyzabbix import ZabbixAPI import json zabbix_server = "http://zabbix.example.com" zabbix_user = "username" zabbix_password = "password" zapi = ZabbixAPI(url=zabbix_server, user=zabbix_user, password=zabbix_password) zapi.login() hosts = zapi.host.get(output=['hostid', 'host', 'name', 'status', 'ip']) for host in hosts: print("Host ID:", host['hostid']) print("Host Name:", host['name']) print("Host Status:", host['status']) print("Host IP:", host['ip']) print("------------------------") ``` 注意:在实际使用中,您可能需要根据具体情况修改查询的参数和返回结果的处理方式。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值