How to Automatically Connect Openconnect Vpn When the Connection Closes?

I need to use a third party web service which is accessible only through Cisco AnyConnect VPN. I'm using OpenConnect on Ubuntu to connect to this VPN using host, username, and password.

However, instead of having to manually connect every time we need to connect to the service (since the service is being consumed by a script that runs on daily basis), I would like to set it up once and have itself reconnect when the tunnel breaks.

Is there a way for us to connect openconnect client (or any other similar client for Cisco AnyConnect) to automatically reconnect when the connection breaks.

Alternatively, is there a way to login without username and password and store that configuration somewhere so we can automatically respawn the process when it stops.

Please note that this is all on a server, so no GUI.

3 Answers

See the options it has. openconnect --help:

-u,--user=NAME

Set login username to NAME

--passwd-on-stdin

Read password from standard input

--reconnect-timeout

Keep reconnect attempts until so many seconds have elapsed. 
The default timeout is 300 seconds, which means that openconnect 
can recover VPN connection after a temporary network 
downtime of 300 seconds.

it also supports a

--config=CONFIGFILE

There are several scripts on-line you can adapt to your situation.

I created a script to do this, you must change DEVICE_NAME, SERVER_ADDRESS, USERNAME and PASSWORD_FILE_PATH to a file that contains your password

You can find the name of your VPN device with /sbin/ifconfig.

#!/bin/bash
if ! /sbin/ifconfig | grep -q 'DEVICE_NAME'; then
  sudo openconnect -b -q SERVER_ADDRESS -u 'USERNAME' --passwd-on-stdin < PASSWORD_FILE_PATH
fi

i use a service file

/etc/systemd/system/myVpn.service

[Unit]
Description=My Vpn Connection
After=network.target

[Service]
Type=simple
Environment=password=correcthorsebatterystaple
 ExecStart=/bin/sh -c 'echo YourPasswordHere | sudo openconnect --protocol=nc YourServerHere --user=YourUserHere --passwd-on-stdin'

Restart=always

then I just run it with

systemctl start myVpn

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Elena Rostova

Elena Rostova

Lead Health, Wellness & Medical Journalist

Elena Rostova holds a Master's degree in Public Health Journalism. She covers groundbreaking medical research, holistic wellness trends, mental health awareness, and nutritional science.

Share this article
Twitter Facebook Pinterest