做了
Keepalived+Nginx
的高可用之后,接下来需要做的就是在主备服务器切换的发送通知邮件,这样我们才知道服务器宕机了。
1.测试环境
直接写一个脚本sendmail.pl
放在/etc/keepalived
中,然后每次出问题时,就调用这个脚本发送邮件。
脚本内容:
#!/usr/bin/perl -w
use Net::SMTP_auth;
use strict;
my $mailhost = 'smtp.163.com';
my $mailfrom = '发送邮件的邮箱名字@163.com';
my @mailto = ('接收邮件的邮箱名字@163.com');
my $subject = 'keepalived up on backup';
my $text = "正文\n 151服务器宕机!";
my $user = '发送邮件的邮箱名称.com';
my $passwd = '发送邮件的邮箱密码'; #注意是要填写163客户端授权的密码
&SendMail();
##############################
# Send notice mail
##############################
sub SendMail() {
my $smtp = Net::SMTP_auth->new( $mailhost, Timeout => 120, Debug => 1 )
or die "Error.\n";
$smtp->auth( 'LOGIN', $user, $passwd );
foreach my $mailto (@mailto) {
$smtp->mail($mailfrom);
$smtp->to($mailto);
$smtp->data();
$smtp->datasend("To: $mailto\n");
$smtp->datasend("From:$mailfrom\n");
$smtp->datasend("Subject: $subject\n");
$smtp->datasend("\n");
$smtp->datasend("$text\n\n");
$smtp->dataend();
}
$smtp->quit;
}
写完脚本之后,添加可执行权限
chmod 755 sendmail.pl
keepalived
配置文件修改内容,注:我把脚本放到了与配置文件同级目录下,添加一段:
! Configuration File for keepalived
#这里的邮件只能发送到本机
global_defs {
notification_email {
root@localhost
}
notification_email_from root@localhost
smtp_server 127.0.0.1
smtp_connect_timeout 30
router_id slave2
}
vrrp_script chk_nginx {
script "/etc/keepalived/ck_ng.sh"
interval 2
weight -5
fall 3
rise 2
}
vrrp_sync_group VG_1 {
group {
VI_1
}
#节点变为master时执行
notify_master /etc/keepalived/sendmail.pl
}
vrrp_instance VI_1 {
state MASTER
interface ens32
virtual_router_id 51
priority 100
advert_int 1
authentication {
auth_type PASS
auth_pass 1111
}
track_script {
chk_nginx
}
virtual_ipaddress {
59.68.29.15/24
}
}
可进入该脚本目录,直接执行脚本,看看是否发送邮件成功;若失败,安装Net::SMTP_auth模块 ,安装方法:
yum -y install perl-CPAN
> sudo perl -MCPAN -e shell
capn > install Net::SMTP_auth
![](https://img.haomeiwen.com/i2859254/775d2453b4924bf8.png)
注意事项
my $passwd = '发送邮件的邮箱密码'; #注意是要填写163客户端授权的密码
![](https://img.haomeiwen.com/i2859254/c0406456c7133565.png)
最后测试一下:
执行脚本./sendmail.pl
![](https://img.haomeiwen.com/i2859254/2ab906622b8efd1b.png)
![](https://img.haomeiwen.com/i2859254/0e55d0d33d54a6ae.png)
大功告成!
网友评论