Automatically reconnect to your VPN on Linux

Network

Automatically reconnect to your VPN on Linux

Introduction

This article is aimed at those who configured their VPN connection using the Network Manager applet, and by extension those who configured their VPN connection so that it is available in the nmcli command. It does not apply if you use gOpenVPN or GADMIN-OPENVPN-Client.

VPN connections become more and more popular, for a variety of reasons. If you are using a VPN connection for privacy or any other reasons, you probably fear to be disconnected while you are not in front of your computer, because this could leave your activity unencrypted on your ISP network. The Gnome Network Manager applet doesn’t offer a way to reconnect automatically. Fortunately, there is a solution. I will show you a little Bash script that adds this functionality.

Here is the script:

#!/bin/bash
while [ "true" ]
do
	VPNCON=$(nmcli con status)
	if [[ $VPNCON != *MyVPNConnectionName* ]]; then
		echo "Disconnected, trying to reconnect..."
		(sleep 1s && nmcli con up uuid df648abc-d8f7-4ce4-bdd6-3e12cdf0f494)
	else
		echo "Already connected !"
	fi
	sleep 30
done

Where:

  • MyVPNConnectionName is the name of you VPN connection in the Network Manager applet
  • df648abc-d8f7-4ce4-bdd6-3e12cdf0f494 is the uuid of your VPN connection. You can find it using the following command:
nmcli con

Save this script in your user personal directory, for example.

Do not forget to make this script executable by running the following command:

chmod +x /path/to/my/script/my_script

Explanation:

This script will check if you are connected to the VPN by testing if the $VPNCON variable contains the line corresponding to your VPN connection. If the $VPNCON variable doesn’t contain it, then the VPN is not connected and the script attempt to connect. Otherwise we just wait for 30 seconds (you can change this delay, but you should give enough time to fully reconnect).

Just save this script in your home directory and run it when you need.

How to run this script automatically when a user has logged in?

It’s very easy. Just append the following line to your .profile (in the root of your user directory):

/path/to/your/script/my_script &

In some distributions, it may be the .bashrc file. In Debian it’s .profile (it doesn’t work as expected with .bashrc). Just choose what works for you.

Finally, save your changes, logout from your session, and login again. The script should be automatically started, and your VPN should connect immediately. Hurray!

FAQ

Q: It doesn’ t work with my Linux distribution! What can I do?

A: This script has been tested with Debian Squeeze (6.0.3) and works like a charm. Please refer to your distribution documentation.

