Search

Linux default gateway failover

I have an “unreliable” (I sometimes just take it with me) mifi box with fast LTE connection, shared to internal network via separate gateway, and a reliable but slow ADSL connection. I use the following script to switch to the slower connection when the default one is not working and automatically switch back when possible. It’s run by cron every minute on multiple devices.

#!/bin/bash
 
#*********************************************************************
#       Configuration
#*********************************************************************
DEF_GATEWAY="192.168.1.21"      # Default Gateway
BCK_GATEWAY="192.168.1.1"       # Backup Gateway
RMT_IP_1="193.166.3.2"          # first remote ip
RMT_IP_2="8.8.8.8"              # second remote ip
PING_TIMEOUT="1"                # Ping timeout in seconds
#*********************************************************************
 
# check user
if [ `whoami` != "root" ]
then
        echo "Failover script must be run as root!"
        exit 1
fi
 
#Check GW
CURRENT_GW=`ip route show | grep default | awk '{ print $3 }'`
if [ "$CURRENT_GW" == "$DEF_GATEWAY" ]
then
        ping -c 2 -W $PING_TIMEOUT $RMT_IP_1 > /dev/null
        PING_1=$?
        ping -c 2 -W $PING_TIMEOUT $RMT_IP_2 > /dev/null
        PING_2=$?
else
        # add static routes to remote ip's
        ip route add $RMT_IP_1 via $DEF_GATEWAY
        ip route add $RMT_IP_2 via $DEF_GATEWAY
        ping -c 2 -W $PING_TIMEOUT $RMT_IP_1 > /dev/null
        PING_1=$?
        ping -c 2 -W $PING_TIMEOUT $RMT_IP_2 > /dev/null
        PING_2=$?
        # del static route to remote ip's
        ip route del $RMT_IP_1
        ip route del $RMT_IP_2
fi
 
LOG_TIME=`date +%b' '%d' '%T`
 
if [ "$PING_1" == "1" ] && [ "$PING_2" == "1" ]
then
        if [ "$CURRENT_GW" == "$DEF_GATEWAY" ]
        then
                ip route del default
                ip route add default via $BCK_GATEWAY
                # flushing routing cache
                ip route flush cache
                echo "$LOG_TIME: $0 - switched Gateway to Backup with IP $BCK_GATEWAY"
        fi
 
elif [ "$CURRENT_GW" != "$DEF_GATEWAY" ]
then
        # switching to default
        ip route del default
        ip route add default via $DEF_GATEWAY
        ip route flush cache
        echo "$LOG_TIME: $0 - Gateway switched to Default with IP $DEF_GATEWAY"
fi