I am trying to write a script which automatically connects to vpn (purevpn)(it automatically connects to the fastest available server, therefore i can't allow a specific IP for ufw because it always connects to different Servers/ IPs) and also enables an internet kill switch. Heres my script:


sudo ufw disable

disconnect and reconnect to vpn

purevpn -d

purevpn -c

sudo ufw --force reset

sudo ufw default deny incoming

sudo ufw default deny outgoing

sudo ufw allow out on tun0 from any to any

sudo ufw enable

(The fat lines are actually comments in the script)

Unfortunately the script doesn't always work. Sometimes it works fine, meaning that it connects to vpn and enables the kill switch so I can browse but once I disconnect from vpn sites can't load - as it's wanted. However sometimes after running the script when I then afterwards try to google something it shows that it's loading (anticklockwise circle in chrome) but never shows any progress. I can't quite find a regularity in when it works and when not. Any ideas?


You may have to add a line like

sudo ufw allow out from any to

to your script just before the "enable", where "" is the IP of the VPN server you're connected to. At least that's how the script I'm using works. Unfortunately that does not make it independent from the server you're currently connected to, but I don't see a way around that.

  • I think my original source for the script is here: gist.github.com/Necklaces/18b68e80bf929ef99312b2d90d0cded2 which may also explain why it sometimes works and sometimes not. – Sebastian Dec 30 '18 at 15:40
  • Thanks, I'll try that later. Maybe I can find a way to store the IP of the server I'm connected to somewhere to then let it automatically be filled into your line. I'll give an update later. – user10445763 Dec 30 '18 at 15:55
  • Sorry for the late reply but better now than never. I downgraded to 16.04 but it still didnt work so I downgraded further to 14.04. Now in 14.04 the script above works perfectly fine. – user10445763 Feb 8 at 15:22
  • I don't think downgrading to a 5 year old distribution is really the way to go, but it's your call. – Sebastian Feb 8 at 20:47
  • Yeah I see what you mean, but there was no way for me getting it to work on 18.04. Still got no idea why though. – user10445763 Feb 10 at 9:22

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.