ZABBIX3.2使用python脚本实现监控报表的方法
作者:思考v 发布时间:2021-04-11 20:15:02
标签:ZABBIX3.2,python,监控报表
如下所示:
#!/usr/bin/python
#coding:utf-8
import MySQLdb
import time,datetime
#zabbix数据库信息:
zdbhost = '172.16.8.200'
zdbuser = 'zabbix'
zdbpass = 'zabbix'
zdbport = 3306
zdbname = '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()
来源:https://blog.csdn.net/xiegh2014/article/details/76422676
0
投稿
猜你喜欢
- 扪心自问,你真正了解你卖给用户的是什么玩意么?你所认为革命性的,一定会震惊世界的功能、特色,用户真的买单么?我的意思是,我们总是习惯性的忘记
- 为什么能实现在线编辑呢? 首先需要ie 的支持,在 ie 5.5以后就有一个编辑状态,就是利用这个编辑状态,然后用javascript 来控
- 五子棋游戏相信大部分人都玩过,今天我们用python来实现一次具体代码可以访问我的GitHub地址获取构建五子棋棋盘from collect
- 一.Jupyter介绍Jupyter Notebook是一个交互式笔记本,支持运行40多种编程语言。Jupyter Notebook 的本质
- 在Python的标准库中,functools库中有很多对方法有操作的封装功能,partial Objects就是其中之一,他可以实现对方法参
- 空白双边距是一个极容易误解的CSS特性.它不是CSS的bug,但如果我们一旦误解,将会给你带来很多麻烦.先看如下demo代码:<!do
- server application error--IIS故障故障现象:Server Application Error The serve
- 首先要作出决策,你是否想要使用最新的开发版本或最终的稳定版本。在MySQL开发过程中,同时存在多个发布系列,每个发布处在成熟度的不同阶段:&
- 一旦你已经为MySQL实例管理器设置了一个密码文件并且IM正在运行,你可以连接它。你可以使用mysql客户端工具通过标准MySQL API来
- 由于计算机软件的非法复制,通信的泄密、数据安全受到威胁。一般为了安全,会要求将数据库名称、密码等信息进行加密。所以加密在开发过程中是经常使用
- 导语:哈喽,哈喽~大家有没有遇到过这种情况,手机用着用着没有内存了,一到设置里面一看。微信和 QQ 10G!啊这。。。。。就离谱!好说,好说
- 进程、线程和协程之间的关系和区别也困扰我一阵子了,最近有一些心得,写一下。进程拥有自己独立的堆和栈,既不共享堆,亦不共享栈,进程由操作系统调
- 给静态网页加密的方法有很多,有的简单有的复杂。前两天看见有人问静态网页加密问题,就写了这个代码思路:加密时:先把用户的密钥A用md5加密为B
- 我们都知道Django rest framework这个库,默认只支持批量查看,不支持批量更新(局部或整体)和批量删除。下面我们来讨论这个问
- Oracle 背景资料 在介绍 Oracle9i 之前我们先介绍一些关于Oracle 公司的资料,让各位朋友更多了解 Oracle。 197
- 有时候难免需要直接调用Shell命令来完成一些比较简单的操作,比如mount一个文件系统之类的。那么我们使用Python如何调用Linux的
- 开放源代码社区为了扩展MySQL的使用范围,开发出了.Net框架(.NET Framework)中可以使用的数据库连接器。我们就来学习一下如
- 解决办法: 1.新建一个同名的数据库(数据文件与原来的要一致) 2.再停掉sql server(注意不要分离数据库) 3.用原数据库的数据文
- YAHOO.util.Subscriber 与 YAHOO.util.CustomEvent。1. YAHOO
- 前言matplotlib.pyplot是一些命令行风格函数的集合,使matplotlib以类似于MATLAB的方式工作。每个pyplot函数