Python+Mysql生成zabbix统计数据(优化)

本文涉及的产品
RDS MySQL Serverless 基础系列,0.5-2RCU 50GB
云数据库 RDS MySQL,集群系列 2核4GB
推荐场景:
搭建个人博客
云数据库 RDS PostgreSQL,集群系列 2核4GB
简介:

周末重新整理了一下,把有些不合理的地方改了下,自我感觉好多了

ZabbixReport.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
#!/usr/bin/python
#coding:utf-8
 
import  MySQLdb
import  time,datetime
 
 
#zabbix数据库信息:
zdbhost  =  '192.168.1.100'
zdbuser  =  'zabbix'
zdbpass  =  'zabbixreport'
zdbport  =  3306
zdbname  =  'zabbix'
 
#生成文件名称:
xlsfilename  =  'damo.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  =  '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  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' ))
             =  1
             for  ip  in  self .IpInfoList:
                 worksheet.write(i, 0 ,ip)
                 =  +  1
 
             #写入其他列:
             =  1
             for  value  in  keys:
                 worksheet.write( 0 ,i,value[ 0 ].decode( 'utf-8' ))
 
                 #写入该列内容:
                 =  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 ])
                     =  +  1
 
                 =  +  1
         except  Exception,e:
             print  e
 
 
 
     def  __del__( self ):
         '''关闭数据库连接'''
         self .cursor.close()
         self .conn.close()
 
if  __name__  = =  "__main__" :
     zabbix  =  ReportForm()
     zabbix.getInfo()
     zabbix.writeToXls2()
本文转自运维笔记博客51CTO博客,原文链接http://blog.51cto.com/lihuipeng/1535454如需转载请自行联系原作者                                                                                                                                                                                                                                                lihuipeng
相关实践学习
如何快速连接云数据库RDS MySQL
本场景介绍如何通过阿里云数据管理服务DMS快速连接云数据库RDS MySQL,然后进行数据表的CRUD操作。
全面了解阿里云能为你做什么
阿里云在全球各地部署高效节能的绿色数据中心,利用清洁计算为万物互联的新世界提供源源不断的能源动力,目前开服的区域包括中国(华北、华东、华南、香港)、新加坡、美国(美东、美西)、欧洲、中东、澳大利亚、日本。目前阿里云的产品涵盖弹性计算、数据库、存储与CDN、分析与搜索、云通信、网络、管理与监控、应用服务、互联网中间件、移动服务、视频服务等。通过本课程,来了解阿里云能够为你的业务带来哪些帮助 &nbsp; &nbsp; 相关的阿里云产品:云服务器ECS 云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。产品详情: https://www.aliyun.com/product/ecs
相关文章
【Azure Developer】分享两段Python代码处理表格(CSV格式)数据 : 根据每列的内容生成SQL语句
本文介绍了使用Python Pandas处理数据收集任务中格式不统一的问题。针对两种情况:服务名对应多人拥有状态(1/0表示),以及服务名与人名重复列的情况,分别采用双层for循环和字典数据结构实现数据转换,最终生成Name对应的Services列表(逗号分隔)。此方法高效解决大量数据的人工处理难题,减少错误并提升效率。文中附带代码示例及执行结果截图,便于理解和实践。
淘宝商品详情API的调用流程(python请求示例以及json数据示例返回参考)
JSON数据示例:需要提供一个结构化的示例,展示商品详情可能包含的字段,如商品标题、价格、库存、描述、图片链接、卖家信息等。考虑到稳定性,示例应基于淘宝开放平台的标准响应格式。
MySQL细节优化:关闭大小写敏感功能的方法。
通过这种方法,你就可以成功关闭 MySQL 的大小写敏感功能,让你的数据库操作更加便捷。
60 19
如何在Python下实现摄像头|屏幕|AI视觉算法数据的RTMP直播推送
本文详细讲解了在Python环境下使用大牛直播SDK实现RTMP推流的过程。从技术背景到代码实现,涵盖Python生态优势、AI视觉算法应用、RTMP稳定性及跨平台支持等内容。通过丰富功能如音频编码、视频编码、实时预览等,结合实际代码示例,为开发者提供完整指南。同时探讨C接口转换Python时的注意事项,包括数据类型映射、内存管理、回调函数等关键点。最终总结Python在RTMP推流与AI视觉算法结合中的重要性与前景,为行业应用带来便利与革新。
【YashanDB知识库】python驱动查询gbk字符集崖山数据库CLOB字段,数据被驱动截断
【YashanDB知识库】python驱动查询gbk字符集崖山数据库CLOB字段,数据被驱动截断
Python 请求微店商品详情数据 API 接口
微店开放平台允许开发者通过API获取商品详情数据。使用Python请求微店商品详情API的主要步骤包括:1. 注册并申请API权限,获得app_key和app_secret;2. 确定API接口地址与请求参数,如商品ID;3. 生成签名确保请求安全合法;4. 使用requests库发送HTTP请求获取数据;5. 处理返回的JSON格式响应数据。开发时需严格遵循微店API文档要求。
Python爬虫实战:一键采集电商数据,掌握市场动态!
这个爬虫还挺实用,不光能爬电商数据,改改解析规则,啥数据都能爬。写爬虫最重要的是要有耐心,遇到问题别着急,慢慢调试就成。代码写好了,运行起来那叫一个爽,分分钟几千条数据到手。
基于SQL Server / MySQL进行百万条数据过滤优化方案
对百万级别数据进行高效过滤查询,需要综合使用索引、查询优化、表分区、统计信息和视图等技术手段。通过合理的数据库设计和查询优化,可以显著提升查询性能,确保系统的高效稳定运行。
64 9
python语言采集淘宝商品详情数据,json数据示例返回
通过淘宝开放平台的API接口,开发者可以轻松获取商品详情数据,并利用这些数据进行商品分析、价格监控、库存管理等操作。本文提供的示例代码和JSON数据解析方法,可以帮助您快速上手淘宝商品数据的采集与处理。

热门文章

最新文章

AI助理

你好,我是AI助理

可以解答问题、推荐解决方案等