I needed to maintain a continuous (or near-continuous) VPN connection to a server (server 1) from another server (server 2) that was running a Tomcat web-app (on Ubuntu Server 16.04). Server 1 was part of a network which provides secured VPN access to external connections via Cisco Anyconnect.
For this, we're going to use the excellent OpenConnect to connect to server 1, and a bash script to continuously check the connection, and if disconnected, to reconnect.
Let's first install OpenConnect. Server 2 was running Ubuntu 16.04. Let's do:
Creating a script to reconnect when disconnected
Please note that the below approach stores a vpn password in clear text in the script file, and as such is a potential security risk. The script should be locked down to stop users without authorisation from viewing its contents. Hence, this approach may only be appropriate for a server/system that is strictly managed or not accessed by other users.
Let's create a script that will:
- connect to your VPN;
- check every
xseconds whether it is still connected
- reconnect to the VPN if the connection is broken
In the below example we'll create a
Copy the following into in your script:
Let's at least lock this file down to be only readable by root:
Running script in background
Once your happy with your script you can run said script as a background script:
Stopping background script
To stop/disconnect the VPN and script, use
ps to find the PID's of the VPN script and the
openconnect process by:
For example, on my system, running the above gives:
kill PID's 10525 and 28445, like this:
Split tunnelling with vpn-slice
Split tunnelling allows you to explicitly define the ip address(es) for which traffic will be routed to on the vpn server side. This is useful for situations where you might want to route traffic to/from a specific ip, and want all other traffic to use normal (non-vpn) connections.
For this use case you can use vpn-slice. Once installed (see here for requirements and install guide), you can then modify your the script above as follows (see line 15 for the
vpn-slice script argument):
<IP-ADDRESS> is the ip address (or addresses, separated by a space) is what addresses you want tunnelled to the vpn.
NOTE: you should install vpn-slice with
sudo to ensure it is available on the standard path (otherwise you'll need to give the full path to the vpn-slice script).