Skip to content

Instantly share code, notes, and snippets.

@Daniyal-Javani
Forked from Apsu/failover.sh
Last active July 17, 2019 12:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Daniyal-Javani/6ea632dbbbb744f0e4f6dd0004b0351e to your computer and use it in GitHub Desktop.
Save Daniyal-Javani/6ea632dbbbb744f0e4f6dd0004b0351e 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
#!/bin/bash
# Set defaults if not provided by environment
CHECK_DELAY=${CHECK_DELAY:-4}
CHECK_IP=${CHECK_IP:-8.8.8.8}
PRIMARY_IF=${PRIMARY_IF:-eth0} PRIMARY_GW=${PRIMARY_GW:-192.168.1.1}
BACKUP_IF=${BACKUP_IF:-wlan0}
BACKUP_GW=${BACKUP_GW:-192.168.43.1}
# 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 succeedscd
if ! ping -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"
else
ip r d default via "$PRIMARY_GW" dev "$PRIMARY_IF"
ip r a default via "$BACKUP_GW" dev "$BACKUP_IF"
fi
fi
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment