获取zabbix监控数据

#!/usr/bin/python3
# @Date: 2020/8/20 14:16
# @Author: zhangcheng
# @email: 3359957053@qq.com
# -*- coding: utf-8 -*-import pymysql
import time,datetime
import math#zabbix数据库信息:
zdbhost = "192.168.63.141"
zdbuser = "zabbix"
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.util[,user,avg5]',#'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 IpInfoListdef __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 = Nonereturn itemiddef getTrendsValue(self,itemid, start_time, stop_time):'''查询trends_uint表的值,type的值为min,max,avg三种'''resultlist = {}for type in ['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)print(sql)result = self.cursor.fetchone()[0]if result == None:result = 0resultlist[type] = resultreturn resultlistdef getTrends_uintValue(self,itemid, start_time, stop_time):'''查询trends_uint表的值,type的值为min,max,avg三种'''resultlist = {}for type in ['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] = resultelse:resultlist[type] = 0return resultlistdef 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()))# print(ts_lnow_time =int(time.mktime(datetime.datetime.now().timetuple()))#print(now_time)#print(now_time)itemid = self.__getItemid(hostid, itemname)function = getattr(self,'get{0}Value'.format(table.capitalize()))return  function(itemid, now_time, 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("	正在统计 key_:'{0}'".format(key))#print("	正在统计 key_:'{0}'".format(key))#print("	正在统计 key_:'{0}'".format(table))data =  zabbix.getLastMonthData(resultdict['hostid'],table,key)zabbix.IpInfoList[ip][key] = datadef writeToXls(self):'''生成xls文件'''try:import xlsxwriterdate = time.strftime("%Y-%m",time.localtime())#创建文件'filename=self.groupname + "-" +date + ".xlsx"workbook = xlsxwriter.Workbook(filename)#创建工作薄worksheet = workbook.add_worksheet()#写入标题(第一行)i = 0#for value in ["归属部门","主机","CPU核数","CPU平均空闲值","CPU最小空闲值","CPU15分钟负载"]:for value in ["归属部门", "主机", "CPU负载"]:worksheet.write(0,i, value)i = i + 1#写入内容:j = 1for ip,value in self.IpInfoList.items():worksheet.write(j, 0, self.groupname)worksheet.write(j,1, ip)#print(value['system.cpu.num']['avg'])#worksheet.write(j,2, '{}'.format(value['system.cpu.num']['avg']))worksheet.write(j,2, '{:.2f}%'.format(value['system.cpu.util[,user,avg5]']['avg']))# worksheet.write(j,4, '{:.2f}%'.format(value['system.cpu.util[,idle]']['min']))#worksheet.write(j,1, '{:.2f}'.format(value['system.cpu.util[all,user,avg5]']['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 + 1workbook.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()

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/535381.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

logstash安装

下载最新版logstash https://www.elastic.co/cn/downloads/logstash 解压缩 tar zxvf logstash-7.12.1-linux-x86_64.tar.gz 下载jdk1.8 tar zxvf jdk-8u291-linux-x64.tar.gz 编辑启动文件logstash、logstash.lib.sh、logstash-plugin 在首行添加 export JAVA_C…

[logstash-input-file]插件使用详解

这个插件可以从指定的目录或者文件读取内容&#xff0c;输入到管道处理&#xff0c;也算是logstash的核心插件了&#xff0c;大多数的使用场景都会用到这个插件&#xff0c;因此这里详细讲述下各个参数的含义与使用 1 path 是必须的选项&#xff0c;每一个file配置&#xff0c…

[logstash-input-log4j]插件使用

Log4j插件可以通过log4j.jar获取Java日志&#xff0c;搭配Log4j的SocketAppender和SocketHubAppender使用&#xff0c;常用于简单的集群日志汇总。 最小化的配置 input {log4j {host>"localhost"port>4560} } output {stdout {} } log4j插件配置host以及port就…

logstash-input-redis插件使用详解

input {#redis {#host> "10.246.187.12"#redis地址#host> "10.246.152.116"#redis地址#port > "6379" #redis端口号#password > "123qwe" #如果有安全认证&#xff0c;此项为密码#key > "logstash:redis"#ty…

logstash-input-redis源码解析

首先是程序的自定义&#xff0c;这里设置了redis插件需要的参数&#xff0c;默认值&#xff0c;以及校验等。 然后注册Redis实例需要的信息&#xff0c;比如key的名字或者url等&#xff0c;可以看到默认的data_type是list模式。 程序运行的主要入口&#xff0c;根据不同的dat…

logstash-filter模块

Fillters 在Logstash处理链中担任中间处理组件。他们经常被组合起来实现一些特定的行为来&#xff0c;处理匹配特定规则的事件流。常见的filters如下&#xff1a; grok&#xff1a;解析无规则的文字并转化为有结构的格式。Grok 是目前最好的方式来将无结构的数据转换为有结构可…

weblogic启动慢

1.最差的解决办法 执行命令 mv /dev/random /dev/random.ORIG ln /dev/urandom /dev/random   将/dev/random 指向/dev/urandom 2. 较好的解决办法&#xff1a; 在weblogic启动脚本里setDomainEnv.sh: 加入以下内容 JAVA_OPTIONS"${JAVA_OPTIONS}" -Dja…

SSL双向认证和SSL单向认证的区别

双向认证 SSL 协议要求服务器和用户双方都有证书。单向认证 SSL 协议不需要客户拥有CA证书&#xff0c;具体的过程相对于上面的步骤&#xff0c;只需将服务器端验证客户证书的过程去掉&#xff0c;以及在协商对称密码方案&#xff0c;对称通话密钥时&#xff0c;服务器发送给客…

双向认证SSL原理

文中首先解释了加密解密的一些基础知识和概念&#xff0c;然后通过一个加密通信过程的例子说明了加密算法的作用&#xff0c;以及数字证书的出现所起的作用。接着对数字证书做一个详细的解释&#xff0c;并讨论一下windows中数字证书的管理&#xff0c;最后演示使用makecert生成…

Xtrabackup备份与恢复

一、Xtrabackup介绍 Percona-xtrabackup是 Percona公司开发的一个用于MySQL数据库物理热备的备份工具&#xff0c;支持MySQL、Percona server和MariaDB&#xff0c;开源免费&#xff0c;是目前较为受欢迎的主流备份工具。xtrabackup只能备份innoDB和xtraDB两种数据引擎的表&…

实时备份工具之inotify+rsync

1.inotify简介 inotify 是一个从 2.6.13 内核开始&#xff0c;对 Linux 文件系统进行高效率、细粒度、异步地监控机制&#xff0c; 用于通知用户空间程序的文件系统变化。可利用它对用户空间进行安全、性能、以及其他方面的监控。Inotify 反应灵敏&#xff0c;用法非常简单&…

nginx proxy_cache缓存详解

目录 1. 关于缓冲区指令 1.1 proxy_buffer_size1.2 proxy_buffering1.3 proxy_buffers1.4 proxy_busy_buffers_size1.5 proxy_max_temp_file_size1.6 proxy_temp_file_write_size1.7 缓冲区配置实例2. 常用配置项 2.1 proxy_cache_path2.2 proxy_temp_path2.3 proxy_cache2.4 …

mysql主从延迟

在实际的生产环境中&#xff0c;由单台MySQL作为独立的数据库是完全不能满足实际需求的&#xff0c;无论是在安全性&#xff0c;高可用性以及高并发等各个方面 因此&#xff0c;一般来说都是通过集群主从复制&#xff08;Master-Slave&#xff09;的方式来同步数据&#xff0c…

16张图带你吃透高性能 Redis 集群

现如今 Redis 变得越来越流行&#xff0c;几乎在很多项目中都要被用到&#xff0c;不知道你在使用 Redis 时&#xff0c;有没有思考过&#xff0c;Redis 到底是如何稳定、高性能地提供服务的&#xff1f; 你也可以尝试回答一下以下这些问题&#xff1a; 我使用 Redis 的场景很…

Redis与MySQL双写一致性如何保证

谈谈一致性 一致性就是数据保持一致&#xff0c;在分布式系统中&#xff0c;可以理解为多个节点中数据的值是一致的。 强一致性&#xff1a;这种一致性级别是最符合用户直觉的&#xff0c;它要求系统写入什么&#xff0c;读出来的也会是什么&#xff0c;用户体验好&#xff0c;…

weblogic忘记console密码

进入 cd /sotware/oracle_ldap/Middleware/user_projects/domains/base_domain/security/ 目录 执行 java -classpath /sotware/oracle_ldap/Middleware/wlserver_10.3/server/lib/weblogic.jar weblogic.security.utils.AdminAccount weblogic(账号) weblogic123(密码) . …

Mysql高性能优化技能总结

数据库命令规范 所有数据库对象名称必须使用小写字母并用下划线分割 所有数据库对象名称禁止使用mysql保留关键字&#xff08;如果表名中包含关键字查询时&#xff0c;需要将其用单引号括起来&#xff09; 数据库对象的命名要能做到见名识意&#xff0c;并且最后不要超过32个…

Redis的AOF日志

如果 Redis 每执行一条写操作命令&#xff0c;就把该命令以追加的方式写入到一个文件里&#xff0c;然后重启 Redis 的时候&#xff0c;先去读取这个文件里的命令&#xff0c;并且执行它&#xff0c;这不就相当于恢复了缓存数据了吗&#xff1f; 这种保存写操作命令到日志的持久…

Redis 核心技术与实战

目录 开篇词 | 这样学 Redis&#xff0c;才能技高一筹 01 | 基本架构&#xff1a;一个键值数据库包含什么&#xff1f; 02 | 数据结构&#xff1a;快速的Redis有哪些慢操作&#xff1f; 键和值用什么结构组织&#xff1f; 为什么哈希表操作变慢了&#xff1f; 有哪些底层数…

redis核心技术与实战(二)缓存应用篇

1.《旁路缓存&#xff1a;redis 在缓存中工作原理》 1.缓存的两个特征 1.什么是缓存&#xff0c;有什么特征&#xff1f; 磁盘->内存->cpu 之间读写速度差异巨大&#xff0c;为了平衡他们之间的差异&#xff0c;操作系统默认使用了两种缓存&#xff1b; CPU 里面的末级…