Last active
September 10, 2015 15:12
-
-
Save ianhomer/006fe83241cdbea99349 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# Set static routing tables to route some external IP addresses to a different gateway, for example if tend | |
# to connect on a VPN and you want to route some traffic to avoid the VPN. | |
# | |
# I use this on a Mac - if you're lucky it might work on other operating systems. This script does update | |
# your /etc/hosts files AND route table. Take appropriate due care. | |
# | |
# Usage | |
# ----- | |
# | |
# Run the following BEFORE you connect to your VPN : | |
# | |
# export NON_VPN_HOSTS="host1.com host2.com host3.com" | |
# export LOCAL_GATEWAY="192.168.1.254" | |
# vpn-route-external.sh | |
# | |
# and enter sudo password so that /etc/hosts and route table is updated | |
# | |
action=${1:-create} | |
gateway=${2:-$LOCAL_GATEWAY} | |
nonVpnHosts=${3:-$NON_VPN_HOSTS} | |
if [ -z "gateway" ] ; then | |
echo "Please set shell variable \$LOCAL_GATEWAY to static gateway IP address" | |
exit 1 | |
fi | |
if [ -z "$nonVpnHosts" ] ; then | |
echo "Please set shell variable \$NON_VPN_HOSTS to space separated list of hosts that don't want route through VPN" | |
exit 1 | |
fi | |
echo "Action : $action" | |
for host in $nonVpnHosts ; do | |
ip=`host $host | awk '/has address/ { print $4 }'` | |
nonVpnIps=$nonVpnIps" $ip" | |
done | |
nonVpnIps=`echo $nonVpnIps | tr ' ' '\n' | sort -u | tr '\n' ' '` | |
echo "Direct Gateway : $gateway" | |
echo "Non VPN Hosts : $nonVpnHosts" | |
echo "Non VPN IPs : $nonVpnIps" | |
function deleteVpnRoutes { | |
for ip in $nonVpnIps ; do | |
sudo route -n delete $ip/32 $gateway | |
done | |
echo "External routes REMOVED to route table" | |
for host in $nonVpnHosts ; do | |
sudo sed -i '' "/$host/d" /etc/hosts | |
done | |
echo "External IP addresses REMOVED from /etc/hosts" | |
} | |
if [ $action == "delete" ] ; then | |
deleteVpnRoutes | |
else | |
deleteVpnRoutes | |
# We should really get these from nslookup | |
for host in $nonVpnHosts ; do | |
ip=`host $host | awk '/has address/ { print $4 }' | head -n 1` | |
echo "$ip $host" | sudo tee -a /etc/hosts | |
done | |
echo "External IP addresses ADDED to /etc/hosts" | |
echo "External routes ADDED to route table" | |
for ip in $nonVpnIps ; do | |
sudo route -n add $ip/32 $gateway | |
done | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment