Nov 14, 2013

Script To Automatically Connect and Reconnect VPN in Ubuntu 13.10

I mentioned the other day that I replaced Microsoft Windows on my main desktop at home with Xubuntu. I also mentioned yesterday how I had setup Deluge with RSS so I can automatically torrent TV shows. Another thing I mentioned about a month ago was that I had subscribed to TorrentPrivacy because my ISP sent me a copyright infringement warning email.

Well the torrenting is working splendidly, but for the last two days when I checked on the computer in the morning I noticed that my VPN connection to TorrentPrivacy was disconnected. I am also using the IP Blocklist in Deluge too, so I'm not too worried, but it's not fool proof like VPN. I needed something to keep me connected to VPN no matter what.

I realize that in Network Manager you can edit your network connection and select the option to automatically connect to your VPN, but that's flaky and frequently fails. If it can't connect to VPN it just fails to connect altogether.

Well I found a script to run at startup that checks to see if I am connected to VPN every 20 seconds, and if not it tries to connect. It works like a charm too!

Before you can get it to work though you need to do a couple of things.
  • Create your VPN connection in Network Manager like usual.
  • Using your favorite text editor, edit /etc/NetworkManager/system-connections/VPNName
  • Change password-flags=1 to password-flags=0
  • Also add the following at the bottom:


Be sure to change VPNName and VPNPassword to match your configuration.

Now you need to find the UUID of your VPN connection. To do that do the following:
  • Run nmcli con status from the terminal while connected to VPN
  • Alternatively you can get the UUID from /etc/NetworkManager/system-connections/VPNName
Once you have the UUID, and you've edited your VPN's config file, you need to create a text file called autovpn and save it in /etc/init.d by doing the following:
sudo nano /etc/init.d/autovpn
Paste the following and be sure to replace the UUID with the UUID for your VPN:
while [ "true" ]
    VPNCON=$(nmcli con status uuid d30df716-37e8-4e0e-8062-6340cb6f413f | grep VPN.VPN-STATE | awk '{print $2}')
    if [[ $VPNCON != "5" ]]; then
        echo "Disconnected, trying to reconnect..."
        (sleep 1s && nmcli con up uuid d30df716-37e8-4e0e-8062-6340cb6f413f)
        echo "Already connected !"
    sleep 20
Now make your script executable:
sudo chmod +x /etc/init.d/autovpn
Now we want to add autovpn as a service that starts when the computer starts, so we run:
sudo update-rc.d autovpn defaults
That's it! Now when the computer reboots, the script will launch and automatically check if it's connected to VPN every 20 seconds, and if it isn't will try to establish the connection!
Enhanced by Zemanta

Twitter Delicious Facebook Digg Stumbleupon Favorites More

Design by Free WordPress Themes | Bloggerized by Lasantha - Premium Blogger Themes | stopping spam