脚本实现有线网轮询检测插拔状态并分配ip

脚本代码:

#!/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

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值