#!/bin/bash
# # Linux default gateway failover script [route via lan]# @author CsHeng 2020.06.11# ref: https://blog.rapellys.biz/2014/10/18/linux-default-gateway-failover-script/# #*********************************************************************# Configuration#*********************************************************************DEF_GATEWAY="172.16.2.1"# Default GatewayBCK_GATEWAY="172.16.2.2"# Backup GatewaySUBNET="default"# ip route destination subnetRMT_IP_1="119.29.29.29"# first remote ipRMT_IP_2="223.5.5.5"# second remote ipPING_TIMEOUT="1"# Ping timeout in seconds#*********************************************************************# fail fastset -e
# check userif[`whoami` !="root"]thenecho"Failover script must be run as root!"exit1fi#Check GWCURRENT_GW=`ip route show | grep $SUBNET| head -n 1| awk '{print $3}'`PING_NIC=`ip route show | grep $SUBNET| head -n 1| awk '{print $5}'`# ping network interfaceif["$CURRENT_GW"=="$DEF_GATEWAY"]then ping -4 -I $PING_NIC -c 2 -W $PING_TIMEOUT$RMT_IP_1 > /dev/null
PING_1=$? ping -4 -I $PING_NIC -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 -4 -I $PING_NIC -c 2 -W $PING_TIMEOUT$RMT_IP_1 > /dev/null
PING_1=$? ping -4 -I $PING_NIC -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_2fiLOG_TIME=`date +%b' '%d' '%T`# both ping failif["$PING_1"=="1"]&&["$PING_2"=="1"]thenif["$CURRENT_GW"=="$DEF_GATEWAY"]then ip route del $SUBNET ip route add $SUBNET via $BCK_GATEWAY# flushing routing cache ip route flush cache
echo"$LOG_TIME: $0 - Switched $SUBNET gateway to default with IP $BCK_GATEWAY"fielif["$CURRENT_GW" !="$DEF_GATEWAY"]then# switching to default ip route del $SUBNET ip route add $SUBNET via $DEF_GATEWAY ip route flush cache
echo"$LOG_TIME: $0 - Switched $SUBNET gateway to default with IP $DEF_GATEWAY"fi