Skip to content

Instantly share code, notes, and snippets.

@tizmagik
Last active May 7, 2020 11:55
Show Gist options
  • Save tizmagik/2055a38aeca8976a69e3 to your computer and use it in GitHub Desktop.
Save tizmagik/2055a38aeca8976a69e3 to your computer and use it in GitHub Desktop.
Bash script to automatically reconnect VPN (as long as the parent connection is active)
#!/bin/bash
### BEGIN INIT INFO
# Provides: autovpn
# Required-Start: $local_fs $network
# Required-Stop: $local_fs
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: autovpn
# Description: Automatically reconnects VPN if disconnected
### END INIT INFO
### USAGE
# Bash script to automatically reconnect VPN (as long as the parent connection is active)
# adapted from: http://www.bauer-power.net/2013/11/script-to-automatically-connect-and.html#.VP3SuoHF-n4 to fix the bug that prevented the machine from restarting
# Just place in /etc/init.d/autovpn with chmod +x and then `sudo update-rc.d autovpn defaults`
# if using Ubuntu Guest in VirtualBox and you need Shared Folders to work, rename to `zautovpn` and add it to startup via the 'Startup' app
### END USAGE
# While we're at Default run level (2), e.g. not rebooting
while [ "$(runlevel | awk '{ print $2 }')" -eq 2 ]
do
VPNCON=$(nmcli con show uuid 844ccb1c-fb23-4962-b20c-fcff5cf53b65 | grep VPN.VPN-STATE | awk '{print $2}')
if [[ $VPNCON != "5" ]]; then
echo "Disconnected, trying to reconnect..."
(sleep 1s && nmcli con up uuid 844ccb1c-fb23-4962-b20c-fcff5cf53b65)
else
echo "Already connected !"
fi
sleep 15
done
@tizmagik
Copy link
Author

tizmagik commented Sep 3, 2017

Edit the config to not prompt for a password every time:

sudo gedit /etc/NetworkManager/system-connections/PIA\ -\ US\ East

change password-flags=1 to password-flags=0

Add the following two lines:

[vpn-secrets]
password=THEPASSWORD-FROM-PIA

Get the UUID of the Ethernet and VPN network adapters

nmcli con show

Edit this GIST:

sudo edit /etc/init.d/autovpn
sudo chmod +x /etc/init.d/autovpn
sudo update-rc.d autovpn defaults

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment