本脚本适合单台lvs服务器时使用,使用keepalived是会自动检测状态,所以使用lvs+keepalived是不需要使用脚本检查realserver状态。
#!/bin/bash#VIP=192.168.3.22CPORT=80FAIL_BACK=127.0.0.1RS=("192.168.3.211" "192.168.3.215")#声明数组变量RSSTATUSdeclare -a RSSTATUSRW=("2" "1")RPORT=80TYPE=gCHKLOOP=3LOG=/var/log/ipvsmonitor.log#添加realserver函数addrs() { ipvsadm -a -t $VIP:$CPORT -r $1:$RPORT -$TYPE -w $2 [ $? -eq 0 ] && return 0 || return 1}#删除realserver函数delrs() { ipvsadm -d -t $VIP:$CPORT -r $1:$RPORT [ $? -eq 0 ] && return 0 || return 1}#检查realserver是否在线checkrs() { local I=1 while [ $I -le $CHKLOOP ]; do if curl --connect-timeout 1 http://$1 &> /dev/null; then return 0 fi let I++ done return 1}#检测ipvsadm配置中是否包含realserver服务器以及端口,如果存在就给数组赋值1 不存在就赋值为2initstatus() { local I local COUNT=0; for I in ${RS[*]}; do if ipvsadm -L -n | grep "$I:$RPORT" && > /dev/null ; then RSSTATUS[$COUNT]=1 else RSSTATUS[$COUNT]=0 fi let COUNT++ done}initstatuswhile :; do let COUNT=0 for I in ${RS[*]}; do if checkrs $I; then if [ ${RSSTATUS[$COUNT]} -eq 0 ]; then addrs $I ${RW[$COUNT]} [ $? -eq 0 ] && RSSTATUS[$COUNT]=1 && echo "`date +'%F %H:%M:%S'`, $I is back." >> $LOG echo "`date +'%F %H:%M:%S'`, $I is back."|sendmail -s "realserver is back" 403182580@qq.com fi else if [ ${RSSTATUS[$COUNT]} -eq 1 ]; then delrs $I [ $? -eq 0 ] && RSSTATUS[$COUNT]=0 && echo "`date +'%F %H:%M:%S'`, $I is gone." >> $LOG echo "`date +'%F %H:%M:%S'`, $I is gone."|sendmail -s "realserver is gone" 403182580@qq.com fi fi let COUNT++ done sleep 5done
本脚本检查到realserver未运行时,会自动从ipvsadm配置中踢出该服务器。如果realserver重新启用时会自动添加realserver到ipvsadm配置文件中。同时
如有疑问可联系QQ:403182580