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
6,接下去要解决的课题

多个log监视同时大量写入时的状况未经测试,不知道脚本是否能够承受住。

Zabbix日志监视的汇总报警(更新发送邮件脚本)的更多相关文章

  1. Zabbix日志错误总结(持续更新)

    no active checks on server [*.*.*.*:10051]: host [*] not found failed to accept an incoming connecti ...

  2. zabbix使用之打造邮件报警

    zabbix使用之打造邮件报警 前言: 报警信息很重要,它能使我们最快的知道故障内容,以便于及时处理问题.zabbix如果没配置报警功能,则完全不能体现zabbix的优势了 配置详情如下: 1.编写发 ...

  3. Asp.Net Core 轻松学-利用日志监视进行服务遥测

    前言     在 Net Core 2.2 中,官方文档表示,对 EventListener 这个日志监视类的内容进行了扩充,同时赋予了跟踪 CoreCLR 事件的权限:通过跟踪 CoreCLR 事件 ...

  4. linux下日志文件error监控报警脚本分享

    即对日志文件中的error进行监控,当日志文件中出现error关键字时,即可报警!(grep -i error 不区分大小写进行搜索"error"关键字,但是会将包含error大小 ...

  5. 使用jenkins中遇到的问题汇总/持续更新

    jenkins产生大量日志文件 question: [DNSQuestion@1446063419 type: TYPE_IGNORE index 0, class: CLASS_UNKNOWN in ...

  6. zabbix学习笔记:zabbix监控之短信报警

    zabbix学习笔记:zabbix监控之短信报警 zabbix的报警方式有多种,除了常见的邮件报警外,特殊情况下还需要设置短信报警和微信报警等额外方式.本篇文章向大家介绍短信报警. 短信报警设置 短信 ...

  7. KbmMW资源汇总(更新中…)

    KbmMW框架是收费的,不在此提供下载,如需购买,请自行联系作者Kim Madsen. 网址资源: 官网主页:http://www.components4programmers.com/product ...

  8. 《WCF技术剖析》博文系列汇总[持续更新中]

    原文:<WCF技术剖析>博文系列汇总[持续更新中] 近半年以来,一直忙于我的第一本WCF专著<WCF技术剖析(卷1)>的写作,一直无暇管理自己的Blog.在<WCF技术剖 ...

  9. Ubuntu16.04 + Zabbix 3.4.7 邮件报警设置

    部署了Zabbix,需要配置邮件报警,在网上找了一些教程,大多是是用的CentOS + Zabbix 2.x版本的,而且还要写脚本,感觉太麻烦了,所以自己结合其他文章摸索了一套配置方法. 先说一下环境 ...

随机推荐

  1. MVc Forms Membership rolemanage 角色权限验证管理

    Forms  登录验证Membership 权限验证rolemanage 角色管理 以往的项目中只有单纯的Forms 验证今天想把这三个结合到mvc 中发现要导入aspnet_ 相关表,但是有个问题验 ...

  2. 有趣的代码: fixTypeof

    typeof 可以匹配对象的类型,但是他的能力很弱,比如 typeof new String('123')会显示的object这是我们不想看到的结果很久以前JQ的作者通过Object.prototyp ...

  3. NOIP2016普及组

    普及组.代码有空发. 第一题就是买铅笔.暴力模拟绝对可取. 第二题就是回文日期.从t1的年份到t2的年份枚举每一年.头尾要特判. 第三题就是海港.骗了40分. 第四题就是魔法阵.不太好优化. 完.

  4. 搭建调用 WebService 的 ASP.NET 网站 (VS2010, C#)

    [系统环境]Windows 7 / 2008r2 [软件环境]Visual Studio 2010 [开发语言]C# [感谢]本文是在 <C#开发和调用Web Service> 一文的基础 ...

  5. Jquery一般操作归纳

    一.DOM操作分类    1.DOM Core  getElement(s)获得元素        2.HTML-DOM  document.对象/操作标签的属性        3.CSS-DOM   ...

  6. ADV数字的剪切

    #include <iostream> using namespace std; #define SIZE 9 #define MAXLEN 6 int data[SIZE][MAXLEN ...

  7. Springmvc mybatis

    http://www.icoolxue.com/album/show/216 07

  8. 移动端HTML5<video>视频播放优化实践[转]

    http://blog.csdn.net/u010918416/article/details/52705732 http://www.xuanfengge.com/html5-video-play. ...

  9. 1075 PAT Judge (25)

    排序题 #include <stdio.h> #include <string.h> #include <iostream> #include <algori ...

  10. ros学习笔记 - 深度传感器转换成激光数据(hector_slam)

    前提条件:1,确保读者已经安装了kinect或者其他深度摄像头的驱动,如果未安装,可以直接在网盘下载:http://pan.baidu.com/s/1hqHB10w 提取密码:wrmn 利用深度相机仿 ...