Skip to content

Instantly share code, notes, and snippets.

@Apsu Apsu/failover.sh
Last active Jan 28, 2020

Embed
What would you like to do?
An example failover script for dual WAN, using a ping healthcheck and managing default routes appropriately
#!/bin/bash
# Set defaults if not provided by environment
CHECK_DELAY=${CHECK_DELAY:-5}
CHECK_IP=${CHECK_IP:-8.8.8.8}
PRIMARY_IF=${PRIMARY_IF:-eth0}
PRIMARY_GW=${PRIMARY_GW:-1.2.3.4}
BACKUP_IF=${BACKUP_IF:-eth1}
BACKUP_GW=${BACKUP_GW:-2.3.4.5}
# Compare arg with current default gateway interface for route to healthcheck IP
gateway_if() {
[[ "$1" = "$(ip r g "$CHECK_IP" | sed -rn 's/^.*dev ([^ ]*).*$/\1/p')" ]]
}
# Cycle healthcheck continuously with specified delay
while sleep "$CHECK_DELAY"
do
# If healthcheck succeeds from primary interface
if ping -I "$PRIMARY_IF" -c1 "$CHECK_IP" &>/dev/null
then
# Are we using the backup?
if gateway_if "$BACKUP_IF"
then # Switch to primary
ip r d default via "$BACKUP_GW" dev "$BACKUP_IF"
ip r a default via "$PRIMARY_GW" dev "$PRIMARY_IF"
fi
else
# Are we using the primary?
if gateway_if "$PRIMARY_IF"
then # Switch to backup
ip r d default via "$PRIMARY_GW" dev "$PRIMARY_IF"
ip r a default via "$BACKUP_GW" dev "$BACKUP_IF"
fi
fi
done
@csitech

This comment has been minimized.

Copy link

csitech commented Mar 22, 2017

Very nice article. Thanks for this.
We apply your script in ours servers and it works perfectly.

@philip-dakno

This comment has been minimized.

Copy link

philip-dakno commented Jul 2, 2018

Should [[ "$1" = "$(ip r g "$CHECK_IP" | sed -rn 's/^.*dev ([^ ]*).*$/\1/p')" ]] be [[ "$1" == "$(ip r g "$CHECK_IP" | sed -rn 's/^.*dev ([^ ]*).*$/\1/p')" ]]

@dushyantbangal

This comment has been minimized.

Copy link

dushyantbangal commented Jul 20, 2018

If the primary network is disconnected, it fails at ip r d default via "$PRIMARY_GW" dev "$PRIMARY_IF" saying
RTNETLINK answers: Network is unreachable.

How can I make it go ahead with the next command that adds the backup as the default?

@stikkx

This comment has been minimized.

Copy link

stikkx commented Dec 4, 2018

i have a little problem. If i disconnect the primary network to test the configuration, it switches perfectly to the failover network. But if i plug in it again. The ping from the primary device got no route. Has anyone else this problem ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.