zabbix 报警方式之 邮件报警(4)

一、为什么要自定义邮件脚本报警?

  灵活,方便。可以自定义过滤信息。

  下面是使用不同方式的邮件报警,一个是利用sendEmail程序来发送报警邮件,第二个是利用python脚本来发送邮件。

二、sendEmail的部署步骤

  1.官方介绍:http://caspian.dotconf.net/menu/Software/SendEmail/

  2.先下载安装包到本地,解压。

[root@zabbix-6 ~]# wget -c http://caspian.dotconf.net/menu/Software/SendEmail/sendEmail-v1.56.tar.gz
[root@zabbix-6 ~]# tar zxf sendEmail-v1.56.tar.gz
[root@zabbix-6 ~]# cd sendEmail-v1.56
[root@zabbix-6 sendEmail-v1.56]# cp -a sendEmail /usr/local/bin/
[root@zabbix-6 sendEmail-v1.56]# chmod +x /usr/local/bin/sendEmail
[root@zabbix-6 sendEmail-v1.56]# file /usr/local/bin/sendEmail
/usr/local/bin/sendEmail: a /usr/bin/perl -w script text executable

  3.看下sendemail命令的帮助信息

[root@zabbix-6 sendEmail-v1.56]# /usr/local/bin/sendEmail 

sendEmail-1.56 by Brandon Zehm <caspian@dotconf.net>

Synopsis:  sendEmail -f ADDRESS [options]

  Required:
    -f ADDRESS                from (sender) email address
    * At least one recipient required via -t, -cc, or -bcc
    * Message body required via -m, STDIN, or -o message-file=FILE

  Common:
    -t ADDRESS [ADDR ...]     to email address(es)
    -u SUBJECT                message subject
    -m MESSAGE                message body
    -s SERVER[:PORT]          smtp mail relay, default is localhost:25

  Optional:
    -a   FILE [FILE ...]      file attachment(s)
    -cc  ADDRESS [ADDR ...]   cc  email address(es)
    -bcc ADDRESS [ADDR ...]   bcc email address(es)
    -xu  USERNAME             username for SMTP authentication
    -xp  PASSWORD             password for SMTP authentication

  Paranormal:
    -b BINDADDR[:PORT]        local host bind address
    -l LOGFILE                log to the specified file
    -v                        verbosity, use multiple times for greater effect
    -q                        be quiet (i.e. no STDOUT output)
    -o NAME=VALUE             advanced options, for details try: --help misc
        -o message-content-type=<auto|text|html>
        -o message-file=FILE         -o message-format=raw
        -o message-header=HEADER     -o message-charset=CHARSET
        -o reply-to=ADDRESS          -o timeout=SECONDS
        -o username=USERNAME         -o password=PASSWORD
        -o tls=<auto|yes|no>         -o fqdn=FQDN


  Help:
    --help                    the helpful overview you're reading now
    --help addressing         explain addressing and related options
    --help message            explain message body input and related options
    --help networking         explain -s, -b, etc
    --help output             explain logging and other output options
    --help misc               explain -o options, TLS, SMTP auth, and more

  4.安装下依赖

[root@zabbix-6 sendEmail-v1.56]# yum install perl-Net-SSLeay perl-IO-Socket-SSL -y

  5.简单的报警脚本,脚本来自群内一位大神:@东南:http://ywwd.net/read-866

[root@zabbix-6 sendEmail-v1.56]# cd /usr/lib/zabbix/alertscripts/
[root@zabbix-6 alertscripts]# cat mail.sh 
#!/bin/bash

To=$1
Subject=$2
Body=$3

/usr/local/bin/sendEmail -f [发送者地址] -t "$To" -s [你的smtp服务器地址] -u "$Subject" -xu [smtp验证登陆名] -xp [你的邮箱密码] -m "$Body"
 2>&1 >>/var/log/sendEmail.lo

  编辑完成后,给脚本权限

[root@zabbix-6 alertscripts]# chmod +x mail.sh
[root@zabbix-6 alertscripts]# chown zabbix.zabbix /var/log/sendEmail.log
[root@zabbix-6 alertscripts]# chown zabbix.zabbix mail.sh

  6.脚本编辑好后,在zabbix 登陆界面进行设置。

    注意:zabbix 3.0 需要在为alert脚本定义参数,以前的版本参数都固定的,现在用户可以自己定义命令行的参数了。添加的参数也就是脚本中的$1、$2、$3等。

添加方法:Administration-->Media types,增加如下参数
   添加媒介:


  添加完成后,需要关联到报警用户Administration-->Users-->Media-->add

  添加动作,触发条件后报警后发送邮件。Configuration-->Actions-Event source(Triggers)-Create action-

设置了60秒,接收消息组,接受消息用户,以及报警介质。

模拟下,把其中一个zabbix-agent 服务关掉

 

三、第二种报警方式直接利用python脚本   脚本出自ITnihao:https://github.com/itnihao/zabbix-book

 

#!/usr/bin/python 
#coding:utf-8 
#author: itnihao
#mail: itnihao@qq.com
#url: https://github.com/itnihao/zabbix-book/edit/master/06-chapter/zabbix_sendmail.py

import smtplib
from email.mime.text import MIMEText
import os
import argparse
import logging
import datetime

mail_host = 'smtp服务器'
mail_user = '账号'
mail_pass = '密码'
mail_postfix = '邮局'


def send_mail(mail_to,subject,content):
    me = mail_user+"<"+mail_user+"@"+mail_postfix+">"
    msg = MIMEText(content)
    msg['Subject'] = subject
    msg['From'] = me
    msg['to'] = mail_to
    global sendstatus
    global senderr

    try:
        smtp = smtplib.SMTP()
        smtp.connect(mail_host)
        smtp.login(mail_user,mail_pass)
        smtp.sendmail(me,mail_to,msg.as_string())
        smtp.close()
        print 'send ok'
        sendstatus = True
    except Exception,e:
        senderr=str(e)
        print senderr
        sendstatus = False

def logwrite(sendstatus,mail_to,content):
    logpath='/var/log/zabbix/alert'

    if not sendstatus:
        content = senderr

    if not os.path.isdir(logpath):
        os.makedirs(logpath)

    t=datetime.datetime.now()
    daytime=t.strftime('%Y-%m-%d')
    daylogfile=logpath+'/'+str(daytime)+'.log'
    logging.basicConfig(filename=daylogfile,level=logging.DEBUG)
    os.system('chown zabbix.zabbix {0}'.format(daylogfile))
    logging.info('*'*130)
    logging.debug(str(t)+' mail send to {0},content is :\n {1}'.format(mail_to,content))


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='Send mail to user for zabbix alerting')
    parser.add_argument('mail_to',action="store", help='The address of the E-mail that send to user ')
    parser.add_argument('subject',action="store", help='The subject of the E-mail')
    parser.add_argument('content',action="store", help='The content of the E-mail')
    args = parser.parse_args()
    mail_to=args.mail_to
    subject=args.subject
    content=args.content

    send_mail(mail_to,subject,content)
    logwrite(sendstatus,mail_to,content)

  将脚本放在/usr/lib/zabbix/alertscripts目录下。并赋予执行权限,属主改为zabbix,之后添加媒介,关联动作,和上面添加步骤基本一样。

本文章属于本作者原创,遵循开源协议,如有转载,请注明本链接的源地址。谢谢    继续更新中!!

posted @ 2016-04-08 10:07  飞走不可  阅读(2866)  评论(0编辑  收藏  举报