· 9 years ago · Aug 30, 2016, 11:48 AM
1#!/bin/bash
2#
3# Author: Preston M. <pentie [at] gmail.com> 2012.09.01
4#
5# This script sets up route tables for each different interface
6# properly descriped in /etc/network/interfaces.
7# Useful when the server has more than one IP in different subnets with
8# different gateways
9#
10# Usage:
11# 1. put this script under /etc/network/if-up.d , make sure excuatable
12# 2. describe interfaces in /etc/network/interfaces, it's better
13# static, dhcp mode not tested.
14#
15# The script will not work if any of this OPTIONS missing:
16# address
17# gateway
18# network
19#
20
21if [[ "$MODE" != start || "$IFACE" == lo || "$ADDRFAM" != inet ]]; then
22 exit 0
23fi
24
25export `ifquery $IFACE|sed 's/: /=/;s/[- ]/_/g'`
26
27if [[ -z $address || -z $gateway || -z $network ]]; then
28 logger "$0: RouteTable Network for dev $IFACE incomplete. add=$address gw=$gateway nw=$network"
29 echo "$0: RouteTable Network for dev $IFACE incomplete. add=$address gw=$gateway nw=$network"
30 exit 0;
31fi
32
33TABLENAME="table`echo $address|sed 's/\.//g'`"
34
35isIDInRtTables () {
36 for NUM in `sed -n 's/^\([0-9]\+\).\+/\1/p' /etc/iproute2/rt_tables`; do
37 if [[ $1 -eq $NUM ]]; then
38 return 0
39 fi
40 done
41
42 return 1;
43}
44
45if ! grep -q $TABLENAME /etc/iproute2/rt_tables; then
46 while true; do
47 let ID=$RANDOM%250
48 if ! isIDInRtTables $ID; then
49 echo $ID $TABLENAME >> /etc/iproute2/rt_tables
50 break
51 fi
52 done
53fi
54
55
56/sbin/ip route add $network dev $IFACE src $address table $TABLENAME || true
57/sbin/ip route add default via $gateway table $TABLENAME || true
58/sbin/ip rule add from $address table $TABLENAME || true
59
60logger "$0: Setup Route table $TABLENAME for $IFACE with gateway $gateway ."