Zabbix没有报表导出的功能,于是通过编写脚本导出zabbix数据并发邮件。效果如下:

下面是脚本,可根据自己的具体情况修改:

#!/usr/bin/python
#coding:utf-8 import MySQLdb
import time,datetime
import xlsxwriter import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header #zabbix数据库信息:
zdbhost = '127.0.0.1'
zdbuser = 'zabbix'
zdbpass = 'zabbix'
zdbport = 3306
zdbname = 'zabbix' #生成文件名称:
xlsfilename = 'Group_Production_Server.xlsx' #需要查询的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],
['CPU使用率(%)','trends','CPU_used','avg','%.2f',1],
#['内存大小(单位G)','trends_uint','vm.memory.size[total]','avg','',1048576000],
#['剩余内存(单位G)','trends_uint','vm.memory.size[available]','avg','',1048576000],
['内存使用率(%)','trends','Memory_used','avg','%.2f',1],
# ['可用平均内存(单位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],
#['磁盘总大小(单位G)','trends_uint','vfs.fs.size[/fs01,total]','avg','',1073741824],
#['磁盘剩余(单位G)','trends_uint','vfs.fs.size[/fs01,free]','avg','',1073741824],
['磁盘使用率(%)','trends','fs01_used','avg','%.2f',1],
# ['进入最大流量(单位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 = 'Group_Production_Server' #获取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,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获取该监控项的值'''
#获取上个月的第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 getNowData(self):
nowtime = datetime.datetime.now().strftime('%Y-%m-%d')
return nowtime 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,"主机".decode('utf-8'))
i = 1
for ip in self.IpInfoList:
worksheet.write(i,0,ip)
i = i + 1 #写入其他列:
i = 1
for value in keys:
worksheet.write(0,i,value[0].decode('utf-8')) #写入该列内容:
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()
def Send_Email(self):
sender = 'from@runoob.com'
receivers = ['hejianlai@pci.cn'] # 接收邮件,可设置为你的QQ邮箱或者其他邮箱 #创建一个带附件的实例
message = MIMEMultipart()
message['From'] = Header("Zabbix_server", 'utf-8')
message['To'] = Header("it", 'utf-8')
subject = '生产环境虚机资源使用情况'
message['Subject'] = Header(subject, 'utf-8') #邮件正文内容
message.attach(MIMEText('生产环境虚机资源使用情况', 'plain', 'utf-8')) # 构造附件1,传送当前目录下的 test.txt 文件
att1 = MIMEText(open('Group_Production_Server.xlsx', 'rb').read(), 'base64', 'utf-8')
att1["Content-Type"] = 'application/octet-stream'
# 这里的filename可以任意写,写什么名字,邮件中显示什么名字
att1["Content-Disposition"] = 'attachment; filename="Group_Production_Server.xlsx"'
message.attach(att1) try:
smtpObj = smtplib.SMTP('localhost')
smtpObj.sendmail(sender, receivers, message.as_string())
print "邮件发送成功"
except smtplib.SMTPException:
print "Error: 无法发送邮件" if __name__ == "__main__":
zabbix = ReportForm()
zabbix.getInfo()
zabbix.writeToXls2()
zabbix.Send_Email()

