Automatically reconnect to your VPN on Linux

Network

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.

19 thoughts on “Automatically reconnect to your VPN on Linux

  1. 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. 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
  3. 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. 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. 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 / 8 March 2013 at 03:24

    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. 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 / 3 March 2014 at 01:18

    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

    • 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 / 13 March 2015 at 14:33

      Thanks for putting the script on github :-)

  9. 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. 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 / 13 March 2015 at 14:23

      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.

      • 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 / 16 March 2015 at 14:29

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

Leave a Reply

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


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>