Zabbix日志监视的汇总报警(更新发送邮件脚本)
Zabbix的用户一定会碰到这种情况:
日志报警一般设置的是multiple模式,有错误大量写入的时候,每写入一行就会触发一次action,导致出现大量的报警邮件。
特别是ora的报警,经常一出就是上千条,有时候会让别的报警都淹没在ora的邮件中。
这时候就考虑能不能让日志的报警汇总,同样的内容在一定的时间内只发送一封邮件。
基本思想就是:
1,日志写入à触发actionà将报警内容写入数据库
2,Crontab定期查询数据库à有报警就汇总发送邮件à发送完成后清空数据表
详细步骤如下:
1,zabbix上的设置
administratoràMediaTypes ,新建MediaTypes(writetodb),type选择Script,脚本名称命名为writetodb.py
administratoràUsers ,新建User(writetodb),Media中添加刚才新建的MediaType(writetodb)
ConfigurationàActions,新建Action(log error),Operation中设置Sendmessage给刚才新建的用户(writetodb),
Conditions中把日志的监视都填进去,其他的设置如报警的内容等请自行填写
到这里zabbix就设置完了。
2,mysql设置
新建数据库
Create database alert;
新建数据表nowalert
Create table nowalert ( Time varchar(), Title varchar() Value varchar() );
新建数据表passalert
Create table passalert like nowalert;
新建视图alertsum
Create view alertsum (Time, Title , Value, Count) as select Time, Title, Value, Count(*) from nowalert group by Value;
3,写入数据库的脚本
cd /usr/lib/zabbix/alertscripts/ vim writetodb.py
脚本内容
#!/usr/bin/python import sys import MySQLdb import datetime #捕捉zabbix传过来的参数2和3 subject = str(sys.argv[2]) body = str(sys.argv[3]) #定义时间以及格式 now = datetime.datetime.now() time = now.strftime("%Y.%m.%d %H:%M:%S") #以列表形式定义要插入数据表的内容 error = [] error.append(time) error.append(subject) error.append(body) #将error插入数据表 conn = MySQLdb.connect(host='localhost',user='zabbix',passwd='xxxxxx',port=3306,db='alert') cur = conn.cursor() try: cur.execute('insert into nowalert values(%s,%s,%s)',error) conn.commit() except conn.rollback() conn.close()
chmod +x writetodb.py
4,发邮件脚本
新建地址簿
mkdir addresslist vim addresslist /ServerTeam
to和cc之间用##隔开,多个邮箱之间用逗号隔开
aaa@xxx.com##bbb@xxx.com,ccc@xxx.com
发送邮件脚本(更新)
2016/12/9 :增加了邮件的retry(3次),增加了各个模块的日志记录,改善了代码结构
vim sendmail.py
#!/usr/bin/python #-*- coding:utf-8 -*- import MySQLdb import smtplib from email.mime.text import MIMEText from email.header import Header import logging import os import datetime LOGFILE = datetime.datetime.now().strftime('%Y-%m-%d')+'.log' LOGDIR = os.path.join(os.getcwd(),"log") logger = logging.getLogger() hdlr = logging.FileHandler(os.path.join(LOGDIR,LOGFILE),'a') formatter = logging.Formatter('%(asctime)s: %(process)d %(levelname)s %(message)s') hdlr.setFormatter(formatter) logger.addHandler(hdlr) logger.setLevel(logging.NOTSET) def mysql(sql): try: conn = MySQLdb.connect(host='localhost',user='zabbix',passwd='xxxxx',port=3306,db='alert') cur = conn.cursor() cur.execute(sql) results = cur.fetchall() cur.close() conn.commit() conn.close() except MySQLdb.Error as e: mysqlerror = "Mysql Error %d: %s" % (e.args[0], e.args[1]) logger.error(mysqlerror) return results def sendmail(def_title, def_to, def_cc, def_body): mail_user = "xxxxxx@xxxx" mail_pass = "xxxxxx" sender = 'xxxxxx@xxxx' msg = MIMEText(def_body, 'plain', 'utf-8') msg['Subject'] = Header(def_title, 'utf-8') msg['To'] = ','.join(def_to) if def_cc: msg['CC'] = ','.join(def_cc) reciver = def_to + def_cc smtp = smtplib.SMTP() attempts = 0 success = False while attempts < 3 and not success: try: smtp.connect('smtp.partner.outlook.cn') smtp.ehlo() smtp.starttls() smtp.ehlo() #smtp.set_debuglevel(1) smtp.login(mail_user, mail_pass) smtp.sendmail(sender, reciver, msg.as_string()) smtp.quit() success = True logger.info("Send Mail Successful") except: attempts += 1 logger.warn("Send Mail Failed, Retry") if attempts == 3: logger.error("Send Mail Failed For 3 Times") def address(addbook): f = open("/usr/lib/zabbix/alertscripts/addresslist/" + addbook,"r") line = f.readline().strip() toandcc = line.split('##') mail_to = toandcc[0].split(',') mail_cc = toandcc[1].split(',') f.close() return(mail_to, mail_cc) def main(): results = mysql('select Time, Title, Value, count from alertsum') if results: for row in results: time = row[0] title = row[1] value = row[2] count = row[3] mail_title = title + " 检测到" + str(count) + "次 从:" + time mail_subject = value mail_to, mail_cc = address("ServerTeam") sendmail(mail_title, mail_to, mail_cc, mail_subject) logger.info("Title:" + mail_title + "\nTo:" + ",".join(mail_to) + "\nCC:" + ",".join(mail_cc) + "\n" + mail_subject ) mysql('insert into passalert select * from nowalert') mysql('TRUNCATE TABLE nowalert') if __name__ == "__main__": main()
chmod +x sendmail.py
然后加到crontab,15分钟执行一次
crontab –e */ * * * * root python /usr/lib/zabbix/alertscripts/sendmail.py >> /usr/lib/zabbix/alertscripts /maillog.log >&
5,测试
手动写入日志
echo error >> /root/log.txt
打3次
echo anothererror >> /root/log.txt
打5次
在zabbix页面上看到报警触发后登入mysql
数据已经写入至nowalert
select * from nowalert; 略 rows in set (0.00 sec)
视图alertsum已经更新
select * from alertsum; 略 rows in set (0.00 sec)
手动执行送信脚本或者等crontab触发后会收到如下2封邮件
再次登入mysql查看数据表nowalert,发现已经被清空,数据已经移动至passalert表
mysql> select * from nowalert; Empty set (0.00 sec)
记录到的日志大概是这个样子的
2016-12-06 17:05:58,038: 14492 INFO Send Mail Successful 2016-12-06 17:05:58,038: 14492 INFO Title:<test>故障:Zabbix serverlogerr 检测到x次从:2016-12-06 17:05:00 To:xxxxx CC:yyyyy 邮件内容xxxxxxxxxxx
送信出错时还会响应的记录以下日志
2016-12-06 16:38:53,669: 14182 WARNING Send Mail Failed, Retry 2016-12-06 16:38:58,687: 14182 WARNING Send Mail Failed, Retry 2016-12-06 16:39:03,719: 14182 WARNING Send Mail Failed, Retry 2016-12-06 16:39:03,720: 14182 ERROR Send Mail Failed For 3 Time
多个log监视同时大量写入时的状况未经测试,不知道脚本是否能够承受住。
Zabbix日志监视的汇总报警(更新发送邮件脚本)的更多相关文章
- Zabbix日志错误总结(持续更新)
no active checks on server [*.*.*.*:10051]: host [*] not found failed to accept an incoming connecti ...
- zabbix使用之打造邮件报警
zabbix使用之打造邮件报警 前言: 报警信息很重要,它能使我们最快的知道故障内容,以便于及时处理问题.zabbix如果没配置报警功能,则完全不能体现zabbix的优势了 配置详情如下: 1.编写发 ...
- Asp.Net Core 轻松学-利用日志监视进行服务遥测
前言 在 Net Core 2.2 中,官方文档表示,对 EventListener 这个日志监视类的内容进行了扩充,同时赋予了跟踪 CoreCLR 事件的权限:通过跟踪 CoreCLR 事件 ...
- linux下日志文件error监控报警脚本分享
即对日志文件中的error进行监控,当日志文件中出现error关键字时,即可报警!(grep -i error 不区分大小写进行搜索"error"关键字,但是会将包含error大小 ...
- 使用jenkins中遇到的问题汇总/持续更新
jenkins产生大量日志文件 question: [DNSQuestion@1446063419 type: TYPE_IGNORE index 0, class: CLASS_UNKNOWN in ...
- zabbix学习笔记:zabbix监控之短信报警
zabbix学习笔记:zabbix监控之短信报警 zabbix的报警方式有多种,除了常见的邮件报警外,特殊情况下还需要设置短信报警和微信报警等额外方式.本篇文章向大家介绍短信报警. 短信报警设置 短信 ...
- KbmMW资源汇总(更新中…)
KbmMW框架是收费的,不在此提供下载,如需购买,请自行联系作者Kim Madsen. 网址资源: 官网主页:http://www.components4programmers.com/product ...
- 《WCF技术剖析》博文系列汇总[持续更新中]
原文:<WCF技术剖析>博文系列汇总[持续更新中] 近半年以来,一直忙于我的第一本WCF专著<WCF技术剖析(卷1)>的写作,一直无暇管理自己的Blog.在<WCF技术剖 ...
- Ubuntu16.04 + Zabbix 3.4.7 邮件报警设置
部署了Zabbix,需要配置邮件报警,在网上找了一些教程,大多是是用的CentOS + Zabbix 2.x版本的,而且还要写脚本,感觉太麻烦了,所以自己结合其他文章摸索了一套配置方法. 先说一下环境 ...
随机推荐
- Android内部自带的SQLite数据库操作dos命令
1:什么叫做SQLite数据库 Android系统内核是Linux系统,Android系统很特殊,他自带了一个SQLite数据库,轻量型的一款嵌入式的数据库 它占用资源非常的低,在嵌入式设备中,可能只 ...
- python学习之——django环境搭建
Django是一个基于MVC构造的框架,用于web开发,主要目的是简便.快速的开发数据库驱动的网站. 前提:已经安装python 搭建步骤: 1.https://www.djangoproject.c ...
- LVM增大和减小ext4、xfs分区
可以对ext4调整分区大小,能自动识别要增大还是减小 lvresize -L 300M -r /dev/vg/lvol0 原文地址http://www.361way.com/lvm-xfs-ext4/ ...
- 我 && yii2 (路由优化)
今天配置了一下yii2 的路由,用 /index.php?r=... 这样的路由,实在是不太习惯,所以我便试着把yii2 的路由,写成laravel 那般,以下为详情 1.环境介绍 lnmp php5 ...
- 使用jekyll在GitHub Pages上搭建个人博客【转】
网上有不少资源,但大多是“授人以鱼”,文中一步一步的告诉你怎么做,却没有解释为什么,以及他是如何知道的.他们默认着你知道种种专业名词的含义,默认着你掌握着特定技能.你折腾半天,查资料,看教程,一步步下 ...
- (转)selenuim-webdriver注解之@FindBy、@FindBys、@FindAll的区别
selenium-webdriver中获取页面元素的方式有很多,使用注解获取页面元素是其中一种途径, 方式有3种:@FindBy.@FindBys.@FindAll.下文对3中类型的区别和使用场景进行 ...
- 如此清除sql server 2008 记住的用户名
在C盘下搜索这个文件 SqlStudio.bin 搜索到后删除就可以,这样登录Sql server 时就不会有用户名密码之类的,相当于做了初始化操作,但里面的数据库什么的都是有的. 这只是个删除记住 ...
- 哈哈,修改PHP5.4.44语法成功
作为一个脚本语言,面向对象的继承基本上不想用到,强类型比较也想使用==直接比较.作为专业程序员不想让PHP解释器代劳过多. 修改了这个MOD版本,效果杠杠的.
- 安装CocoaPods碰到的问题
1.安装完Pods后第一次使用pod install命令提示"Setting up CocoaPods master repo" 解决办法: 第一次使用pod命令时,先执行以下po ...
- 关于springmvc的配置文件
开发常用的springmvc.xml配置文件,spring 3.0 spring-servlet.xml配置. <?xml version="1.0" encoding=&q ...