28 Responses

  1. Anderson says:

    I am using linux last 1 year but no one Vpn is help for my operating system. sometime ago i read your post and i am trying this.Its work for me.

  2. manolius says:

    This script didn’t work completely for me. “nmcli con status” gives all internet connections, and not only *MyVPNConnectionName*. Thus, it is allways false. I wrote this instead, and it works fine now

    #!/bin/bash +x
    while [ "true" ]
    do
            VPNCON=$(nmcli con status | grep *MyVPNConnectionName* | cut -f1 -d " ")
            if [[ $VPNCON != "*MyVPNConnectionName*" ]]; then
                    echo "Disconnected, trying to reconnect..."
                    (sleep 1s && nmcli con up uuid df648abc-d8f7-4ce4-bdd6-3e12cdf0f494)
            else
                    echo "Already connected !"
            fi
            sleep 30
    done
    1
    2
  3. Kabish says:

    I tried both of these scripts, however it just kept saying the VPN was down and would restart it. I verified that my uuid was correct. If the VPN is off it will connect it, but then after the timeout it reconnects again.

    Any suggestions? Really diggen the script if I could get it to work. Running Ubuntu 12.04

  4. samson says:

    working well with linux mint 13 (based on ubuntu 12.04).
    sometimes I had the problem, that the vpn connection was enabled, but no traffic could run through. so I a ping check if connection is really alive. if ping fails it tries to disconnect and then reconnect. as ping server I use one of googles well known dns servers.

    #!/bin/bash +x
    while [ “true” ]
    do
    VPNCON=$(nmcli con status uuid f6f5085d-xxxx-4050-85f2-0ec18ddb2ce3 | grep VPN.VPN-STATUS |awk ‘{print $2}’)
    if [[ $VPNCON != “5” ]]; then
    echo “Disconnected, trying to reconnect…”
    (sleep 1s && nmcli con up uuid f6f5085d-xxxx-4050-85f2-0ec18ddb2ce3)
    else
    echo “Already connected !”
    fi
    sleep 10
    echo “pincheck”
    PINGCON=$(ping 8.8.8.8 -c2 -q -W 3|grep “2 received”)
    if [[ $PINGCON != *2*received* ]];then
    echo “Timeout, trying to reconnect…”
    (nmcli con down uuid f6f5085d-xxxx-4050-85f2-0ec18ddb2ce3)
    (sleep 1s && nmcli con up uuid f6f5085d-xxxx-4050-85f2-0ec18ddb2ce3)
    else
    echo “PINGCHECK OK!”
    fi
    done

  5. sazary says:

    really good script, dude!
    thanx a lot
    btw, why don’t you put it up in a github repo? i think that way it should be more discoverable

  6. northofnowhere says:

    New to a gui based linux for home use. Mint was my fourth attempt at a distro that would work, been fun but sometimes hard work. Got into the networking stuff for my home server and was amazed autoreconnect wasnt built into anything. Actually, kind of disgusted. Tried about 6 complex and cumbersome fixes until I found your minimal itty bitty so simple script that simply works. THANK YOU. Works fine on Linux Mint 14

  7. Raul says:

    The problem that I have is that the VPN seems to be connected but it losses connection so that’s why I installed vpnautoconnect, but sometimes it doesn’t work as expected because it seems like it’s still connected but it’s not. Is there any way to do that too?
    Thanks in advance.

  8. Antoniy Chonkov says:

    Hello,

    Thank you for your solution. I’ve reformatted the scripts posted by you and the other guys and published it on github: https://gist.github.com/antoniy/f925ae55410a092c9e75

    I hope this will make it easier for people to setup.

    Thanks

    • Samuli says:

      Hi,

      This works well for me but I have one issue with the ping check. If I download something or my connection is otherwise very busy I sometimes get disconnected and reconnected because the ping test fails. I’ve added a 10 seconds time-out for the ping test but it doesn’t matter. Is there any other way to be sure that the VPN connection is alive? Ping check would be great otherwise because sometimes my VPN connection is down but seems to be online and the ping test works in this situation.

    • Gabriel Hautclocq says:

      Thanks for putting the script on github 🙂

  9. purpse says:

    Very new to this but when I run the script it fails to reconnect because it says \”no valid VPN secrets\”. Is there any way of including the secrets into the script?

  10. yochanon says:

    This script is actually no easier than just doing a couple of clicks with the mouse by opening the networkmanager and restarting the VPN manually.

    It isn’t checking the VPN connection constantly to make sure it needs to ‘reconnect’, so it’s really not a lot of help.

    The only way I can think of to make this script more usefull is to put in a cron job of something making the script constantly execute every x seconds/minutes to check if ones VPN connection is up and if not it executes.

    The only problem with that though is that it’d make an awful lot of cpu usage (or something, I’m sure) drag down the system by constantly checking if the VPN connection is up.

    Does this make sense? Am I seeing it wrongly? Is there an easier way to have something checking the VPN connection all the time (or at some set interval I can use) that will then utilize this script when it finds the VPN down?

    • Gabriel Hautclocq says:

      Well what you describe is pretty much what my script does… Polling the status of the connection every 30 secs, and reconnect if necessary… Sure it could be improved but it does what it says.

      • yochanon says:

        Yes, I got to thinking about it a little while ago and you’re right, except that with your solution one has to leave the konsole open on the taskbar.

        Is there a way to make it run in the background without having to keep konsole open all the time?

        • Gabriel Hautclocq says:

          You won’t see any console if you follow the advice of executing the script automatically by putting it in your .profile.

  11. Patrik says:

    Hey everyone,

    thank you for the working script.

    Is there a way to make it so when it attempts to reconnect, and perhaps the server is down, it would choose another connection instead? If that one is also down, another one?

  12. Morten says:

    I’m using Debian Jessie and

    nmcli con status

    doesn’t work anymore. However I think

    nmcli con show --active

    should do the trick.

  13. pankaj says:

    HI,

    How remove this script from doing this, how can ?

  14. Mark says:

    Fedora 24 you have to do something more like:

    VPNCON=$(nmcli con show --active | grep My\ VPN | cut --fields=1,2 -d " ")
    if [[ "$VPNCON" != "My VPN" ]]; then
    

    This handles this seemingly different nmcli (no con status command) and how a two word VPN could be handled.

  15. Cas says:

    Hi, I also use a firewall rule to prevent any DNS leaks in the case of a drop out. So this looks like a good solution for me except I’m not good enough with scripts yet to know where to edit. My VPN won’t connect with my firewall rules set, so I have a script that “unfirewalls” which allows me to connect to VPN, once connected I activate the firewall rules and now only traffic through the VPN will be accepted. For start up I just used the start up applications in settings and that allowed me to unfirewall, connect and refirewall all automtically. So now all I need is somewhere within this script to say (pardon my rubbish computer language) “VPN disconnected, run unfirewall, connect to vpn, run firewall”. I do have little scripts for those commands just where to insert them here.

    #!/bin/bash
    while [ “true” ]
    do
    VPNCON=$(nmcli con status | grep *VPN* | cut -f1 -d ” “))
    if [[ $VPNCON != *VPN* ]]; then
    echo “Disconnected, trying to reconnect…”
    (sleep 1s && nmcli con up uuid c8013f1e-615b-4900-80ac-01ccef317c78)
    else
    echo “Already connected !”
    fi
    sleep 30
    done

    my firewall script is ./firewall.sh and unfirewall is ./unfirewall.sh

    Any help on this would be great

  16. Dan Bowkley says:

    I use pon and poff for my VPN, as NM seems to barf all over my routing tables for some weird reason I haven’t yet figured out. So I bodged this together:

    #!/bin/bash
    WIFIUUID=f3b57d7a-701e-46f2-8b95-74b61851c65b
    WIFICON=`nmcli -t -fields uuid con show --active`
    while [[ $WIFICON = $WIFIUUID ]]; do
      PINGRES=`ping -c 2 192.168.1.254`
      PLOSS=`echo $PINGRES : | grep -oP '\d+(?=% packet loss)'`
      echo "`date` : Loss Result : $PLOSS"
      if [ "100" -eq "$PLOSS" ]; then
        echo "`date` : Starting VPN"
        pon home updetach && route add -net 192.168.1.0 netmask 255.255.255.0 dev ppp0
        echo "`date` : VPN Started"
      else
        echo "`date` : VPN Already Running"
      fi
      sleep 30
    done
    echo "WiFi Disconnected, Terminating VPN"
    poff
    

    Basically it just watches my WiFi, and if it’s connected it babysits the VPN.

    You’ll have to change the VPN name, network particulars, and pinged IP address to match your network. Either the router IP or some server that’s only reachable via the VPN and always up should work fine for this purpose.

  17. Yo Mismo says:

    Thanks a lot bro!!! It works like a charm on Ubuntu 16.04.

  18. richi says:

    thank you very very much and also you can this script :

    #!/bin/bash
    YOUR_VPN_NAME="speed"
    while [ "true" ]
    do
    VPNCON=$(nmcli con show --active)

    ############### the contains of $VPNCON is :
    # NAME UUID TYPE DEVICE
    # Wired connection 1 59be4e24-ef52-3288-8611-062a2e4866aa ethernet enp0s31f6
    # speed b449281e-b683-4952-bb3d-d2c33aa7090f vpn enp0s31f6

    if [[ ($VPNCON != *"vpn"*) && ($VPNCON != *"$YOUR_VPN_NAME"*) ]];then
    echo "Disconnected, trying to reconnect..."
    (sleep 1s && nmcli con up $YOUR_VPN_NAME)
    else
    echo "Already connected !"
    fi
    sleep 5
    done

  19. Gerald says:

    Hi Gabriel (and maybe Antoniy),
    my VPN-Router is a headless VM, so there is no users to login locally.
    My NIC is autoconnecting at boot time.
    Which would be the right place and/or instructions to start this script at boot time respectively after the network ist running?
    Many thanks in advance,
    Gerald

Leave a Reply

Your email address will not be published. Required fields are marked *

*

This site uses Akismet to reduce spam. Learn how your comment data is processed.