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. Android开发学习---使用XmlPullParser解析xml文件

    Android中解析XML的方式主要有三种:sax,dom和pull关于其内容可参考:http://blog.csdn.net/liuhe688/article/details/6415593 本文将 ...

  2. shadow Dom(shadowRoot) 访问

    示例 gtx.shadowRoot.getElementById("translation") gtx为host对象 起因 抓去chorome谷歌翻译插架的内容.有信息的内容div ...

  3. 【python】将一个正整数分解质因数

    def reduceNum(n): '''题目:将一个正整数分解质因数.例如:输入90,打印出90=2*3*3*5''' print '{} = '.format(n), : print 'Pleas ...

  4. MySQL 性能优化的最佳20多条经验分享

    当我们去设计数据库表结构,对操作数据库时(尤其是查表时的SQL语句),我们都需要注意数据操作的性能.这里,我们不会讲过多的SQL语句的优化,而只是针对MySQL这一Web应用最多的数据库.希望下面的这 ...

  5. iOS:xCode7版本运行xCode8.0的代码

    怎么在xCode7版本上运行xCode8.0的代码? 1.右键你的"LaunchScreen.sb"文件并用编辑器打开sb 2.删掉"<capability nam ...

  6. AJAX应用优势

    国内翻译(仅音译)常为 “阿贾克斯” 和阿贾克斯足球队同音. 使用ajax 构建应用程序 这个术语源自描述从基于 Web 的应用到基于数据的应用的转换.在基于数据的应用中,用户需求的数据如联系人列表, ...

  7. 遇到的sql关键字

    select count(1)  相当于  select count(*)  网上有比较差别的 菜鸟不用管

  8. 关于json解析中 解析多重json对象

    JSONObject rst = {"AIS-RST":"AIS-00000001","AIS-STATUS":"AIS-0000 ...

  9. 国内首个微信小程序开发者社区www.mntuku.cn

    微信小程序开发者社区-微信小程序开发教程-微信小程序最新资讯 - www.mntuku.cn .本站作为专业的微信小程序开发者社区为大家提供:微信小程序开发者交流平台,微信小程序开发教程,微信小程序定 ...

  10. mysql数据表操作&库操作

    首先登陆mysql:mysql -uroot -proot -P3306 -h127.0.0.1 查看所有的库:show databases; 进入一个库:use database; 显示所在的库:s ...