python导出zabbix数据并发邮件脚本的更多相关文章

  1. SQL Server定时自动抓取耗时SQL并归档数据发邮件脚本分享

    SQL Server定时自动抓取耗时SQL并归档数据发邮件脚本分享 第一步建库和建表 USE [master] GO CREATE DATABASE [MonitorElapsedHighSQL] G ...

  2. 通过python为zabbix发送告警邮件

    最近部署ZABBIX的邮件告警时,用刚学的python来写告警邮件脚本. 由于时间有限,我只对关键步骤做截图,对zabbix的基本配置略过. python代码如下 1 #!/usr/bin/pytho ...

  3. Python迁移MySQL数据到MongoDB脚本

    MongoDB是一个文档数据库,在存储小文件方面存在天然优势.随着业务求的变化,需要将线上MySQL数据库中的行记录,导入到MongoDB中文档记录. 一.场景:线上MySQL数据库某表迁移到Mong ...

  4. Python脚本:爬取天气数据并发邮件给心爱的Ta

    第一部分:爬取天气数据 # 在函数调用 get_weather(url = 'https://www.tianqi.com/foshan') 的 url中更改城市,foshan为佛山市 1 impor ...

  5. PHP调用Python快速发送高并发邮件

    1 简介 在PHP中发送邮件,通常都是封装一个php的smtp邮件类来发送邮件.但是PHP底层的socket编程相对于Python来说效率是非常低的.CleverCode同时写过用python写的爬虫 ...

  6. 用Python控制摄像头拍照并发邮件

    概述前言 工具 思路 安装及导入包 设置参数 实现拍照 构造邮件内容 发送邮件 判断网络连接 开机自启 后记 o1 前言为什么会有写这个程序的想法呢? 最初的想法是写一个可以用电脑前置摄像头拍照的程序 ...

  7. SQL Server里面如何导出包含数据的SQL脚本

    通常情况下,SQL Server里面的生成SQL脚本,只会包含数据库及表的字段结构,而不会包含表的数据,也就是SQL脚本里面只有Create database,Create table 这样的语句,没 ...

  8. python 导出mongoDB数据中的数据

    import pymongo,urllibimport sysimport timeimport datetimereload(sys)sys.setdefaultencoding('utf8')fr ...

  9. python使用zabbix的API接口

    一.实验环境 python3.6.6 zabbix 3.0.9 二.实验目的 了解Zabbix的API接口格式 通过python实现登陆zabbix服务,获得登陆token 通过python检索zab ...

随机推荐

  1. PhpStorm服务激活

    日期 服务地址 状态  2018-03-15  http://idea.singee77.com/  使用中

  2. 神奇的ASCⅡ码图

    神奇的ASCⅡ码图 可能在网上也常见了asc2码图,但你知道是怎么做出来的吗?(总不可能是人一个一个字码进去的吧,当然,不排除有这种神人的可能

  3. vue实现淘宝商品详情页属性选择功能

    方法一是自己想出来的,方法二来自忘记哪里看到的了 不知道是不是你要的效果: 方法一:利用input[type="radio"] css代码: input { display: no ...

  4. Hive入门学习--HIve简介

    现在想要应聘大数据分析或者数据挖掘岗位,很多都需要会使用Hive,Mapreduce,Hadoop等这些大数据分析技术.为了充实自己就先从简单的Hive开始吧.接下来的几篇文章是记录我如何入门学习Hi ...

  5. 在C# 中 如何限制在文本框(textBox)中输入的类型为正整数

    在文本框的 KeyPress 事件中写下这些代码就可以保证是正整数了 private void textBox1_KeyPress(object sender, KeyPressEventArgs e ...

  6. Python中Json对象处理的jsonpath-rw

    这两天在写一个爬虫,需要从网站返回的json数据提取一些有用的数据. 向url发起请求,返回的是response,在python3中,response.content是二进制bytes类型的,需要用d ...

  7. Scrapy爬虫框架第一讲(Linux环境)

    1.What is Scrapy? 答:Scrapy是一个使用python语言(基于Twistec框架)编写的开源网络爬虫框架,其结构清晰.模块之间的耦合程度低,具有较强的扩张性,能满足各种需求.(前 ...

  8. Spring Boot常用注解总结

    Spring Boot常用注解总结 @RestController和@RequestMapping注解 @RestController注解,它继承自@Controller注解.4.0之前的版本,Spr ...

  9. “史上更难就业季”暴露出啥隐情?

      如果说,2013年中国高校毕业生达到699万,被称为"史上最难就业季".那么2014年将成为去年之后的"更难就业季".据最新资料显示,2014年应届大学毕业 ...

  10. Java 领域从传统行业向互联网转型你必须知道的事儿

    我为什么要写这篇文章 武林中,"天下武功出少林"指各门各派的武功都与少林武学有一定的渊源,技术也是相同的道理,对于Java领域的应用而言,传统行业与互联网行业的技术都来自J2SE和 ...