脚本代码:
#!/bin/bash
flag0='0'
flag1='0'
check_ip() {
local interface="eth$1"
local flag="flag"
if ! ip link show "$interface" >/dev/null 2>&1; then
echo "Interface $interface does not exist!"
exit 1
fi
if ip link show "$interface" | grep -q "state UP"; then
echo "Interface $interface is connected"
if [ "$(eval echo \$$flag$1)" -eq 0 ]; then
ip link set dev "$interface" down
ip link set dev "$interface" up
udhcpc -i "$interface"
ifconfig "$interface" down
ifconfig "$interface" up
eval "$flag$1=1"
if [ "$interface" = "eth0" ]; then
ip route del default >/dev/null 2>&1
ip route flush dev eth1
ip route add default via 192.168.1.1 dev eth0
echo "eth0 has been set as the primary route"
elif [ "$interface" = "eth1" ]; then
ip route del default >/dev/null 2>&1
ip route flush dev eth0
ip route add default via 192.168.1.1 dev eth1
echo "eth0 has been set as the primary route"
else
echo "other netplan set as the primary route"
fi
echo "IP has been assigned"
fi
else
eval "$flag$1=0"
echo "Interface $interface does not exist"
fi
}
while true; do
check_ip "0"
check_ip "1"
sleep 5
done