32

I do have a working VPN connection. Now I want this VPN connection to automatically activate when I'm in a certain wireless network. Is there a non-intrusive graphical way using network-manager-applet? If I remember correctly it worked for a while and doesn't anymore.

I made the wireless-connection in question available for all users for not having to input the password every time.

The CLI program used is vpnc with Hybrid-Auth enabled (cisco VPN-client compatible) from sroecker's PPA

EDIT: I can' try the answers anymore (because of eduroam) and since no answer seems to gain a majority of votes I'm just gonna leave it unanswered for now until one is upvoted then I'm gonna accept that.

5

12 Answers 12

20

The solution suggested by con-f-use should work but doesn't, due to a long-standing bug:

https://bugs.launchpad.net/ubuntu/+source/network-manager/+bug/280571

There are workarounds though. For recent NetworkManager versions, there is a commandline utitility, nmcli, that can be edited and saved as something like /etc/NetworkManager/dispatcher.d/vpn-up:

#! /bin/bash

REQUIRED_CONNECTION_NAME="<name-of-connection>"
VPN_CONNECTION_NAME="<name-of-vpn-connection>"


activ_con=$(nmcli con status | grep "${REQUIRED_CONNECTION_NAME}")
activ_vpn=$(nmcli con status | grep "${VPN_CONNECTION_NAME}")
if [ "${activ_con}" -a ! "${activ_vpn}" ];
then
    nmcli con up id "${VPN_CONNECTION_NAME}"
fi

