-
-
Save HenryNe/61b3181bd88952435d35abaa25b0cbee to your computer and use it in GitHub Desktop.
An example failover script for dual WAN, using a ping healthcheck and managing default routes appropriately
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# | |
# Based on https://gist.github.com/Apsu/5021255 with two network interfaces, | |
# gateways can conneted on different network interfaces or in same network. | |
# Set defaults if not provided by environment | |
CHECK_DELAY=${CHECK_DELAY:-5} | |
CHECK_LOOPS=${CHECK_LOOPS:-3} | |
CHECK_IP=${CHECK_IP:-8.8.8.8} | |
PRIMARY_GW=${PRIMARY_GW:-192.168.0.1} | |
BACKUP_GW=${BACKUP_GW:-192.168.0.2} | |
# Compare arg with current default gateway address | |
gateway_ip() { | |
[[ "$1" = "$(ip route list | sed -rn 's/^default.*via ([^ ]*).*$/\1/p')" ]] | |
} | |
trap "logger -t failover 'Terminated'; route del -host $CHECK_IP gw $PRIMARY_GW" INT TERM | |
logger -t failover "Started with route to `ip route get $INTERNET_IP | sed -rn 's/^.*via ([^ ]*).*$/\1/p'`" | |
# Setup host route to continuous check primary gateway | |
# Ignore error, if route always set | |
route add -host $CHECK_IP gw $PRIMARY_GW | |
# Cycle healthcheck continuously with specified delay | |
while sleep $CHECK_DELAY | |
do | |
# If healthcheck succeeds from primary interface | |
if ping -c 1 $CHECK_IP &>/dev/null | |
then | |
# Are we using the primary? | |
if gateway_ip $PRIMARY_GW | |
then | |
LOOP=0 | |
else | |
LOOP=$(( $LOOP + 1 )) | |
logger -t failover "Ping to $CHECK_IP via $PRIMARY_GW is good ($LOOP/$CHECK_LOOPS)" | |
if [[ $LOOP -ge $CHECK_LOOPS ]] | |
then # Switch to primary | |
logger -t failover "Switch to primary gateway $PRIMARY_GW" | |
ip route del default via $BACKUP_GW | |
ip route add default via $PRIMARY_GW | |
fi | |
fi | |
else | |
# Are we using the backup? | |
if gateway_ip $BACKUP_GW | |
then | |
LOOP=0 | |
else | |
LOOP=$(( $LOOP + 1 )) | |
logger -t failover "Ping to $CHECK_IP via $PRIMARY_GW failed ($LOOP/$CHECK_LOOPS)" | |
if [[ $LOOP -ge $CHECK_LOOPS ]] | |
then # Switch to backup | |
logger -t failover "Switch to backup gateway $BACKUP_GW" | |
ip route del default via $PRIMARY_GW | |
ip route add default via $BACKUP_GW | |
fi | |
fi | |
fi | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment