Similar to this case, I needed to maintain a (near) continuous VPN connection to a server (server 1) from my server (server 2) that was running a Tomcat web-app (on Ubuntu Server 16.04). Server 1 was part of a network that provided secured VPN access using a FortiNet VPN gateway.
Installing Forticlient and dependencies
You'll need to install an appropriate Forticlient SSLVPN package. I don't know why, but FortiNet makes it unusually difficult to find the Linux client package with the forticlientsslvpn_cli script that is required. In any case, I found a package (used version 4.4.23330-1) appropriate for my Ubuntu server (running 16.04) here. Once downloaded you can install it with:
You'll also need the
expect packages installed. If you're using Ubuntu, simply do:
Forticlient should be installed to /opt/forticlient-sslvpn/64bit/. Apparently you need to run the
setup script first:
Scroll through the legalese and then accept (type
Y). We should have everything we need to now automate connecting.
Bash script (with embedded expect script) to execute (and maintain FortiClient VPN connection)
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.
We'll now create a bash script to handle the connection (and automatic reconnection). The script below does several things, including creating and executing an external expect script. This expect script automates and emulates a bit of human interaction that
NOTE: the "EOF" on line 47 MUST be preceded by a single TAB character (not spaces), otherwise the script will fail. If you are copy/pasting the script above into your favourite Linux text editor, please remove the preceding spaces and replace with a tab character.
Securing and executing
You'll note that the above script requires the entering of a username and password. At the very least, let's lock down this script to
root (only allow
root to read/write contents):
Assume our script is called
forti-vpn.sh and is located in our home folder
To execute the script, change to the folder where it resides and run
which will execute the script in the background.
Stopping the script (and killing the vpn connection)
To stop the script you'll need to find it's
pid's and kill them. If you named your script
forti-vpn.sh, then you can do this easily with
pkill. For example, executing
will kill all processes with the name "forti" in it (which include the script and spawned forticlient processes).
Alternatively, you can use
htop. You should have this installed (if not, do
sudo apt-get install htop). With
htop you can then locate the
sudo forti-vpn.sh process and select them (with space-bar) and then hit F9 (kill) and then 9 (sigkill) and hit enter.