bash脚本把上下环路接口(Bash script to bring up and down an

2019-09-16 15:13发布

我使用Ubuntu服务器作为NAT路由器。 WAN接口是eth1和LAN接口eth0 。 我用ucarp虚拟IP局域网侧故障切换。 我写一个脚本这将拉低LAN接口eth0 ,如果WAN链路或默认网关出现故障(如LAN接口出现故障,则ucarp可以释放NAT网关IP到网络上的另一台路由器)。 此外,如果WAN IP被ping通,那么LAN接口应该拿出,并应继续,直到WAN IP可以Ping通。

bash脚本:

#!/bin/bash
t1=$(ifconfig | grep -o eth0)
t2="eth0"
#RMT_IP = "8.8.8.8"
SLEEP_TIME="10"

ping -c 2 8.8.8.8 > /dev/null
   PING_1=$?

if [ $PING_1 = 1 ]; then
    if [ "$t1" != "$t2" ]; then
        ifconfig eth0 up
        echo "Iface brought up"
    else
        echo "Iface is already up"
    fi
else
    if [ "$t1" = "$t2" ]; then
        ifconfig eth0 down
        echo "Iface brought down"
    else
        echo "iface already down"
    fi
fi

sleep $SLEEP_TIME

该脚本不会为我工作。 我想,如果一个WAN IP可以Ping通,则LAN接口eth0应该留起来。 如果WAN IP地址不能ping通,那么接口应该被放倒。 该脚本应该在循环中运行每隔10秒。 如果WAN IP地址不能被ping通了较长一段时间内,然后eth0应该留下来只有如果WAN IP获取一段时间后,ping通,然后eth0应该被提出来。 我还计划运行开机脚本作为一个暴发户的工作。

编辑1:我的最终脚本:

#!/bin/bash

timeout=5         # delay between checks
pingip='8.8.8.8'   # what to ping
iface="eth0"
LOG_FILE="/var/log/syslog"
isdown=0            # indicate whether the interface is up or down
                   # start assuming interface is up

while true; do
    LOG_TIME=`date +%b' '%d' '%T`
    if ping -q -c 2 "$pingip" >> /dev/null ; then      # ping is good - bring iface up
        if [ "$isdown" -ne 0 ] ; then
            ifup $iface && isdown=0
            printf "$LOG_TIME $0: Interface brought up: %s\n" "$iface" | tee -a $LOG_FILE
        fi
    else                                 # ping is bad - bring iface down
        beep -f 4000
        if [ "$isdown" -ne 1 ] ;  then
            ifdown $iface && isdown=1
            printf "$LOG_TIME $0: Interface brought down: %s\n" "$iface" | tee -a $LOG_FILE
        fi
    fi
    sleep "$timeout"
done

Answer 1:

试试这个
如果ping成功然后把$iface
如果Ping失败,然后把$iface下降

#!/bin/bash

timeout=3               # delay between checks
iface="eth0"            # which interface to bring up/down
pingip='8.8.8.8'        # what to ping
isdown=-1               # indicate whether the interface is up(0) or down(1)
                        # start in unknown state

while true; do
    if ping -q -c 2 "$pingip"; then       # if ping is succeeds bring iface up
        if [ "$isdown" -ne 0 ]; then      # if not already up
            ifconfig "$iface" up && isdown=0
            printf ":: iface brought up: %s\n" "$iface"
        fi
    elif [ "$isdown" -ne 1 ]; then        # if ping failed, bring iface down, if not already down
        ifconfig "$iface" down && isdown=1
        printf ":: iface brought down: %s\n" "$iface"
    fi
    sleep "$timeout"
done


文章来源: Bash script to bring up and down an interface on loop