#!/bin/sh
# Describe:check the real server status
# History:2015-08-25 22:21:38
# Author:Tim
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH
VIP=192.168.1.121
DIP=192.168.1.112
RIP=("192.168.1.122" "192.168.1.123")
VPORT=80
STATUS=(0 0)
TYPE=g
SCHEMA=rr
WEIGHT=(1 3)
let COUNT=0
#初始化realserver状态
initstats() {
local I
for I in `seq 0 1`;do
if ipvsadm -L -n |grep ${RIP[$I]} &>/dev/null ;then
STATUS[$I]=1
else
STATUS[$I]=0
fi
done
}
#添加realserver
add() {
ipvsadm -a -t $VIP:$VPORT -r ${RIP[$1]} -$TYPE -w ${WEIGHT[$1]}
[ $? -eq 0 ] && return 0 || return 1
}
#删除realserver
del() {
ipvsadm -d -t $VIP:$VPORT -r ${RIP[$1]}
[ $? -eq 0 ] && return 0 || return 1
}
#检测realserver状态,也可以考虑使用上述initstats方式
check() {
if curl --connect-timeout 1 http://$1 &>/dev/null;then
return 0
else
return 1
fi
}
initstats
while :;do
for N in `seq 0 1`;do
if check ${RIP[$N]} ;then
if [ ${STATUS[$N]} -eq 0 ] ;then
add $N &&STATUS[$N]=1 && echo "`date +%F-%T` , ${RIP[$N]} is back">>/var/log/ipvs
fi
else
if [ ${STATUS[$N]} -eq 1 ];then
del $N &&STATUS[$N]=0 &&echo "`date +%F-%T`, ${RIP[$N]} is gone" >>/var/log/ipvs
fi
fi
done
if [ ${STATUS[0]} -eq 0 -a ${STATUS[1]} -eq 0 ] ;then
ipvsadm -a -t $VIP:$VPORT -r $DIP -$TYPE
else
ipvsadm -d -t $VIP:$VPORT -r $DIP &>/dev/null
fi
sleep 5
done
注:此脚本是学习马哥linux视频教程时编写。