#!/usr/local/bin/python
# coding:utf-8
import json
import urllib2
from urllib2 import URLError
import sys
import xlrd
import getpass
import time
import datetime
import xlsxwriter
reload(sys)
sys.setdefaultencoding('utf-8')
# History object types to return.
#
# Possible values:
# 0 - numeric float;
# 1 - character;
# 2 - log;
# 3 - numeric unsigned;
# 4 - text.
#
# Default: 3.
class ZabbixTools:
def __init__(self):
self.url = 'http://192.168.243.99//zabbix/api_jsonrpc.php'
self.header = {'User-agent': 'Mozilla/5.0 (Windows NT 6.2; WOW64; rv:22.0) Gecko/20100101 Firefox/22.0',
"Content-Type": "application/json"}
def user_login(self):
data = json.dumps({
"jsonrpc": "2.0",
"method": "user.login",
"params": {
"user": "Admin",
"password": "zabbix"
},
"id": 0
})
request = urllib2.Request(self.url, data)
for key in self.header:
request.add_header(key, self.header[key])
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()
self.authID = response['result']
return self.authID
def retimes(self, times):
timeArray = time.strptime(times, "%Y-%m-%d %H:%M:%S")
timestamp = time.mktime(timeArray)
return timestamp
def reshowtime(self, cptimes):
t1 = time.localtime(cptimes)
showtimes = time.strftime("%Y-%m-%d %H:%M:%S", t1)
return showtimes
def host_getbyip(self, hostip):
data = json.dumps({
"jsonrpc": "2.0",
"method": "host.get",
"params": {
"output": ["hostid", "name", "status", "available", "proxy_hostid"],
"filter": {"ip": hostip}
},
# "auth":self.user_login(),
"auth": self.authID,
"id": 1,
})
request = urllib2.Request(self.url, data)
for key in self.header:
request.add_header(key, self.header[key])
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 %s: " % hostName, len(response['result'])
lens = len(response['result'])
# print response["result"]
if lens > 0:
# return response['result'][0]['name']
# print response['result'][0]['status']
print
hostip, response['result'][0]['proxy_hostid'] + " " + response['result'][0]['available'] + " " + \
response['result'][0]['name'] + " " + response['result'][0]['hostid']
return response['result'][0]['hostid']
else:
print
"error " + hostip
def getitemids(self, hostips, itemnames):
hostid = self.host_getbyip(hostips)
data = json.dumps({
"jsonrpc": "2.0",
"method": "item.get",
"params": {
"output": "extend",
"hostids": hostid,
"filter": {
# "name": itemnames,
"key_": itemnames
}
# "proxy_hostid":proxyids,
},
"auth": self.authID,
"id": 1,
})
request = urllib2.Request(self.url, data)
for key in self.header:
request.add_header(key, self.header[key])
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 response['result']
print(response['result'][0]["itemid"]) + " test"
return response['result'][0]["itemid"]
def historyvalues(self, itemids, start, stop, types=3):
data = json.dumps({
"jsonrpc": "2.0",
"method": "history.get",
"params": {
"itemids": itemids,
"history": types,
"sortfield": "clock",
"sortorder": "DESC",
"time_from": int(start),
"time_till": int(stop),
"limit": 100000
},
"auth": self.authID,
"id": 1,
})
request = urllib2.Request(self.url, data)
for key in self.header:
request.add_header(key, self.header[key])
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 response
# print response['result']
# for items in response['result']:
# dt=int(items['clock'])
# dts=self.reshowtime(dt)
# print dts,items['value']
return response['result']
def printhistory(self, ips, items, start, stop, types=3):
starttime = self.retimes(start)
stoptime = self.retimes(stop)
print
starttime, stoptime
itemid = self.getitemids(ips, items)
results = self.historyvalues(itemid, starttime, stoptime, types)
nowtime = time.strftime('%Y-%m-%d-%H-%M-%S', time.localtime(time.time())) + ""
filenames = nowtime + 'iteminfos.xlsx'
workbook1 = xlsxwriter.Workbook(filenames)
worksheet = workbook1.add_worksheet()
t1 = 'ZABBIX监控数据'
format = workbook1.add_format()
format.set_bold()
yellow = workbook1.add_format(
{'align': 'center', 'valign': 'vcenter', 'font_size': 22, 'fg_color': 'FFC1C1'})
yellow.set_bold()
# worksheet.merge_range(0,0,0,4,t1,yellow)
worksheet.merge_range('A1:B1', t1, yellow)
worksheet.set_row(0, 38)
worksheet.set_column("A:A", 30)
worksheet.set_column("B:B", 60)
title = [u'主机IP', u'时间', u'键值' + items]
format = workbook1.add_format()
# worksheet.set_column(0,15,20)
format = workbook1.add_format({'align': 'center', 'valign': 'vcenter'})
format.set_bold()
worksheet.write_row('A2', title, format)
worksheet.set_row(1, 25)
row = 2
for items in results:
dt = int(items['clock'])
dts = self.reshowtime(dt)
# print dts,items['value']
worksheet.write(row, 0, ips)
worksheet.write(row, 1, dts)
worksheet.write(row, 2, items['value'])
row = row + 1
workbook1.close()
def printhistorylist(self, ips, items, start, stop, types=3):
starttime = self.retimes(start)
stoptime = self.retimes(stop)
print
starttime, stoptime
itemid = self.getitemids(ips, items)
results = self.historyvalues(itemid, starttime, stoptime, types)
return results
def printmanyitemexcel(self, ary1, items):
nowtime = time.strftime('%Y-%m-%d-%H-%M-%S', time.localtime(time.time())) + ""
filenames = nowtime + 'iteminfos.xlsx'
workbook1 = xlsxwriter.Workbook(filenames)
worksheet = workbook1.add_worksheet()
t1 = 'ZABBIX监控数据'
format = workbook1.add_format()
format.set_bold()
yellow = workbook1.add_format(
{'align': 'center', 'valign': 'vcenter', 'font_size': 22, 'fg_color': 'FFC1C1'})
yellow.set_bold()
# worksheet.merge_range(0,0,0,4,t1,yellow)
worksheet.merge_range('A1:B1', t1, yellow)
worksheet.set_row(0, 38)
worksheet.set_column("A:A", 30)
worksheet.set_column("B:B", 60)
title = [u'主机IP', u'时间', u'键值' + items]
format = workbook1.add_format()
# worksheet.set_column(0,15,20)
format = workbook1.add_format({'align': 'center', 'valign': 'vcenter'})
format.set_bold()
worksheet.write_row('A2', title, format)
worksheet.set_row(1, 25)
row = 2
ipaddress = ''
for items in ary1:
if items.has_key('ipaddress'):
ipaddress = items['ipaddress']
else:
dt = int(items['clock'])
dts = self.reshowtime(dt)
# print dts,items['value']
worksheet.write(row, 0, ipaddress)
worksheet.write(row, 1, dts)
worksheet.write(row, 2, items['value'])
row = row + 1
workbook1.close()
def manyhostsvalues(self, files, keys, types, starttimes, stoptimes):
ary1 = []
myfile = open(files, 'r')
for line in myfile:
con = line.split()
ips = con[0].strip()
arys = test.printhistorylist(ips, keys, starttimes, stoptimes, types)
m = dict()
m["ipaddress"] = ips
arys.insert(0, m)
ary1.extend(arys)
print
arys
# print ary1
self.printmanyitemexcel(ary1, keys)
if __name__ == '__main__':
test = ZabbixTools()
test.user_login()
test.manyhostsvalues("1.txt", "net.if.in[ens32]", 3, "2022-2-25 0:00:00", "2022-3-2 11:00:00")
#把IP列表写在同一目录的1.txt
调用的API:?history.gethttps://www.zabbix.com/documentation/4.4/en/manual/api/reference/history/get
|