linux双机热备脚本

多年前帮同事写的一个双机设备的shell脚本,在中标麒麟7.4上测试过,现在看来,有些语句写的傻傻的,我也不改了,抛砖引玉吧,话不多说,代码如下:

#!/bin/bash
function standby {
echo "$(date "+%Y-%m-%d %H:%M:%S") Standby"
while true
do
#检查网关状态
ping -c1 $gateway &>/dev/null
a=$?
#检查业务主机状态
ping -c1 $ip &>/dev/null
b=$?
#如果网络通,且业务主机不在线,切换为主机模式
if [ $a -eq 0 ] && [ $b -ne 0 ];then
master
break
fi
done
}
function master {
echo "$(date "+%Y-%m-%d %H:%M:%S") Master"
#确认业务主机是否在线
ping -c1 $ip &>/dev/null
#如果业务主机不在线,自己配成业务主机的IP,提供服务,如果业务主机在线,老老实实继续回去当备机
if [ $? -ne 0 ];then
ifconfig $eth $ip netmask $mask
else standby
fi
while true
do
#主机监控自身网络状态和和业务端口是否正常,如任意一个不通,释放业务IP,切换为备机
ping -c1 $gateway &>/dev/null
a=$?
nc -w 1 127.0.0.1 $port &>/dev/null
b=$?
if [ $((a+b)) -ne 0 ];then
echo "$(date "+%Y-%m-%d %H:%M:%S") Error"
ifconfig $eth $local netmask $mask
sleep 20
standby
break
fi
sleep 1
done
}
echo "Initializing"
#业务主机的IP
ip = 192.168.1.100
gateway = 192.168.1.1
mask = 255.255.255.0
#本机IP
local = 192.168.1.111
#监控业务端口
port = 22
#网卡设备名
eth = eth0
service network restart &>/dev/null
while true
do
ping -c1 $gateway &>/dev/null
#检测网络,如果到网关通则继续执行,不通就一直ping
if [ $? -eq 0 ];then
#网络通,默认进入备机模式
standby
break
fi
sleep 1
done

在两台虚拟机上跑代码测试,切换时间大概是3秒,稍微有点慢。此脚本只能用于一主一备的场景。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

weixin_57319390

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值