Failover iproute2

From MS Computech
Jump to: navigation, search

iproute2 failover script


Wan1 up <source lang=bash>

  1. !/bin/sh
  2. WAN1

DEV=eth0 GATEWAY=192.168.101.1

ip route delete default

  1. ip route delete default

ip route add default via $GATEWAY dev $DEV </source>

Wan2 up <source lang=bash>

  1. !/bin/sh
  2. WAN2

DEV=eth1 GATEWAY=192.168.102.1

ip route delete default

  1. ip route delete default

ip route add default via $GATEWAY dev $DEV </source>


Failover <source lang=bash>

  1. !/bin/sh

INTERVAL=10 PACKETS=1 USINGWAN=0 WAN1=eth0 WAN2=eth1

  1. WAN1GW=`route -n | grep $WAN1 | grep '^0.0.0.0' | awk '{ print $2 }'`
  2. WAN2GW=`route -n | grep $WAN2 | grep '^0.0.0.0' | awk '{ print $2 }'`

WAN1GW=192.168.101.1 WAN2GW=192.168.101.2

  1. We'll run this in the intervals given above

while sleep $INTERVAL do

# Try to figure out the current route

       TARGET=`ip route | awk '/default via/ {print $3}'`
       

# Set the variable, so let the script now which connection is it dealing with

       if [ "$WAN1GW" = "$TARGET" ]; then 
               USINGWAN=1;
       else if [ "$WAN2GW" = "$TARGET" ]; then
               USINGWAN=2;
         fi;
       fi
       # We'll ping as many times the $PACKETS variable tells, and test if we have connection:
       RET=`ping -c $PACKETS $TARGET 2>/dev/null | awk '/packets received/ {print $4}'`

# If we don't have connection, change the active WAN port (If there is any loss with multiple packets, it should change either)

       if [ "$RET" -ne "$PACKETS" ]; then
               if [ "$USINGWAN" = "1" ]; then
                       /app/wan2.up
                       USINGWAN=2
                       echo "Changed active WAN port to 2!"
               else
                       /app/wan1.up
                       USINGWAN=1
                       echo "Changed active WAN port to 2!"
               fi
       fi 

done;




</source> Source