定义通知脚本:
notify_master <STRING>|<QUOTED-STRING>:
当前节点成为主节点时触发的脚本
notify_backup <STRING>|<QUOTED-STRING>:
当前节点转为备节点时触发的脚本
notify_fault <STRING>|<QUOTED-STRING>:
当前节点转为“失败”状态时触发的脚本
notify <STRING>|<QUOTED-STRING>:
通用格式的通知触发机制,一个脚本可完成以上三种状态的转换时的通知
一、编写通知脚本
vim /etc/keepalived/notify.sh
存放位置,脚本名自定义
示例脚本如下:
#!/bin/bash
#
rpm -qi mail &>/dev/null || yum install mailx -y &>/dev/null
contact='root@localhost' notify() { mailsubject="$(hostname) to be $1, vip floating" mailbody="$(date +'%F %T'): vrrp transition, $(hostname) changed to be $1" echo "$mailbody" | mail -s "$mailsubject" $contact } case $1 in master) notify master ;; backup) notify backup ;; fault) notify fault ;; *) echo "Usage: $(basename $0) {master|backup|fault}" exit 1 ;; esac
二、添加执行权限
chmod +x /etc/keepalived/notify.sh
三、将这个脚本拷贝到其他keepalive服务器上
scp /etc/keepalived/notify.sh 192.168.1.8:/etc/keepalived/notify.sh
四、测试脚本
bash notify.sh backup
五、查看是否有收到邮件
2 root Wed May 26 01:39 19/678 "ka1 to be backup, vip floating" & 2 Message 2: From root@ka1.localdomain Wed May 26 01:39:38 2021 Return-Path: <root@ka1.localdomain> X-Original-To: root@localhost Delivered-To: root@localhost.localdomain Date: Wed, 26 May 2021 01:39:38 -0400 To: root@localhost.localdomain Subject: ka1 to be backup, vip floating User-Agent: Heirloom mailx 12.5 7/5/10 Content-Type: text/plain; charset=us-ascii From: root@ka1.localdomain (root) Status: RO 2021-05-26 01:39:38: vrrp transition, ka1 changed to be backup &
六、在配置文件中添加脚本
vim /etc/keepalived/keepalived.conf
1、在实例的最下面添加三行
notify_master "/etc/keepalived/notify.sh master" notify_backup "/etc/keepalived/notify.sh backup" notify_fault "/etc/keepalived/notify.sh fault"
解释:
notify_master "/etc/keepalived/notify.sh master"
master时触发notify.sh master
notify_backup "/etc/keepalived/notify.sh backup"
backup的时候触发notify.sh backup
notify_fault "/etc/keepalived/notify.sh fault"
fault (有故障)的时候触发fault
七、测试
1、查看主服务器的邮件
[02:20:29 root@ka1 keepalived]#mail Heirloom Mail version 12.5 7/5/10. Type ? for help. "/var/spool/mail/root": 3 messages > 1 root Wed May 26 01:33 19/678 "ka1 to be master, vip floating" 2 root Wed May 26 01:39 19/678 "ka1 to be backup, vip floating" 3 root Wed May 26 02:17 19/678 "ka1 to be master, vip floating" &
2、我这邮件太多了,为了看的清楚,就清空现有的邮件
rm -rf /var/spool/mail/root
3、直接杀掉keepalived进程
killall -9 keepalived
4、查看从服务器的邮件,这时候从服务器已经获取了IP地址了,
但测试下来发现,直接杀死进程,所有服务器都没有收到邮件,停止服务可以收到邮件