Apply VPN routes automatically


I work remote, and for accessing work machines (that are scattered around the world) I use VPN. The usual problem of using VPN is that when the VPN connection is up, all network traffic gets trhough the VPN connection. It might be not a problem, but you might be not wanting to route your private network data via the employer’s VPN connection. And in some cases, access to the Internet over work VPN account might be prohibited on the employer side. In other words, the problem is: you don’t want your network traffic to go via the work VPN account when the VPN connection is up.

The suggested solution works for OS X. Should work for Linux also.


First of all, you need to go to the VPN account options and disable the ‘Use as default route’ selector. After that, when the VPN is up, no traffic will go through it.

Now, we need some way to instruct computer to use the VPN for some certain list of IP addresses. For doing that, here is a simple shell script:


# configuration section




ROUTE_CMD="sudo /sbin/route"

# end of configuration section

IP=$(/sbin/ifconfig ${IFACE} 2>/dev/null | grep 'inet '| cut -d ' ' -f4)

if [[ -z $IP ]]; then
  echo "Can't find network interface ${IFACE}\n";

echo "Using IP $IP\n"

for ((i = 0; i < ${#array_add[@]}; i++))
  $ROUTE_CMD add ${array_add[$i]} $IP

for ((i = 0; i < ${#array_delete[@]}; i++))
  $ROUTE_CMD delete ${array_delete[$i]}

In the beginning of the script ou can find the ‘confgiuration’ section:
IFACE - here you should put the VPN interface name (can be found out by using ifconfig command)
array_add - it is an array where you should put all the hosts and networks you want access them through the VPN connection
array_delete - it is an array where you should put all hosts/networks you want to delete from the routing table when the VPN connection is up.
ROUTE_CMD - a full path to the route command on your computer

You can execute this script manually after you up the VPN connection. Or you can put the script into the VPN if-up configuration, so the magic will be happening automatically.