#! /bin/sh # # default_route.sh - Set default route to use specific network interface # Copyright 2003 Tommi Saviranta # # This script is designed to set default routing to use specific network # interface. When a default route is deleted, single-host route is added # to the old gateway so that old routing can be restored. This means the # script will litter your kernel IP routing table by one "useless" rule # for each network interface that will be used as default route. If the # script believes that something isn't going as expected, it should only # print an error message and kernel IP routing table. The script may not # work properly if more than one default route exists. # # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. # # # Version: default_route.sh v0.1.2 24-Feb-2004 tsaviran@cs.helsinki.fi get_field_no () { TMP=$(echo "$1" | tr -s ' ' '\t' | cut -f $2) } get_gateway () { get_field_no "$(route -n | grep UG | grep $1 | head -1)" 2 } # Show usage # if [ $# -ne 1 ]; then echo "Usage: $0 INTERFACE" echo "Current default route:" route -n | head -2 | tail -1 route -n | grep '^0.0.0.0' exit 0 fi # Get current route # LINE=$(route -n | grep '^0.0.0.0') get_field_no "$LINE" 8 OLDDEV="$TMP" # See if we don't need to do a thing # if [ "$1" = "$TMP" ]; then echo "Current default route already through $1." exit 0 fi # Get new gateway # get_gateway $1 if [ "$TMP" = "" -o "$TMP" = "0.0.0.0" ]; then echo "Couldn't get new gateway (got \"$TMP\")!" >&2 route -n >&2 exit 1 fi NEWGATEWAY="$TMP" # Get old default route's IP and set a static routing to it so we don't lose # it's address. If a route to gateway already exists, skip this. # get_gateway $OLDDEV if [ "$TMP" = "" -o "$TMP" = "0.0.0.0" ]; then echo "Couldn't get old gateway (got \"$TMP\")!" >&2 route -n >&2 exit 1 fi if [ -z "$(route -n | grep UGH | grep $TMP)" ]; then route add -host $TMP gateway $TMP dev $OLDDEV fi # Delete old default route # get_field_no "$LINE" 2 route del default gateway $TMP dev $OLDDEV # Set up a new gateway # route add default gateway $NEWGATEWAY dev $1