Toggle a VPN connection

on March 06, 2020. in Development. A 1 minute read.

At work I often have to turn a VPN connection on and off. Clicking through the network manager, finding the right VPN connection, connect to it… Feels like a waste of time, no? There has to be a better way. And there is :)

It uses the nmcli command line tool that comes with the Network Manager on Ubuntu:
#! /bin/bash


if [ -z "$VPN" ]
    exit 1

ACTIVE=`nmcli con show --active | grep "$VPN"`

if [ -z "$ACTIVE" ]
    nmcli con up id "$VPN"
    nmcli con down id "$VPN"

exit 0

We pass it one argument, the name (ID) of the VPN connection. Set it as an executable for the current user and link it to somewhere that’s in our $PATH, like /usr/local/bin:

chmod u+x
sudo ln -s /home/robert/projects/toggle-vpn/ /usr/local/bin/toggle-vpn

Running toggle-vpn myvpn for the first time will turn the VPN myvpn on, running it again will turn it off.

Now that we have it as a system wide command, we can create a keyboard shortcut for it through Settings > Devices > Keyboard. I have set it as Ctrl+Super+V.

Happy hackin’!

Tags: bash, vpn.

Get the next article to your inbox

If you'd like, you can get the next article I write to your email inbox.