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版本的,而且还要写脚本,感觉太麻烦了,所以自己结合其他文章摸索了一套配置方法. 先说一下环境 ...
随机推荐
- thinkpad e450 win7黑苹果macos 10.10.5(网/显/声卡驱动)安装成功
首先上图: 过程: 1.使用变色龙安装macos 10.10.5懒人版黑苹果 2.使用Haswell破解内核替换,成功进入系统 2.5.使用Hackintosh Vietnam Tool 1.9.6以 ...
- python学习笔记-多进程
multiprocessing from multiprocessing import Process import time def f(name): time.sleep(2) print('he ...
- mysql备份文件注释乱码处理工具
我们有时候需要做mysql数据库的注释,可是备份出来的是乱码,怎么办呢? 本工具软件来帮你的忙. 将GBK库备份后的文本文件中夹带的UTF8乱码转换为GBK编码,就不再乱码了. http://down ...
- Iscroll解析
做了一些移动端的产品,发现一些滚动效果很多会使用 iscroll 作为底层库(如阿里小蜜).iscroll 的文档已经好久没更新了,而且比较简单,经常需要直接读源码.这里写一篇总结,作为对 iscro ...
- RHEL7学习之crontab无法执行ntpdate
1,"/etc/crontab"文件 [root@localhost ~]# more /etc/crontab SHELL=/bin/bash PATH=/sbin:/bin:/ ...
- spring知识大全(3)
4 Spring对持久层的支持 Spring对持久层的支持:① JDBC,② O/R Mapping(Hibernate,TopLink等) 一.Spring对持久层支持采用的策略: 1.Spring ...
- tomcat使用线程池配置高并发连接
1:配置executor属性打开/conf/server.xml文件,在Connector之前配置一个线程池:[html] view plain copy<Executor name=" ...
- Linux添加/删除用户和用户组
声明:现大部分文章为寻找问题时在网上相互转载,在此博客中做个记录,方便自己也方便有类似问题的朋友,故原出处已不好查到,如有侵权,请发邮件表明文章和原出处地址,我一定在文章中注明.谢谢. 本文总结了Li ...
- Ubuntu Server安装R和Rstudio(zz)
Ubuntu Server安装R和Rstudio 发表于 技术天堂 2014-03-15 21:03 字数: 534 阅读量: 205 R是一个在科研领域很常用的工具,经常用R的年轻人或者经常上统计之 ...
- 一个书店管理系统java
自己的第一个小程序 ps:书是在集合里面后面文件处理的有一点小问题,希望有人会给点意见 //客户类 import java.io.Serializable; public class Customer ...