How to keep VPN connection alive automatically on debian

In today’s world of relentless surveillance, censorship and raising authoritarianism, using VPN –while it is still legal– should be a routine practice.

I wrote a script to keep my VPN connection alive. This script runs when you log in and checks every 20 seconds whether your VPN is connected or not. If it finds out that your VPN is not connected it tries to establish the connection. It works silently in the background.

Here are the steps I have taken to keep my VPN almost always connected on debian:

  1. Create a VPN connection and connect to it using Gnome panel (network-manager-gnome) or in any other way possible (I will not go into detail of this here).
  2. In Terminal: nmcli c show and note UUID of your VPN connection
  3. In Terminal: mkdir ~/Scripts ; gedit ~/Scripts/autovpn.sh
  4. Copy & paste the following script:
    #!/bin/bash
    
    # A script which tries to establish VPN connection at every 20 seconds.
    # Written by Ertuğrul Harman @ http://ertugrulharman.com/en
    # 18.03.2016
    
    # Keep a log.
    exec > >(tee -i ~/.autovpn.log)
    exec 2>&1
    
    # Enter all your VPN servers' UUID values here.
    # Use "nmcli c show --active" command to learn UUID's of active VPN connections.
    # They will be used in the order given here.
    # You may enter as many servers as you like. More the better.
    vpn=("........-....-....-....-............"
    "........-....-....-....-............"
    "........-....-....-....-............")
    
    # Optional: You may enter server locations or names here. 
    # They are used in log file and command output.
    vpn_name=("Netherlands" "Switzerland" "United Kingdom")
    
    # Keep the number of alternatives in memory.
    vpn_count=${#vpn[@]}
    
    # This defines maximum attempt number to prevent infinite connection failure.
    # Connection failure to all defined VPN servers counts only 1 attempt in this regard.
    max_attempt=20
    
    # Implemantation begins.
    
    printf "\nVPN auto connection script started at $(date +"%F %T").\nIts log file is located at ~/autovpn.log\nIt will only report when no connection is found.\n"
    
    for (( m=1; m<$max_attempt; m++ ));
        do
         #printf "\n$(date +"%F %T") Waiting for 10 seconds before VPN connection check.\n"
        sleep 10
        is_connected=$( nmcli c show --active | grep tun0 )
         if [ "$is_connected" = "" ]; 
            then 
            printf "\n$(date +"%F %T") : VPN connection is not active!\n"
            printf "$vpn_count VPN servers will be reached in given order to make a VPN connection.\n"
            printf "If none of them works this whole process will start over for $(($max_attempt-$m)) times.\n"
            
            for (( i=0; i<${vpn_count}; i++ ));
                do
                printf "\n*** Connecting to "${vpn_name[$i]}"... ***\n"
                 nmcli c up ${vpn[$i]}
                 if [ $? -eq 0 ];
                     then
                     printf "\n*** Connected to "${vpn_name[$i]}"! ***\n\nIt will be periodically checked to see if it is still connected.\n"
                    break
                     fi
                 done
              else
             #printf "$(date +"%F %T") Check result: VPN is already connected.\n"
             m=$((m - 1))
             fi
             #printf "$(date +"%F %T") Loop is ending. Waiting for 10 seconds.\n"
         sleep 10
         done
  5. Close your text editor and save the file.
  6. In Terminal: chmod +x /home/yourusername/Scripts/autovpn.sh
  7. In Terminal: gedit ~/.config/autostart/autovpn.desktop
  8. Copy & paste the following (do not forget to change ‘yourusername’ in Line 5):
    [Desktop Entry]
    Name=AutoVPN
    GenericName=AutoVPN
    Comment=Connects to VPN
    Exec=/home/yourusername/Scripts/autovpn.sh
    Terminal=false
    Type=Application
    X-GNOME-Autostart-enabled=true
  9. Close your text editor and save the file.
  10. Log out and log in or reboot your computer to see if it works.

Keep in mind that this script does not prevent any leak via your unsafe (not VPN) connections. When your VPN disconnects even for a short moment your software may access the internet via unsafe connections during that short period of time. IPTABLES may be used to prevent this. I will talk about that in another post. Here is my post about how to do that simply and effectively.

Lastly, you should check if there is a DNS leak, while your VPN is active. dnsleaktest.com can be used for this purpose. If you use OpenVPN and Network Manager (default networking interface of Ubuntu) and you have DNS leak, check this post.

This is tested on debian 8.3 but it should also work on its derivatives like Ubuntu and Linux Mint.

4 thoughts on “How to keep VPN connection alive automatically on debian

  1. Thank you for this! Took a little messing around to get it working – I think the way I pasted the code introduced a billion unicode syntax errors – but it’s working great now. Great guide.

  2. Hi Kyle! Thank you for your comment. I am happy to read that it works for you.

Leave a Reply

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