-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathroute_via
More file actions
executable file
·76 lines (59 loc) · 1.65 KB
/
route_via
File metadata and controls
executable file
·76 lines (59 loc) · 1.65 KB
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#!/bin/bash
##### ARGUMENTS & CHECKS
force=0
if [[ $1 == "-f" ]]; then
shift
force=1
fi
new_route=$1
if ! [[ ${new_route:0:3} =~ ^[0-9]+$ ]]; then
echo "[Err] Please give me an IP address! (got: $new_route)"
exit -1
fi
dev=`ip route | grep default | cut -d ' ' -f 5`
net=`ip addr show dev $dev | grep -E --only-matching 'inet [0-9]+\.[0-9]+\.[0-9]+\.'`
net=${net:5}
if ! [ $net == ${new_route:0:${#net}} ]; then
echo "[Err] Given IP address is outside of our network (network: ${net:0:-1}.x)"
exit -2
fi
if ! ping -c 1 $new_route >/dev/null ; then
echo "[Err] Given IP address seems to be unreachable (IP: $new_route)"
exit -3
fi
old_route=`ip route | grep default | cut -d ' ' -f 3`
if [[ $new_route == $old_route ]]; then
echo "[i] Routes are the same. No change needed. No change done. (router: $old_route)"
exit 0
fi
##### MAKE THE CHANGE
function route_via {
router=$1
### ROUTING
ip route replace default via $router dev $dev proto static
### DNS RESOLUTION
dns=$router
cp /etc/resolv.conf /tmp/resolv.conf-`date +'%s'`.bkp
cat > /etc/resolv.conf <<EOF
# Generated by route_via
domain lan
search lan
nameserver $dns
EOF
}
route_via $new_route
##### CHECK THE RESULT
if [ $force -eq 0 ] && ! ping -c 2 8.8.8.8 >/dev/null ; then
echo "[E] New route is not working. Failing back to the old one..."
route_via $old_route
exit 1
fi
real_route=`traceroute -n --max-hops=1 --queries=1 8.8.8.8 | tail -1 | grep -E --only-matching '[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+'`
if [[ $real_route == $new_route ]]; then
echo '[i] Route change succeded.'
exit 0
else
echo "[i] Route change failed. Current route is: $real_route"
exit 2
fi
#EOF