前言:
查询监控项历史数据,最常见的办法就是在页面查询,但是页面只能展现最近的500个数值,如果要查询历史数据比较久远或要形成数据表格进行分析,这个办法就不适用了,但是利用zabbix—API查询zabbix监控项历史数据就可以满足这一需求,只需要指定查询的起止时间及监控项,就能以数据的形式进行输出,便于业务侧分析此期间的性能指标是否正常
具体脚本讲解如下:
#coding:utf-8
#给定主机IP获取一段时间内cpu的均值和峰值并写入文件(txt,可以跑完后直接把后缀名改为csv以表格形式打开);需要指定IP文件
import requests
import json
import csv
import time
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"]
def item_get(token, host, itemkey):
data = {
"jsonrpc": "2.0",
"method": "item.get",
"params": {
"host": host,
"search": {
"key_": itemkey
},
},
"auth": token,
"id": 1
}
request = requests.post(zaurl, data=json.dumps(data), headers=header)
dict = json.loads(request.content)
# print(dict)
return dict['result'][0]['itemid']
def getdata(token,itemid, start, stop):
data = {
"jsonrpc": "2.0",
"method": "history.get",
"params": {
"output": "extend",
"itemids": itemid,
"history": 0,
"time_from":start,
"time_till":stop
},
"id": 2,
"auth": token,
}
request = requests.post(zaurl, headers=header, data=json.dumps(data))
dict = json.loads(request.content)
print(dict)
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__":
zaurl = "http://IP/api_jsonrpc.php" # 访问zabbix页面的url
header = {"Content-Type": "application/json"}
username = "xxx" #zabbix的账户与密码
password = "xxx"
hostfile="ip.txt"
token = get_token()
starttime = "2020-05-24 11:30:00" #查询历史数据的起止时间
stoptime = "2020-05-24 12:30:00"
start = timecovert(starttime)
stop = timecovert(stoptime)
#生成一个txt文件
datafile = "/home/dwchenrongbin/linfan/data.txt"
fdata = open(datafile,'w')
with open(hostfile, "r") as f:
f1 = f.readlines()
for ips in f1:
host = ips.replace('\n', '').strip()
# 修改参数
#以下例子为cpu
itemkey = ["cpu_use_ag"] #要查询监控项的KEY值
itemid = item_get(token, host, itemkey)
data = getdata(token,itemid,start,stop)
if data:
valuelist = []
for i in data:
valuelist.append(float(i["value"]))
avge = sum(valuelist)/len(valuelist) #查询周期内的平均值
max1 = max(valuelist) #查询周期内的最大值
fdata.write(host + ',' + str(round(avge,2)) + ',' + str(round(max1,2)) + '\n')
print (host, avge, max1,valuelist) #打印出 主机名、平均值、最大值、历史数据
else:
print (host)
fdata.close()
以下是我根据脚本输出整理的Excel表历史数据(IP已被我过滤掉)