import pymysql as MySQLdb
import time
import datetime
import xlsxwriter # zabbix数据库信息:
zdbhost = 'xxx.xxx.xxx.xxx'
zdbuser = 'MySQL-username'
zdbpass = MySQL-PassWord'
zdbport = 3306
zdbname = 'zabbix-DBName' # 生成文件名称:
xlsfilename = 'Group_Production_Server.xlsx' # 需要查询的key列表 [名称,表名,key值,取值,格式化,数据整除处理]
keys = [
['CPU空闲率(%)', 'trends', 'system.cpu.util[,idle]', 'avg', '%.2f', 1],
['内存使用率(G)', 'trends_uint', 'vm.memory.size[total]', 'avg', '%.2f', 1],
['磁盘使用率(%)', 'trends', 'system.cpu.util[,iowait]', 'avg', '%.2f', 1],
] class ReportForm(object): def __init__(self):
"""打开数据库连接"""
self.conn = MySQLdb.connect(host=zdbhost, user=zdbuser, passwd=zdbpass, port=zdbport, db=zdbname)
self.cursor = self.conn.cursor()
# 生成zabbix哪个分组报表
self.groupname = 'Mysql'
# 获取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()[0]
# 根据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[0]
sql = '''SELECT ip from interface WHERE hostid = '%s' ''' % hostid
ret = self.cursor.execute(sql)
if ret:
IpInfoList[self.cursor.fetchone()[0]] = {'hostid': hostid}
return IpInfoList def __getItemid(self, hostid, itemname):
"""获取itemid""" sql = '''select itemid from items where hostid = '%s' and key_ = '%s' ''' % (hostid, itemname)
self.cursor.execute(sql)
itemid = self.cursor.fetchone()[0]
# print('hostid --> ', hostid)
# print('itemid --> ', itemid)
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)
# print('trends --> ', sql)
self.cursor.execute(sql)
result = self.cursor.fetchone()[0]
if result == None:
result = 0
# print('trends - result --> ', result)
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)
# print('trends_uint --> ', sql)
self.cursor.execute(sql)
result = self.cursor.fetchone()[0] / 1073741824
if result:
result = int(result)
else:
result = 0
# print('trends_uint - result--> ', result)
return result def getLastMonthData(self, type, hostid, table, itemname):
"""根据hostid,itemname获取该监控项的值""" # 获取上个月的第20天和最后1天
ts_first = int(
time.mktime(datetime.date(datetime.date.today().year, datetime.date.today().month - 1, 20).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文件""" # 创建文件
workbook = xlsxwriter.Workbook(xlsfilename)
# 创建工作薄
worksheet = workbook.add_worksheet()
# 写入第一列:
worksheet.write(0, 0, "主机")
i = 1
for ip in self.IpInfoList:
worksheet.write(i, 0, ip)
i = i + 1
# 写入其他列:
for i in range(1, 5):
i = 1
for value in keys:
worksheet.write(0, i, value[0])
# 写入该列内容:
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
workbook.close() def __del__(self):
"""关闭数据库连接""" self.cursor.close()
self.conn.close() if __name__ == "__main__":
zabbix = ReportForm()
zabbix.getInfo()
zabbix.writeToXls2()

参考: https://www.jb51.net/article/167771.htm

获取Zabbix 中资源的使用率的更多相关文章

  1. linux中使用top获取进程的资源占用信息

    在linux中使用top获取进程的资源占用信息: Cpu(s):  1.0%us,  0.0%sy,  0.0%ni, 98.3%id,  0.7%wa,  0.0%hi,  0.0%si,  0.0 ...

  2. Zabbix中获取各用户告警媒介分钟级统计

    任务内容: 获取Zabbix各用户告警媒介分钟级统计,形成趋势图,便于观察各用户在每分钟收到的告警数量,在后续处理中,可以根据用户在某时间段内(例如3分钟内)收到的邮件总数,来判断是否有告警洪水的现象 ...

  3. Spring core resourc层结构体系及JDK与Spring对classpath中资源的获取方式及结果对比

    1. Spring core resourc层结构体系 1.1. Resource相关结构体系 1.2. ResourceLoader相关体系 2. JDK与Spring对classpath中资源的获 ...

  4. 从加载DLL的中获取放置于Resources文件夹中资源字典的几种方法

    原文:从加载DLL的中获取放置于Resources文件夹中资源字典的几种方法 主程序 为 Main_Test.exe 被加载的DLL 为 Load_Test.dll  此DLL 中 有一个 文件夹Re ...

  5. linux下获取占用CPU资源最多的10个进程

    linux下获取占用CPU资源最多的10个进程,可以使用如下命令组合: ps aux|head -1;ps aux|grep -v PID|sort -rn -k +3|head linux下获取占用 ...

  6. linux下获取占用CPU资源最多的10个进程,可以使用如下命令组合:

    linux下获取占用CPU资源最多的10个进程,可以使用如下命令组合: ps aux|head -1;ps aux|grep -v PID|sort -rn -k +3|head linux下获取占用 ...

  7. zabbix 中监控windows 的typepref中的值

    监控项:typepref -qx在zabbix中实现: 1.测试zabbix-get 获取数据: /usr/local/zabbix/bin/zabbix_get -s 192.168.1.3 -p1 ...

  8. SpringMVC核心——参数获取与Servlet资源获取问题

    一.SpringMVC 使用 @PathVariable.@RequestParam.@RequestHeader.@CookieValue 等来解决参数获取问题. 1. @PathVariable: ...

  9. Yii中使用PHPexcel获取excel中数据

    1.view中代码如下: <form name="frmBatchSettle" id="" action="" method=&qu ...

随机推荐

  1. Spring Boot (日志篇):Log4j2整合ELK,搭建实时日志平台

    一.安装JDK1.8以上版本 1.从Oracle官网上下载Linux x64版本的 下载地址: http://www.oracle.com/technetwork/java/javase/downlo ...

  2. 星空 题意转化,差分,状压DP

    好题(爆搜和puts("2")一个分(雾)),不得不说思维真的强. 首先发现区间翻转很难受,考虑用差分(异或满足可逆性),注意是从0到n+1 然后就转化题意,操作改为选取距离为L的 ...

  3. 使用vue-cookies操作cookie

    1.前言 在vue中如果想要操作cookie,除了使用之前我们自己封装好的操作cookie的方法之外,我们还可以使用vue-cookies插件,这是一个简单的Vue.js插件,专门用于在vue中处理浏 ...

  4. 爬虫学习--常用的正则表达式 Day3

    在做爬虫经常遇到需要用正则校验数据时候,往往是在网上去找很久,结果找来的还是不很符合要求.所以我最近把开发中常用的一些正则表达式整理了一下,给自己留个底,也给朋友们做个参考. 一.校验数字的表达式 1 ...

  5. drf

    跨域同源 django做跨域同源 需要把csrf去掉 跨站请求伪造 同源 同源机制:域名.协议.端口号相同的同源 简单请求 不写头部请求 跨域会拦截报错缺少请求信息 (1) 请求方法是以下三种方法之一 ...

  6. aop的简单使用(代码和配置记录)

    Spring aop 简单示例 简单的记录一下spring aop的一个示例 基于两种配置方式: 基于xml配置 基于注解配置 这个例子是模拟对数据库的更改操作添加事物 其实并没有添加,只是简单的输出 ...

  7. @Transactional 的回滚

    默认情况下,Exception是不会引起回滚操作的,RuntimeException才会引起回滚操作. 当然如果所有的Exception都要回滚的话,直接@Transactional(rollback ...

  8. Flink入门(一)——Apache Flink介绍

    Apache Flink是什么? ​ 在当代数据量激增的时代,各种业务场景都有大量的业务数据产生,对于这些不断产生的数据应该如何进行有效的处理,成为当下大多数公司所面临的问题.随着雅虎对hadoop的 ...

  9. JS 原生面经从入门到放弃 篇幅较长,建议收藏

    前言 是时候撸一波 JS 基础啦,撸熟了,银十速拿 offer; 本文不从传统的问答方式梳理,而是从知识维度梳理,以便形成知识网络; 包括函数,数组,对象,数据结构,算法,设计模式和 http. 函数 ...

  10. MyBatis:统计数量(查询所有)

    返回值的类型:resultType="java.lang.Integer". <select id="count" resultType="ja ...