[I haven't tested this -- please feel free to test and edit according to results]

See: https://wiki.archlinux.org/title/NetworkManager#Use_dispatcher_to_connect_to_a_VPN_after_a_network_connection_is_established has more info.

4
  • note that in 13.04 i had to put that script in /etc/network/if-up.d and fix /etc/NetworkManager/system-connections/connection-name according to askubuntu.com/questions/198136/… to avoid "No valid VPN secrets" error
    – OlegYch
    May 20, 2013 at 15:20
  • The Arch wiki hack does work in fact! I tried the script on the arch wiki on july 11th 2013, and modifying it from 'nmcli ...' to 'su [user] -c "nmcli..."' does not work! follow instructions as in the wiki and don't forget the chmod +x ;) cheers!
    – user174385
    Jul 11, 2013 at 15:25
  • The bug mentioned by Hugo Eden (bugs.launchpad.net/ubuntu/+source/network-manager/+bug/280571) has been fixed upstream over 5 months ago. However, I'm still experiencing it in Precise... What gives?
    – iGadget
    Dec 29, 2013 at 14:15
  • This did not work for me, so I decided to look into /var/log/syslog, and saw the following error: Mar 4 13:49:51 oleg-HP nm-dispatcher.action: Cannot execute /etc/NetworkManager/dispatcher.d/vpn-up': not executable by owner.` The solution would be to sudo chmod 755 /etc/NetworkManager/dispatcher.d/vpn-up Mar 4, 2015 at 12:51
18

You can find VPN auto-connect option in the nm-connection-editor GUI in the individual saved Wi-Fi settings. In Ubuntu 14.04 you can find it under:

System settings -> Network -> Wi-Fi or Lan -> Settings (General tab) -> Auto connect to VPN...

(Since Gnome 42, this path leads to a new simplified menu, but the complete one can still be accessed through nm-connection-editor directly)

Screenshot of GUI

After saving, a secondaries= line is added in your configuration file in the [connection] section. It will contain a list of secondary connection UUIDs to be activated. The configuration file is usually /etc/NetworkManager/system-connections/.

This information can be useful if you need to activate more than one secondary connection. You can add multiple connection UUIDs in the configuration file separated by ;, even though the GUI (at the moment: 2022) does not allow to select more than one entry.

1
  • This is exactly what I needed! Very unintuitive tho. I saw that the option was greyed out in my VPN connection config, and I didn't think it might be an option for connecting to a different connection profile.
    – B T
    Dec 15, 2021 at 19:53
13

I was able to get this working on Ubuntu 20.04 by using nm-connection-editor. For whatever reason, the option doesn't appear anymore in neither the Wifi/Ethernet nor the VPN config UIs.

  1. Open a terminal

  2. Type nm-connection-editor

  3. Select the network connection you want to auto-connect

    Network connections selection window, settings button in red

  4. Click the gear icon to open settings for that connection

  5. Go to the General tab

  6. Enable the Automatically connect to VPN option and select the VPN in the dropdown menu to the right

    Network configuration window, general tab, auto-connect option in red

  7. Click Save

1
  • 1
    Such a great answer! Thank you midopa! Sep 6, 2021 at 8:19
5

If you prefer terminals, you can use nmcli, I did it using the following commands:

First, find and open the VPN connection you want to update

➜  ~ nmcli c show --active |grep vpn
MyVPN           115ae594-aa91-4d13-8c92-421af245f935  vpn     wlp61s0         
➜  ~ nmcli c edit MyVPN

This will open the nmcli prompt, from here you can query the values and set them, like this:

===| nmcli interactive connection editor |===
...
nmcli> print connection.autoconnect
connection.autoconnect: no
nmcli> set connection.autoconnect yes
nmcli> save persistent
Saving the connection with 'autoconnect=yes'. That might result in an immediate activation of the connection.
Do you still want to save? (yes/no) [yes] yes
Connection 'MyVPN' (115ae594-aa91-4d13-8c92-421af245f935) successfully updated.

And you should be done!

1
  • Only option that worked for me. On a side note, if you know its name, you can just grep it without having to connect it first by dropping the --active.
    – Ramon Melo
    Oct 28, 2020 at 1:58
3

If I remember correctly it worked for a while and doesn't anymore.

  • This might be obvious, but sometimes I don't think of it. Did you try reinstallation like:

    sudo apt-get purge network-manager-vpn sudo apt-get install network-manager-vpnc Then: enter image description here

Now I want this VPN connection to automatically activate when I'm in a certain wireless network.

  • There's a way to suppress the "couldn't connect"-type of messages when your users are in the wrong network, but can't remember how it went. I see no other way to automatically connect in a graphical way. Maybe you'll have to write a script doing the connecting when in said wlan-network.

Hope that helped.

4
  • I still haven't come around to actually testing this. I'll mark it answered when I will. Promise.
    – turbo
    Jun 16, 2011 at 13:40
  • in my experience this doesn't actually work. I believe this to be a bug in NetworkManager Jul 10, 2011 at 11:42
  • 3
    Yep this is broken, even in Precise. It doesn't connect automatically O_o
    – eggonlegs
    Sep 12, 2012 at 23:44
  • Yup -- broken. Does not work (Ubunutu 12.04).
    – user48956
    Apr 14, 2014 at 16:38
3

I can confirm this following solution working for me. I am running Ubuntu 14.04 LTS.

I went to the shutdown icon and then system settings.

When the settings screen opens, I went to 'Network' and the WiFi network with which I was connected. There is a small arrow one one side of the name of the network.

Settings screen shot, its in Arabic

Click that icon and you should see an option called "settings" or "options" (or something similar) here:

Click settings

When the next window opens, simply go to the 'General' tab and you should see an option that gives you an option to Automatically connect to a VPN. Choose the VPN You'd like to connect when connected to this WiFi, and boom! Everytime you connect to this network, Ubuntu will also connect you to that VPN. :)

For me its working. I hope it works for everyone else too. Doesn't require any sort of text editor or code editor or anything..

1

You don't need any dispatcher scripts any more ! In 14.04 (Trusty Tahr) you just have to take the following steps after setting the autoconnect option in the NetworkManager GUI.

Store the vpn-secrets plainly in the config file for the VPN-connection under /etc/NetworkManager/system-connections/YourVPNConnectionName.

You can achieve this by setting IPSec secret-flags=0 and Xauth password-flags=0 in the config file. Then go to the NetworkManager GUI and save again you VPN-connection settings. Now a section called [vpn-secrets] should be present in the config file. Doublecheck it and autoconnection should be working now !

1

Even though the man page lists nmcli con status as a valid command, The above solution provided by Hugo Heden returns an error "Error: Object 'status' is unknown, try 'nmcli help'"

I'm using nmcli 1.2.2 (nmcli -v) and I've tested and modified the following for /etc/NetworkManager/dispatcher.d/vpn-up and it worked like a charm.

#! /bin/bash

REQUIRED_CONNECTION_NAME="<name-of-connection>"
VPN_CONNECTION_NAME="<name-of-vpn-connection>"


default_conn=$(nmcli con show --active | grep "${REQUIRED_CONNECTION_NAME}")
vpn_conn=$(nmcli con show id | grep "${VPN_CONNECTION_NAME}")
if [ "${default_conn}" -a ! "${vpn_conn}" ];
then
    nmcli con up id "${VPN_CONNECTION_NAME}"
fi

Note: You can use nmcli con show to see all connection names as they aren't always the same as what's listed in the Network Connections GUI

2
  • The OP is asking about Ubuntu.
    – fosslinux
    Jul 22, 2016 at 3:31
  • Kali and Ubuntu are both Debian based so the solution is often the same. I just went ahead and tested this on an Ubuntu 15.10 instance and the nmcli error was the same as I'd mentioned above. The solution worked just the same as well. The nmcli version installed on the 15.10 box is 1.0.4.
    – jw00druff
    Jul 22, 2016 at 8:35
1

You can add the uuid of the VPN profile by using the "secondaries" field in your primary connection

For example, /etc/NetworkManager/system-connections/Wired

[connection]
id=Wired
uuid=95ad54f8-9d72-3e65-a4a7-b106aa310eed
type=ethernet
secondaries=66ecf287-8b26-413b-86f2-caca7608bc67;

Reference https://developer.gnome.org/NetworkManager/stable/nm-settings.html

0

Use following Python script Gist #1547663.

First parameter to the script is VPN connection name in NetworkManager and the second is comma separated names of networks that should be ignored (e.g. using VPN connection at home is useless).

Example to install and let it run at boot time:

git clone git://gist.github.com/1547663.git /home/user/autovpn/
echo "python /home/user/autovpn/autovpn.py 'myvpn' 'Auto homenetwork,Auto worknetwork' > /var/log/autovpn.log&" > /etc/rc.local
/etc/rc.local

Now if you connect to a network (either wifi or ethernet), it will also try to setup VPN connection.

2
  • 1
    I think this approach is less elegant, due to a background process being active for this all the time, while it could be event-driven like in the answer of @hugoheden.
    – gertvdijk
    Dec 4, 2012 at 15:37
  • It does more than his answer: it also handles VPN reconnect and cases where user manually disables vpn connection (meaning it shouldn't try to reconnect VPN in that case)
    – iElectric
    Dec 5, 2012 at 11:18
0

Updating Hugo's answer. Works well on Ubuntu 20.04

#! /bin/bash

REQUIRED_CONNECTION_NAME="<name-of-connection>"
VPN_CONNECTION_NAME="<name-of-vpn-connection>"


activ_con=$(nmcli c s --active | grep "${REQUIRED_CONNECTION_NAME}")
activ_vpn=$(nmcli c s --active | grep "${VPN_CONNECTION_NAME}")
if [ "${activ_con}" -a ! "${activ_vpn}" ];
then
    nmcli con up id "${VPN_CONNECTION_NAME}"
fi
0

All the above mentioned solutions might not properly work with WireGuard VPNs, at least not as far as Debian 12 Bookworm with KDE since there are still open Issues because WireGuard is a device not an vpn as far as I understood it:

So i made a bash script inspired from the answers here for Wireguard which also allows to define multiple WLANs at once and a "Paranoid Mode". I specifically only test one WLAN interface (since I have another one for a virtual machine):

  1. Create a 99-vpn-up.confin /etc/NetworkManager/dispatcher.d/
  2. Make it executable chmod +x 99-vpn-up.conf

Bash script:

#!/bin/bash

# Configuration (change these)
WLAN="wl...."           # Interface name of WLAN adapter (find it with 'ip a'...)
VPN_NAME="FOOBAR..."        # VPN Connection name (Name from Network Manager)
CON="HandyHotspot|PublicWLAN|...."      # Connection names, separated multiple connection names with a pipe '|'

# Get parameters from the dispatcher (see 'man NetworkManager-dispatcher' for all the different states)
interface=$1 status=$2


if [ "$interface" = "$WLAN" ]; then
    # If the interface is the WLAN adapter, check the status
    case $status in
    up)
        # In case the interface got started, check if it is one of our defined WLAN Connections
        if nmcli con show --active | grep -Eqs "$CON"; then
            # Start the VPN Connection if it is not already running
            if ! nmcli con show --active | grep -qs "$VPN_NAME"; then
                 nmcli connection up id "$VPN_NAME"
            fi
        fi
    ;;
    down)
        # In case the interface got stopped, disable the VPN connection if it is active
        # In the case from switching from a defined WLAN to an undefined, this script is run twice 
        #so it 'should' not start another VPN Connection
        if nmcli con show --active | grep -qs "$VPN_NAME"; then
            nmcli connection down id "$VPN_NAME"
        fi
    ;;
    esac
fi

# "Paranoid Mode" :-) 
# Uncomment the following lines if you want to restart the VPN in case it 
# gets deactivated while still connected to a WLAN defined above - basicall disables non-VPN WLANs
# Wireguard is a "device" so "down" has to be used, for other VPNs "vpn-down" has to be used (did not test)

#if [ "$interface" = "$VPN_NAME" ]; then
#   case $status in
#   down)
#       # Restart the VPN again in case on of the defined WLANs is still active
#       if nmcli con show --active | grep -Eqs "$CON"; then
#           nmcli connection up id "$VPN_NAME"
#       fi
#   ;;
#   esac
#fi

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .