Chinaunix首页 | 论坛 | 博客
  • 博客访问: 404502
  • 博文数量: 80
  • 博客积分: 8021
  • 博客等级: 中将
  • 技术积分: 1075
  • 用 户 组: 普通用户
  • 注册时间: 2007-09-08 10:36
文章分类

全部博文(80)

文章存档

2010年(3)

2009年(25)

2008年(52)

我的朋友

分类: LINUX

2008-04-19 15:22:50

    我在http://blog.chinaunix.net/u/12479/showart_397897.html这篇文章中提到了在本机没有启动SMTP服务器的情况下nagios可以通过Mail-Sender发送邮件。
    经过实践,我又找到了其他两种方法:
一、安装SSMTP软件
    安装SSMTP需要卸载其它的MTA程序,如postfix等。我用的是Gentoo,可以很容易的安装它:emerge ssmtp,其它linux发行版可参考相关文档。安装完成后需要删除系统自带的sendmail程序,可以使用which sendmail找到并删除它,然后:
#ln -s /usr/sbin/ssmtp /usr/sbin/sendmail (这里是sendmail原来的路径)
修改修改几个参数/etc/ssmtp/ssmtp.conf:
mailhub=IP (SMTP服务器的地址,域名或IP)
rewriteDomain=(本地域)
hostname=本地主机名
FromLineOverride=YES(使用mail命令中from覆盖默认的发件人地址)
其它参数可参考文档。
系统自带的mail命令在发送邮件是会自动使用ssmtp来发送邮件。
nagios可以不用修改任何设置。

二、使用NET::SMTP
   第二种方法虽然简单,但是由于不能在邮件头中加入类似"Content-Type: text/plain; charset=utf-8”的邮件头,因为字符串中的;将被nagios当作注释而不被处理。应用场景是这样的,我用webinject通过匹配中文关键字来检测网站的健康情况(关于如何使用webinject支持中文的方法我的博客中已有说明http://blog.chinaunix.net/u/12479/showart_537996.html),中文是UTF-8编码,使用mail命令发送邮件时需要添加邮件头:Content-Type: text/plain; charset=utf-8,这样才能被邮件客户端正常解码,否则看到的中文是乱码。但是在nagios中定义命令时不能使用;号,否者被作为注释。因此迫不得已我自己又写了一个发送邮件的perl程序,以下是代码mail.pl:
#!/usr/bin/perl

use Getopt::Std;
use Net::SMTP;

#f:mail from    s:subject   t:rcpt to
Getopt::Std::getopts('f:s:t:', \%options);

my $from = $options{f};
my $subject = $options{s};
my $to = $options{t};

while (defined($line = )) {
        $content .= $line;
}

open(LOG,">>/var/log/notify.log");

$smtp = Net::SMTP->new('mailserver')
  
      $smtp->mail($from); 
      $smtp->to($to); 


      $smtp->data(); 
      $smtp->datasend("To: $to\n"); 
      $smtp->datasend("Subject: $subject\n");
      $smtp->datasend("Content-Type: text/plain; charset=utf-8\n");
      $smtp->datasend("\n"); 
      $smtp->datasend("$content\n"); 
      $smtp->dataend(); 
      $smtp->quit;  

my $date_command = "/bin/date";
my $date = `$date_command`; chop($date);
print LOG "$date: Sent Msg $content to $to\n";
close(LOG);
exit(0);

然后修改nagios的配置文件/etc/nagios/misccommands.cfg
define command{
        command_name    notify-by-email
        command_line    /usr/bin/printf "%b" "$LONGDATETIME$ Info: $SERVICEOUTPUT$" | /usr/local/nagios/bin/mail.pl -f "mail from addr" -s "$TIME$ $SERVICEDESC$ on $HOSTNAME$ is $SERVICESTATE$!" -t $CONTACTEMAIL$
        }
将联系人的service_notification_commands改成notify-by-email即可,自己可定义主机notify命令来对应联系人的host_notification_commands
然后重新启动nagios

阅读(1915) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~