Auto reconnect to VPN on disconnect?

As of 18.10 (cannot check in earlier versions) VPN connections in NetworkManager have a setting vpn.persistent which does just that: reconnects to a VPN on connection loss until you disconnect manually. It is set to "no" by default and unfortunately isn't exposed neither in Gnome Network Settings nor in nm-connection-editor.

But you can set it through a CLI like this:

nmcli connection modify <Your VPN connection name> connection.autoconnect-retries 0
nmcli connection modify <Your VPN connection name> vpn.persistent yes

The connection must exist before you do that, of course. And autoconnect-retries 0 actually means "retry forever".

Also note that these settings get reset occasionally, probably with updates to NetworkManager or related packages, so you need to check them and correct back.

sources:

  • https://developer-old.gnome.org/NetworkManager/stable/settings-connection.html
  • https://developer-old.gnome.org/NetworkManager/stable/settings-vpn.html

OpenVPN has a build-in mechanism to automatically detect dead links and reconnect. In Network Manager go to "Edit Connections", select your VPN connection and choose "Edit". In the "VPN" tab click on "Advanced..." and go to the "General" Tab. There you have two relevant options:

"Specify ping interval" tell OpenVPN how frequently to check if the link is still alive. "Specify exit or restart ping" tells it how long to wait until it takes action and which action to take.

Example: My setting are "30 / ping-restart / 300". This means OpenVPN checks every 30 seconds if the link is still active. If the link is down for 300 seconds it initiates a restart.

This way there is no need for external scripts...


After a bit of digging I found this answer, tested it (on Ubuntu GNOME 15.04) and so far it seems working.

The only thing I might add is that once the script file is created it doesn't necessarily need to be saved to your /home folder. You can save it anywhere, make it executable and add it to the list of startup programs.