import pymysql
import time,datetime
import math
zdbhost = "127.0.0.1"
zdbuser = "pig"
zdbpass = "1"
zdbport = 3306
zdbname = "zabbix"
keys = {
'trends_uint':[
'vm.memory.size[available]',
'vm.memory.size[total]',
],
'trends':[
'system.cpu.load[all,avg15]',
'system.cpu.util[,idle]',
'system.cpu.num',
]
}
class ReportForm:
def __init__(self):
'''打开数据库连接'''
self.conn = pymysql.connect(host=zdbhost,user=zdbuser,passwd=zdbpass,port=zdbport,db=zdbname,charset="utf8")
self.cursor = self.conn.cursor()
self.groupname = "本地生产"
self.IpInfoList = self.__getHostList()
def __getHostList(self):
'''根据zabbix组名获取该组所有IP'''
sql = '''select groupid from hstgrp where name = "{0}"'''.format(self.groupname)
self.cursor.execute(sql)
groupid = self.cursor.fetchone()[0]
sql = '''select hostid from hosts_groups where groupid = {0}'''.format(groupid)
self.cursor.execute(sql)
hostlist = [i for i in list("%s" %j for j in self.cursor.fetchall())]
IpInfoList = {}
for hostid in hostlist:
sql = '''select host from hosts where status = 0 and hostid = {0}'''.format(hostid)
ret = self.cursor.execute(sql)
if ret:
IpInfoList["".join("%s" %i for i in list(self.cursor.fetchone()))] = {'hostid':hostid}
return IpInfoList
def __getItemid(self,hostid,itemname):
'''获取itemid'''
sql = '''select itemid from items where hostid = {0} and key_ = '{1}' '''.format(hostid, itemname)
print(sql)
if self.cursor.execute(sql):
itemid = "".join("%s" %i for i in list(self.cursor.fetchone()))
else:
print(hostid,itemname)
itemid = None
return itemid
def getTrendsValue(self,itemid, start_time, stop_time):
'''查询trends_uint表的值,type的值为min,max,avg三种'''
resultlist = {}
for type in ['min','max','avg']:
sql = '''select {0}(value_{1}) as result from trends where itemid = {2} and clock >= {3} and clock <= {4}'''.format(type, type, itemid, start_time, stop_time)
self.cursor.execute(sql)
result = self.cursor.fetchone()[0]
if result == None:
result = 0
resultlist[type] = result
return resultlist
def getTrends_uintValue(self,itemid, start_time, stop_time):
'''查询trends_uint表的值,type的值为min,max,avg三种'''
resultlist = {}
for type in ['min','max','avg']:
sql = '''select {0}(value_{1}) as result from trends_uint where itemid = {2} and clock >= {3} and clock <= {4}'''.format(type, type, itemid, start_time, stop_time)
print(sql)
self.cursor.execute(sql)
result = self.cursor.fetchone()[0]
print(result)
if result:
resultlist[type] = result
else:
resultlist[type] = 0
return resultlist
def getLastMonthData(self,hostid,table,itemname):
'''根据hostid,itemname获取该监控项的值'''
ts_first = int(1635422400)
ts_last = int(1635516000)
function = getattr(self,'get{0}Value'.format(table.capitalize()))
itemid = self.__getItemid(hostid, itemname)
return function(itemid, ts_first, ts_last)
def getInfo(self):
for ip,resultdict in zabbix.IpInfoList.items():
print("正在查询 IP:%-15s hostid:%5d 的信息" %(ip,int(resultdict['hostid'])))
for table, keylists in keys.items():
for key in keylists:
print("\t正在统计 key_:'{0}'".format(key))
data = zabbix.getLastMonthData(resultdict['hostid'],table,key)
zabbix.IpInfoList[ip][key] = data
def writeToXls(self):
print(self.IpInfoList)
'''生成xls文件'''
try:
import xlsxwriter
date = time.strftime("%Y-%m",time.localtime())
workbook = xlsxwriter.Workbook(self.groupname + "-" + date + '.xls')
worksheet = workbook.add_worksheet()
i = 0
for value in ["归属部门","主机","CPU核数","CPU平均空闲值","CPU最小空闲值","CPU15分钟负载","总内存","平均可用内存","最小可用内存"]:
worksheet.write(0,i, value)
i = i + 1
j = 1
for ip,value in self.IpInfoList.items():
worksheet.write(j,0, self.groupname)
worksheet.write(j,1, ip)
worksheet.write(j,2, '{}'.format(value['system.cpu.num']['avg']))
worksheet.write(j,3, '{:.2f}%'.format(value['system.cpu.util[,idle]']['avg']))
worksheet.write(j,4, '{:.2f}%'.format(value['system.cpu.util[,idle]']['min']))
worksheet.write(j,5, '{:.2f}'.format(value['system.cpu.load[all,avg15]']['avg']))
worksheet.write(j,6, '{}GB'.format(math.ceil(value['vm.memory.size[total]']['avg'] / 1024 / 1024 / 1024)))
worksheet.write(j,7, '{}GB'.format(math.ceil(value['vm.memory.size[available]']['avg'] / 1024 / 1024 / 1024)))
worksheet.write(j,8, '{}GB'.format(math.ceil(value['vm.memory.size[available]']['min'] / 1024 / 1024 / 1024)))
j = j + 1
workbook.close()
except Exception as e:
print(e)
def __del__(self):
'''关闭数据库连接'''
self.cursor.close()
self.conn.close()
if __name__ == "__main__":
zabbix = ReportForm()
zabbix.getInfo()
zabbix.writeToXls()
