Python调用Zabbix API实现自定义功能
一、zabbix API1、API描述Zabbix API允许以编程方式检索和修改Zabbix的配置,并提供对历史数据的访问。用于以下场景:1)创建新的应用程序以使用Zabbix;2)将Zabbix与第三方软件集成;3)自动执行常规任务。Zabbix API是基于Web的API,作为Web前端的一部分提供。它使用JSON-RPC 2.0协议,这意味着:1)该API包含一组独立的方法;2)客户端和A
一、zabbix API
1、API描述
Zabbix API允许以编程方式检索和修改Zabbix的配置,并提供对历史数据的访问。用于以下场景:
1)创建新的应用程序以使用Zabbix;
2)将Zabbix与第三方软件集成;
3)自动执行常规任务。
Zabbix API是基于Web的API,作为Web前端的一部分提供。它使用JSON-RPC 2.0协议,这意味着:
1)该API包含一组独立的方法;
2)客户端和API之间的请求和响应使用JSON格式进行编码。
2、API常用方法
Zabbix API由许多名义上分组的独立API方法组成。每个方法执行一个特定任务。
大多数Zabbix API至少包含四种方法:get,create,update和delete,分别是检索,创建,更新和删除数据
二、执行请求格式
可以使用远程HTTP请求来调用Zabbix API。
调用API需要向Zabbix前端目录中的api_jsonrpc.php文件发送HTTP POST请求。例如,通过HTTP请求来调用apiinfo.version,方法如下:
POST http://192.168.0.100:8008/zabbix/api_jsonrpc.php HTTP/1.1
Content-Type: application/json-rpc
{"jsonrpc":"2.0","method":"apiinfo.version","id":1,"auth":null,"params":{}}
其中,请求的Content-Type头部必须设置为以下值之一: application/json-rpc, application/json 或 application/jsonrequest。
三、API请求示例
在访问Zabbix中的任何数据之前,需要登录并获取身份验证令牌,获取token。(获取apiinfo.version不需要认证)
可以使用该user.login方法实现。
1、request body
{
"jsonrpc": "2.0",
"method": "user.login",
"params": {
"user": "Admin",
"password": "zabbix"
},
"id": 1,
"auth": null
}
2、request参数说明
jsonrpc - API使用的JSON-RPC协议的版本; Zabbix API实现的JSON-RPC版本是2.0;
method - 被调用的API方法名;
params - 将被传递给API方法的参数;
id - 请求的任意标识符;
auth -用户认证令牌; 因为还没有,设置为null。
3、response
账号密码正确,API返回的响应将包含用户身份验证令牌:
{
"jsonrpc": "2.0",
"result": "4fb18ae1d291122de6bc231300e1c814",
"id": 1
}
4、curl调用参考
所有的api接口,都可以先通过curl调用来调试。
[root@node1 ~]# curl -i -X POST -H 'Content-Type: application/json' -d '{"jsonrpc":"2.0","method":"user.login","params":{"user":"Admin","password":"password123"},"auth":null,"id":0}' http://192.168.0.100:8008/zabbix/api_jsonrpc.php
HTTP/1.1 200 OK
Date: Mon, 21 Sep 2020 03:11:43 GMT
Server: Apache/2.4.6 (CentOS) PHP/7.0.22
X-Powered-By: PHP/7.0.22
Content-Length: 68
Content-Type: application/json
{"jsonrpc":"2.0","result":"4fb18ae1d291122de6bc231300e1c814","id":0}
四、Python调用Zabbix API的方法
1、官方推荐的社区维护程序库
https://zabbix.org/wiki/Docs/api/libraries
相当于把zabbix API用python实现了一层封装,直接调用封装好的函数即可。
例如:zabbix-client库
>>> from zabbix_client import ZabbixServerProxy
>>> s = ZabbixServerProxy('http://localhost/zabbix')
>>> s.user.login(user='Admin', password='zabbix')
'44cfb35933e3e75ef51988845ab15e8b'
>>> s.host.get(output=['hostid', 'host'])
[{'host': 'Zabbix server', 'hostid': '10084'},
{'host': 'Test', 'hostid': '10085'}]
>>> s.user.logout()
True
2、自定义封装Zabbix API
1)获取token
def get_token():
data = {
"jsonrpc": "2.0",
"method": "user.login",
"params": {
"user": username,
"password": password
},
"id": 0
}
r = requests.get(zaurl, headers=header, data=json.dumps(data))
auth = json.loads(r.text)
return auth["result"]
2)获取指定的主机id
def host_get(token, instance_uuid):
data = {
"jsonrpc": "2.0",
"method": "host.get",
"params": {
"filter":{
"host": instance_uuid
}
},
"id": 1,
"auth": token
}
request = requests.post(zaurl, data=json.dumps(data), headers=header)
dict = json.loads(request.content)
return dict['result'][0]['hostid']
3)获取指定hostid的所有监控项的itemid以及监控key值
def getall_itemIDandKey_by_hostid(token, hostid):
data = {
"jsonrpc": "2.0",
"method": "item.get",
"params": {
"output": ["itemids","key_"],
"hostids": hostid,
},
"auth": token,
"id": 1
}
request = requests.post(zaurl, data=json.dumps(data), headers=header)
dict = json.loads(request.content)
itemid_and_key_list = dict['result']
return itemid_and_key_list
此处,output可以按需灵活自定义:可以是"extend",表示返回所有对象属性;也可以为"count",表示返回检索的记录数;也可以是一个属性名称数组,仅返回特定属性。
五、简单应用脚本
#coding:utf-8
import requests
import json
import time
# 0. [ ************ Variable to be modified ************]
zaurl = "http://192.168.0.100:8008/zabbix/api_jsonrpc.php"
username = "admin"
password = "password123"
starttime = "2020-09-17 00:00:00"
stoptime = "2020-09-18 00:00:00"
# 1. get token by zabbix API
def get_token():
data = {
"jsonrpc": "2.0",
"method": "user.login",
"params": {
"user": username,
"password": password
},
"id": 0
}
r = requests.get(zaurl, headers=header, data=json.dumps(data))
auth = json.loads(r.text)
return auth["result"]
# 2. get hostid from instance_uuid by zabbix API
def host_get(token, instance_uuid):
data = {
"jsonrpc": "2.0",
"method": "host.get",
"params": {
"filter":{
"host": instance_uuid
}
},
"id": 1,
"auth": token
}
request = requests.post(zaurl, data=json.dumps(data), headers=header)
dict = json.loads(request.content)
return dict['result'][0]['hostid']
# 3. get itemid from itemkey and hostid by zabbix API
def item_get(token, hostid, itemkey):
data = {
"jsonrpc": "2.0",
"method": "item.get",
"params": {
"output": "extend",
"hostids": hostid,
"search": {
"key_": itemkey
},
},
"auth": token,
"id": 1
}
request = requests.post(zaurl, data=json.dumps(data), headers=header)
dict = json.loads(request.content)
return dict['result'][0]['itemid']
# 4. get history data(numeric float) from itemid by zabbix API
def getdata(token, itemid, start, stop):
data = {
"jsonrpc": "2.0",
"method": "history.get",
"params": {
"output": "extend",
"history": 0,
"itemids": itemid,
"sortfield": "clock",
"sortorder": "ASC",
"time_from":start,
"time_till":stop
},
"id": 1,
"auth": token,
}
request = requests.post(zaurl, headers=header, data=json.dumps(data))
dict = json.loads(request.content)
return dict['result']
def timecovert(stringtime):
timeArray = time.strptime(stringtime, "%Y-%m-%d %H:%M:%S")
timeStamp = int(time.mktime(timeArray))
return timeStamp
if __name__ == "__main__":
header = {"Content-Type": "application/json"}
token = get_token()
start = timecovert(starttime)
stop = timecovert(stoptime)
vm_uuid_list = ["123","456"]
monitor_datafile = "/home/testMonitorGetDaily/" + "monitor_datafile" + ".csv"
fdata = open(monitor_datafile,'w')
fdata.write("虚机信息" + ',' + "cpu最小(%)" + ',' + "cpu平均(%)" + ',' + "cpu最大(%)" + '\n')
for vm_uuid in vm_uuid_list:
host_name = dic_vm[vm_uuid]
# ===========================================================================
# 5.Check whether the host is being monitored
# ===========================================================================
try:
hostid = host_get(token, vm_uuid)
except:
print ("instance is not monitored by zabbix, uuid is: ", vm_uuid)
continue
# ===========================================================================
# 6.Gets all monitoring data for the specified host
# ===========================================================================
cpu_itemkey = "general_cpu_util_"
try:
cpu_itemid = item_get(token, hostid, cpu_itemkey)
cpu_data = getdata(token,cpu_itemid,start,stop)
except:
print ("get cpu monitor data failed! instance uuid is: ", vm_uuid)
continue
# ===========================================================================
# 7.Calculate the min/avg/max value from the monitoring data
# ===========================================================================
if cpu_data:
cpu_valuelist = []
for i in cpu_data:
cpu_valuelist.append(float(i["value"]))
cpu_avge = sum(cpu_valuelist)/len(cpu_valuelist)
cpu_min = min(cpu_valuelist)
cpu_max = max(cpu_valuelist)
#print ("cpu:",vm_uuid, cpu_min, cpu_avge, cpu_max)
else:
print ("host No cpu_util data, uuid is: ",vm_uuid)
continue
# ===========================================================================
# 8.Outputs the monitor data results to the specified file
# ===========================================================================
fdata.write(vm_uuid + ',' + str(round(cpu_min,2)) + ',' + str(round(cpu_avge,2)) + ',' + str(round(cpu_max,2)) + '\n')
fdata.close()
参考:https://www.zabbix.com/documentation/4.0/manual/api
更多推荐
所有评论(0)