侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

ZABBIX3.2使用python脚本实现监控报表的方法

Python  /  管理员 发布于 7年前   216

如下所示:

#!/usr/bin/python#coding:utf-8 import MySQLdbimport time,datetime  #zabbix数据库信息:zdbhost = '172.16.8.200'zdbuser = 'zabbix'zdbpass = 'zabbix'zdbport = 3306zdbname = 'zabbix' #生成文件名称:xlsfilename = 'zabbix.xls' #需要查询的key列表 [名称,表名,key值,取值,格式化,数据整除处理]keys = [  ['CPU核心数','trends_uint','system.cpu.num','avg','',1],  ['CPU平均空闲值','trends','system.cpu.util[,idle]','avg','%.2f',1],  ['CPU最小空闲值','trends','system.cpu.util[,idle]','min','%.2f',1],  ['CPU5分钟负载','trends','system.cpu.load[percpu,avg5]','avg','%.2f',1],  ['物理内存大小(单位G)','trends_uint','vm.memory.size[total]','avg','',1048576000],  ['可用平均内存(单位G)','trends_uint','vm.memory.size[available]','avg','',1048576000],  ['可用最小内存(单位G)','trends_uint','vm.memory.size[available]','min','',1048576000],  ['swap总大小(单位G)','trends_uint','system.swap.size[,total]','avg','',1048576000],  ['swap平均剩余(单位G)','trends_uint','system.swap.size[,free]','avg','',1048576000],  ['根分区总大小(单位G)','trends_uint','vfs.fs.size[/,total]','avg','',1073741824],  ['根分区平均剩余(单位G)','trends_uint','vfs.fs.size[/,free]','avg','',1073741824],  ['进入最大流量(单位Kbps)','trends_uint','net.if.in[eth0]','max','',1000],  ['进入平均流量(单位Kbps)','trends_uint','net.if.in[eth0]','avg','',1000],  ['出去最大流量(单位Kbps)','trends_uint','net.if.out[eth0]','max','',1000],  ['出去平均流量(单位Kbps)','trends_uint','net.if.out[eth0]','avg','',1000],]  class ReportForm:   def __init__(self):    '''打开数据库连接'''    self.conn = MySQLdb.connect(host=zdbhost,user=zdbuser,passwd=zdbpass,port=zdbport,db=zdbname)    self.cursor = self.conn.cursor(cursorclass=MySQLdb.cursors.DictCursor)     #生成zabbix哪个分组报表    self.groupname = 'zabbix server'     #获取IP信息:    self.IpInfoList = self.__getHostList()   def __getHostList(self):    '''根据zabbix组名获取该组所有IP'''     #查询组ID:    sql = '''select groupid from groups where name = '%s' ''' % self.groupname    self.cursor.execute(sql)    groupid = self.cursor.fetchone()['groupid']     #根据groupid查询该分组下面的所有主机ID(hostid):    sql = '''select hostid from hosts_groups where groupid = %s''' % groupid    self.cursor.execute(sql)    hostlist = self.cursor.fetchall()     #生成IP信息字典:结构为{'119.146.207.19':{'hostid':10086L,},}    IpInfoList = {}    for i in hostlist:      hostid = i['hostid']      sql = '''select host from hosts where status = 0 and hostid = %s''' % hostid      ret = self.cursor.execute(sql)      if ret:        IpInfoList[self.cursor.fetchone()['host']] = {'hostid':hostid}    return IpInfoList   def __getItemid(self,hostid,itemname):    '''获取itemid'''    sql = '''select itemid from items where hostid = %s and key_ = '%s' ''' % (hostid, itemname)    if self.cursor.execute(sql):      itemid = self.cursor.fetchone()['itemid']    else:      itemid = None    return itemid   def getTrendsValue(self,type, itemid, start_time, stop_time):    '''查询trends_uint表的值,type的值为min,max,avg三种'''    sql = '''select %s(value_%s) as result from trends where itemid = %s and clock >= %s and clock <= %s''' % (type, type, itemid, start_time, stop_time)    self.cursor.execute(sql)    result = self.cursor.fetchone()['result']    if result == None:      result = 0    return result   def getTrends_uintValue(self,type, itemid, start_time, stop_time):    '''查询trends_uint表的值,type的值为min,max,avg三种'''    sql = '''select %s(value_%s) as result from trends_uint where itemid = %s and clock >= %s and clock <= %s''' % (type, type, itemid, start_time, stop_time)    self.cursor.execute(sql)    result = self.cursor.fetchone()['result']    if result:      result = int(result)    else:      result = 0    return result    def getLastMonthData(self,type,hostid,table,itemname):    '''根据hostid,itemname获取该监控项的值'''    #获取上个月的第一天和最后一天    ts_first = int(time.mktime(datetime.date(datetime.date.today().year,datetime.date.today().month-1,1).timetuple()))    lst_last = datetime.date(datetime.date.today().year,datetime.date.today().month,1)-datetime.timedelta(1)    ts_last = int(time.mktime(lst_last.timetuple()))     itemid = self.__getItemid(hostid, itemname)     function = getattr(self,'get%sValue' % table.capitalize())     return function(type,itemid, ts_first, ts_last)   def getInfo(self):    #循环读取IP列表信息    for ip,resultdict in zabbix.IpInfoList.items():      print "正在查询 IP:%-15s hostid:%5d 的信息!" % (ip, resultdict['hostid'])      #循环读取keys,逐个key统计数据:      for value in keys:        print "\t正在统计 key_:%s" % value[2]        if not value[2] in zabbix.IpInfoList[ip]:          zabbix.IpInfoList[ip][value[2]] = {}        data = zabbix.getLastMonthData(value[3], resultdict['hostid'],value[1],value[2])        zabbix.IpInfoList[ip][value[2]][value[3]] = data    def writeToXls2(self):    '''生成xls文件'''    try:      import xlsxwriter       #创建文件      workbook = xlsxwriter.Workbook(xlsfilename)       #创建工作薄      worksheet = workbook.add_worksheet()       #写入第一列:      worksheet.write(0,0,"主机".decode('utf-8'))      i = 1      for ip in self.IpInfoList:        worksheet.write(i,0,ip)        i = i + 1       #写入其他列:      i = 1      for value in keys:        worksheet.write(0,i,value[0].decode('utf-8'))         #写入该列内容:        j = 1        for ip,result in self.IpInfoList.items():          if value[4]:worksheet.write(j,i, value[4] % result[value[2]][value[3]])          else:worksheet.write(j,i, result[value[2]][value[3]] / value[5])          j = j + 1         i = i + 1    except Exception,e:      print e     def __del__(self):    '''关闭数据库连接'''    self.cursor.close()    self.conn.close() if __name__ == "__main__":  zabbix = ReportForm()  zabbix.getInfo()  zabbix.writeToXls2()

以上这篇ZABBIX3.2使用python脚本实现监控报表的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。


  • 上一条:
    python set内置函数的具体使用
    下一条:
    浅谈python 中类属性共享的问题
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 在python语言中Flask框架的学习及简单功能示例(0个评论)
    • 在Python语言中实现GUI全屏倒计时代码示例(0个评论)
    • Python + zipfile库实现zip文件解压自动化脚本示例(0个评论)
    • python爬虫BeautifulSoup快速抓取网站图片(1个评论)
    • vscode 配置 python3开发环境的方法(0个评论)
    • 近期文章
    • 智能合约Solidity学习CryptoZombie第四课:僵尸作战系统(0个评论)
    • 智能合约Solidity学习CryptoZombie第三课:组建僵尸军队(高级Solidity理论)(0个评论)
    • 智能合约Solidity学习CryptoZombie第二课:让你的僵尸猎食(0个评论)
    • 智能合约Solidity学习CryptoZombie第一课:生成一只你的僵尸(0个评论)
    • 在go中实现一个常用的先进先出的缓存淘汰算法示例代码(0个评论)
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 欧盟关于强迫劳动的规定的官方举报渠道及官方举报网站(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2016-11
    • 2018-04
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2022-01
    • 2023-07
    • 2023-10
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客