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