0
点赞
收藏
分享

微信扫一扫

使用shell脚本实现网卡热备

回溯 2023-12-27 阅读 38

环境准备

主机

IP

Rocky_Linux(NFS)

192.168.3.1/24

Rocky_Linux(WEB)

192.168.3.2/24

实验场景

采取shell脚本监控的方式对链路进行监控,当一条链路出现故障时会关闭网卡将其切换到备用链路上。以此来保障nfs服务器与web服务器的连通性。

需要在客户端与服务器都运行此脚本来监控,并且备用网卡需要处于关闭状态,只有当被监控的网卡发生故障时才会启用备用网卡。(仅适用于两台主机都为Linux时)

配置NFS服务

1)创建共享目录

mkdir /opt/client
chmod 777 /opt/client/

使用shell脚本实现网卡热备_链路

2)配置nfs共享

vim /etc/exports
#rw表示客户端对目录可读写,sync表示以同步方式进行写操作
/opt/client 192.168.3.1/24(rw,sync)

使用shell脚本实现网卡热备_链路_02

3)启动nfs服务,加载共享目录配置

systemctl start nfs-server.service
exportfs -rv

使用shell脚本实现网卡热备_链路_03

4)在客户端验证服务

#安装nfs
dnf install nfs-utils
#挂载共享目录
mount 192.168.3.1:/opt/client /opt/client/

使用shell脚本实现网卡热备_共享目录_04

启动脚本监控网卡状态

#!/bin/bash
# **********************************************************
# * Author        : 青菜浪人
# * Create time   : 2023-10
# * Filename      : net.sh
# **********************************************************

eth1=$1
eth2=$2
if [ "$#" -eq 0 ];then
	echo -e "\033[35m\t请传入网卡名称参数 \
    \n\t例:bash xx.sh eth1 eth2 \033[0m"
	exit 1
else
	echo "successlly"
fi
function network(){
    nmcli c down ${eth1} >/dev/null 2>&1
    eth1_ip="192.168.3.1/24"
    if [ "$?" -eq 0 ];then
        nmcli connection modify ${eth2} ipv4.method manual ipv4.addresses ${eth1_ip}
        nmcli c reload
        nmcli c up ${eth2}
    else
        exit 0
    fi
}

function heartbeat(){
    nowtime=$(date +"%F %H:%M:%S")
    #设置对端IP
    eth1_dt="192.168.3.2"
    if ping -c1 -w1 ${eth1_dt} >/dev/null 2>&1 ;then
        echo "${nowtime}      Success" 
    else
        if ping -c1 -w1 ${eth2_dt} >/dev/null 2>&1 ;then
            echo "${nowtime}     success"	
        else
            echo "${nowtime}  ${eth1}该网卡故障,正在切换到备用线路。。。"
                	network
                if [ "$?" -eq 0 ];then
                        echo "${nowtime}   成功切换到${eth2},备用线路正常" #>eth2.log
                else
                         echo "备用线路异常,切换失败"
                         exit 1
                fi

		fi
    fi
}
while true
do
    heartbeat
    sleep 1
done

运行测试

关闭被监控的主网卡测试

此时会自动启用备用线路,保证传输正常

使用shell脚本实现网卡热备_共享目录_05

在web服务器的挂载目录中创建文件,测试与NFS服务器的连通状态

使用shell脚本实现网卡热备_链路_06

在nfs服务器上查看刚才创建的文件,链接状态正常

使用shell脚本实现网卡热备_共享目录_07

PS:个人观点,仅供参考。

举报

相关推荐

0 条评论