Skip to content

Instantly share code, notes, and snippets.

@rohitkode
Last active January 19, 2017 12:16
Show Gist options
  • Save rohitkode/4a34fb238df2d9a1390f to your computer and use it in GitHub Desktop.
Save rohitkode/4a34fb238df2d9a1390f to your computer and use it in GitHub Desktop.
Use openconnect to connect to VPN while allowing internet access (works for wireless interface only)
#/bin/bash
##########################################################################
# Uses openconnect to connect to a VPN gateway and ssh into the specified
# remote host as per the arguments passed to the script, and route internet
# traffic through a default gateway.
# Note: The script assumes internet connectivity on the wireless interface
# "usage: ./vpn <remote_user> <remote_host>"
###########################################################################
VPN_GATEWAY=${VPN_GATEWAY:-127.0.0.1} # Make sure to set this correctly to your VPN Gateway IP Address
VPN_USERNAME=${VPN_USERNAME:-me} # Your VPN username
GROUP=${GROUP:-None} # Set this if VPN profile falls under an Auth Group
TUNNEL_INTERFACE=tun0
WIRELESS_INTERFACE=$(ls /sys/class/net/ |grep w)
NETWORKS=("") # Space separated list of networks to add VPN routes for
DEFAULT_GATEWAY=$(ip route show default | awk '/default/ {print $3}')
USER=$1 # Remote server's ssh user
REMOTE_HOST=$2 # Remote ssh server's host name / i.p address
function usage
{
echo "usage: ./vpn <remote_user> <remote_host>"
}
function parse_args() {
args=$#
if [ $args -ne 2 ]
then
usage
exit
fi
}
function reconfigure_routes() {
# Delete any default routes created on tunnel interface
sudo route del -net 0.0.0.0 netmask 0.0.0.0 dev $TUNNEL_INTERFACE
# Add default route for non-vpn traffic
sudo ip route add default via $DEFAULT_GATEWAY dev $WIRELESS_INTERFACE proto static
# Add static routes for data center networks via tunnel interface
for network in ${NETWORKS[@]}
do
sudo route add -net $network dev $TUNNEL_INTERFACE
done
}
function connect_to_vpn() {
echo "Running openconnect"
sudo openconnect -b --no-cert-check -u $VPN_USERNAME -s /etc/vpnc/vpnc-script --authgroup $GROUP $VPN_GATEWAY
failed=`echo $?`
if [ -n $failed ]
then
reconfigure_routes
fi
}
parse_args $(echo $*)
if [ -z "$DEFAULT_GATEWAY" ]
then
echo "ERROR: No Default Gateway set! Connect to the internet and try again."
exit
fi
connected=`ps aux | grep openconnect | grep -v grep | wc -l`
if [ $connected -eq 0 ]
then
echo -e "Not connected to VPN. Connecting...\n"
connect_to_vpn $user $remote_host
fi
# SSH to the remote host
ssh $USER@$REMOTE_HOST
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment