Failover Script
Failover script for dual WAN failover setup which switches back to primary when connection restores
#!/bin/bash
# Configuration
PRIMARY_INTERFACE="eth0" # Replace with your primary interface name
SECONDARY_INTERFACE="eth1" # Replace with your secondary interface name
TARGET_IP="8.8.8.8" # Replace with a reliable IP to ping (e.g., Google's DNS)
PING_TIMEOUT=2 # Timeout in seconds for ping
SLEEP_INTERVAL=5 # How often to check (seconds)
# Function to check if a gateway is reachable
is_gateway_reachable() {
local interface="$1"
local target="$2"
local timeout="$3"
if ping -c 1 -W "$timeout" -I "$interface" "$target" > /dev/null 2>&1; then
return 0 # Success (reachable)
else
return 1 # Failure (unreachable)
fi
}
# Function to switch to secondary interface
switch_to_secondary() {
echo "$(date '+%Y-%m-%d %H:%M:%S') - Switching to secondary interface: $SECONDARY_INTERFACE"
# Disable primary interface (example)
sudo ip link set "$PRIMARY_INTERFACE" down
# Enable secondary interface (example)
sudo ip link set "$SECONDARY_INTERFACE" up
# Optionally, configure routing to use the secondary gateway if necessary
# sudo ip route add default via <secondary_gateway_ip> dev "$SECONDARY_INTERFACE"
}
# Function to switch back to primary interface
switch_to_primary() {
echo "$(date '+%Y-%m-%d %H:%M:%S') - Switching back to primary interface: $PRIMARY_INTERFACE"
# Disable secondary interface (example)
sudo ip link set "$SECONDARY_INTERFACE" down
# Enable primary interface (example)
sudo ip link set "$PRIMARY_INTERFACE" up
# Optionally, configure routing to use the primary gateway if necessary
# sudo ip route add default via <primary_gateway_ip> dev "$PRIMARY_INTERFACE"
}
# Main script logic
while true; do
if is_gateway_reachable "$PRIMARY_INTERFACE" "$TARGET_IP" "$PING_TIMEOUT"; then
echo "$(date '+%Y-%m-%d %H:%M:%S') - Primary interface is up"
# Check if currently on secondary, and switch back if appropriate
if ip link show "$SECONDARY_INTERFACE" | grep "state UP" > /dev/null; then
switch_to_primary
fi
else
echo "$(date '+%Y-%m-%d %H:%M:%S') - Primary interface is down"
# Check if currently on primary, and switch to secondary
if ! ip link show "$SECONDARY_INTERFACE" | grep "state UP" > /dev/null; then
switch_to_secondary
fi
fi
sleep "$SLEEP_INTERVAL"
doneLast updated