python獲取zabbix數據庫數據生成月度報表


#!/usr/bin/python3
# @Date: 2020/8/20 14:16
# @Author: zhangcheng
# @email: 3359957053@qq.com
# -*- coding: utf-8 -*-

import pymysql
import time,datetimeimport math

#zabbix數據庫信息:
zdbhost = "192.168.200.41"
zdbuser = "root"
zdbpass = "zabbix"
zdbport = 3306
zdbname = "zabbix"

#需要查詢的key列表
keys = {
    'trends_uint':[
        # 'vfs.fs.size[/,used]',
        'vm.memory.size[available]',

        'vm.memory.size[total]',

        ],
    'trends':[
        'system.cpu.load[percpu,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()

        #生成zabbix哪個分組報表
        self.groupname = "智能產品事業部"

        #獲取IP信息:
        self.IpInfoList = self.__getHostList()

    def __getHostList(self):
        '''根據zabbix組名獲取該組所有IP'''
        #查詢組ID:
        sql = '''select groupid from hstgrp where name = "{0}"'''.format(self.groupname)
        self.cursor.execute(sql)
        groupid = self.cursor.fetchone()[0]

        #根據groupid查詢該分組下面的所有主機ID(hostid):
        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())]
        # ['10550', '10551', '10552', '10553', '10555', '10556', '10557', '10558', '10559', '10560', '10561', '10562','10563', '10564']


        #生成IP信息字典:結構為{'112.111.222.55':{'hostid':'10086L'},}
        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)
            self.cursor.execute(sql)
            result = self.cursor.fetchone()[0]
            if result:
                resultlist[type] = result
            else:
                resultlist[type] = 0
        return resultlist


    def getLastMonthData(self,hostid,table,itemname):
        '''根據hostid,itemname獲取該監控項的值'''
        #獲取上個月的第一天和最后一天
        ts_first = int(time.mktime(datetime.date(datetime.date.today().year,datetime.date.today().month,1).timetuple()))
        # lst_last = datetime.date(datetime.date.today().year,datetime.date.today().month,1)-datetime.timedelta(1)
        lst_last = datetime.date(datetime.date.today().year,datetime.date.today().month+1,1)-datetime.timedelta(1)
        ts_last = int(time.mktime(lst_last.timetuple()))
        itemid = self.__getItemid(hostid, itemname)

        function = getattr(self,'get{0}Value'.format(table.capitalize()))

        return  function(itemid, ts_first, ts_last)

    def getInfo(self):
        #循環讀取IP列表信息
        for ip,resultdict in  zabbix.IpInfoList.items():
            print("正在查詢 IP:%-15s hostid:%5d 的信息" %(ip,int(resultdict['hostid'])))
            #循環讀取keys,逐個key統計數據:
            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):
        '''生成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[percpu,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()

效果圖如下,由於CPU核數是新增的,故在本月是沒有數據的:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM