標籤:python mysql zabbix 統計 報表
先大概瞭解一下zabbix資料庫結構:
1、groups表
650) this.width=650;" src="http://s3.51cto.com/wyfs02/M01/43/5E/wKioL1PZ9l2DeGFfAAEDMjzH7lI086.jpg" title="1.png" alt="wKioL1PZ9l2DeGFfAAEDMjzH7lI086.jpg" />
可以根據組名查到組ID
2、找到組ID就可以根據組ID找出這個組下面的所有伺服器的ID,這個關係在hosts_groups表裡面:
650) this.width=650;" src="http://s3.51cto.com/wyfs02/M02/43/5E/wKioL1PZ9vfBBxHKAAEPD2MX5VU788.jpg" title="2.png" alt="wKioL1PZ9vfBBxHKAAEPD2MX5VU788.jpg" />
3、有了hostid就可以在hosts表裡查看這台機器的基本資料了:
650) this.width=650;" src="http://s3.51cto.com/wyfs02/M01/43/5F/wKioL1PZ98jCuezkAAPU0Vuzf4s989.jpg" style="float:none;" title="3.png" alt="wKioL1PZ98jCuezkAAPU0Vuzf4s989.jpg" />
items表則可以根據hostid查出這台伺服器的所有監控項:
650) this.width=650;" src="http://s3.51cto.com/wyfs02/M00/43/5E/wKiom1PZ9q_y6ZdqAALMc4xTfZE224.jpg" style="float:none;" title="4.png" alt="wKiom1PZ9q_y6ZdqAALMc4xTfZE224.jpg" />
4、終於在items表查到itemid,利用這個itemid在trends和trends_uint這兩個表中統計出我們需要的資料
650) this.width=650;" src="http://s3.51cto.com/wyfs02/M01/43/5E/wKiom1PZ91LgY2LoAAGEwEweiyA064.jpg" title="5.png" alt="wKiom1PZ91LgY2LoAAGEwEweiyA064.jpg" />
我python水平挺菜的,很多物件導向的功能都不知道咋用,求大神教育
#!/usr/bin/python#coding:utf-8import MySQLdbimport time,datetime#zabbix資料庫資訊:zdbhost = ‘192.168.1.1‘zdbuser = ‘zabbix‘zdbpass = ‘zabbixreport‘zdbport = 3306zdbname = ‘zabbix‘#需要查詢的key列表keys = { ‘trends_uint‘:[ ‘net.if.in[eth0]‘, ‘net.if.out[eth0]‘, ‘vfs.fs.size[/,used]‘, ‘vm.memory.size[available]‘, ], ‘trends‘:[ ‘system.cpu.load[percpu,avg5]‘, ‘system.cpu.util[,idle]‘, ], }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 = ‘qjsh‘ #擷取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,itemid, start_time, stop_time): ‘‘‘查詢trends_uint表的值,type的值為min,max,avg三種‘‘‘ resultlist = {} for type in [‘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 resultlist[type] = result return resultlist def getTrends_uintValue(self,itemid, start_time, stop_time): ‘‘‘查詢trends_uint表的值,type的值為min,max,avg三種‘‘‘ resultlist = {} for type in [‘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: resultlist[type] = int(result) else: resultlist[type] = 0 return resultlist def getLastMonthData(self,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(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 table, keylists in keys.items(): for key in keylists: print "\t正在統計 key_:%s" % key data = zabbix.getLastMonthData(resultdict[‘hostid‘],table,key) zabbix.IpInfoList[ip][key] = data def writeToXls(self): ‘‘‘產生xls檔案‘‘‘ try: import xlsxwriter #建立檔案 workbook = xlsxwriter.Workbook(‘damo.xls‘) #建立工作薄 worksheet = workbook.add_worksheet() #寫入標題(第一行) i = 0 for value in ["主機","CPU平均空閑值","CPU最小空閑值","可用平均記憶體(單位M)","可用最小記憶體(單位M)","CPU5分鐘負載","進入最大流量(單位Kbps)","進入平均流量(單位Kbps)","出去最大流量(單位Kbps)","出去平均流量(單位Kbps)"]: worksheet.write(0,i, value.decode(‘utf-8‘)) i = i + 1 #寫入內容: j = 1 for ip,value in self.IpInfoList.items(): worksheet.write(j,0, ip) worksheet.write(j,1, ‘%.2f‘ % value[‘system.cpu.util[,idle]‘][‘avg‘]) worksheet.write(j,2, ‘%.2f‘ % value[‘system.cpu.util[,idle]‘][‘min‘]) worksheet.write(j,3, ‘%dM‘ % int(value[‘vm.memory.size[available]‘][‘avg‘] / 1024 / 1024)) worksheet.write(j,4, ‘%dM‘ % int(value[‘vm.memory.size[available]‘][‘min‘] / 1024 / 1024)) worksheet.write(j,5, ‘%.2f‘ % value[‘system.cpu.load[percpu,avg5]‘][‘avg‘]) worksheet.write(j,6, value[‘net.if.in[eth0]‘][‘max‘]/1000) worksheet.write(j,7, value[‘net.if.in[eth0]‘][‘avg‘]/1000) worksheet.write(j,8, value[‘net.if.out[eth0]‘][‘max‘]/1000) worksheet.write(j,9, value[‘net.if.out[eth0]‘][‘avg‘]/1000) j = j + 1 workbook.close() except Exception,e: print e def __del__(self): ‘‘‘關閉資料庫連接‘‘‘ self.cursor.close() self.conn.close()if __name__ == "__main__": zabbix = ReportForm() zabbix.getInfo() zabbix.writeToXls()
產生xls檔案我用了一個叫xlsxwriter的第三方庫,這個庫只能寫不能讀,感覺還可以,產生出來的效果:
650) this.width=650;" src="http://s3.51cto.com/wyfs02/M01/43/5F/wKioL1PZ-VWAgEvhAAbEjHEpkVM093.jpg" title="6.png" alt="wKioL1PZ-VWAgEvhAAbEjHEpkVM093.jpg" />
本文出自 “營運筆記” 部落格,請務必保留此出處http://lihuipeng.blog.51cto.com/3064864/1533315