Friday, July 30, 2010

Cisco VPN Scripts

I have found that the Cisco VPN client occasionally hangs up on its connection. The reason is because the client removes the local network route which works fine until the MAC address cache expires and needs to be refreshed. Linux can't find its local route and basically drops the vpn, at which time the Cisco client conveniently puts the route back making it extra hard to track.

The really nasty part is you can't add the route ahead of time as the client will just remove it no matter how many there are and you can't add it later from the same shell as any attempt to background the client will end badly. My solution is to capture the local route and background a sub-shell which will add the route 60 seconds after the vpn client starts. I thought this would give enough time for the user to establish the connection but not be too long as to expire the MAC address cache. Here it is:
#!/bin/bash
# look for the interface that is up with a gateway assigned (UG) and grab the last field
DEV=`netstat -rn | grep UG | awk '{print $NF}'`
# This should just grab the one local route for the default interface
NETSTAT=`netstat -rn | grep $DEV | grep -v "^127\|^0.0\|169.254"`
NETWORK=`echo $NETSTAT | awk '{print $1}'`
MASK=`echo $NETSTAT | awk '{print $3}'`

# This says after 60 seconds add the local route back in
# you can't do this after vpnclient as it can't be backgrounded without a username / password on the command line
(sleep 60 && sudo /sbin/route add -net $NETWORK netmask $MASK dev $DEV)&

# Finally run the vpnclient
vpnclient connect mypcf_file

In order to make this work, your user account has to be able to execute sudo for /sbin/route without a password. For me I added my group to /etc/sudoers with the following entry:
# visudo
%users  ALL=(ALL) NOPASSWD:  /sbin/route

No comments:

Post a Comment