獲取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.pswp.cn/news/535381.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/535381.shtml
英文地址,請注明出處:http://en.pswp.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 里面的末級…