Skip to content

Instantly share code, notes, and snippets.

@groundcat
Last active February 9, 2023 01:31
Show Gist options
  • Select an option

  • Save groundcat/9ea50acf1b42a51531239a701d569149 to your computer and use it in GitHub Desktop.

Select an option

Save groundcat/9ea50acf1b42a51531239a701d569149 to your computer and use it in GitHub Desktop.
WireGuard auto control script

Setting up a WireGuard VPN Script on Ubuntu

Prerequisites:

  • Ubuntu system with WireGuard installed and configured

  • Root access to your Ubuntu system

Create a new file with your favorite text editor, for example:

sudo nano ~/wg_auto_toggle.sh

Paste the following code into the file and save it.

sudo chmod +x ~/wg_auto_toggle.sh

Now, every time you run the script, it will automatically detect the status of your VPN and toggle it on or off as needed. You can run the script by executing:

sudo bash ~/wg.sh
#!/bin/bash
VPN_CONFIG="example" # this is your wg config file name in /etc/wireguard
VPN_UP=0
# Function to check if VPN is up
check_vpn_status() {
if ip link show "$VPN_CONFIG" | grep -q UP; then
VPN_UP=1
else
VPN_UP=0
fi
}
# Function to toggle VPN
toggle_vpn() {
check_vpn_status
if [ $VPN_UP -eq 1 ]; then
sudo wg-quick down $VPN_CONFIG
echo "VPN turned off."
else
sudo wg-quick up $VPN_CONFIG
if [ $? -eq 0 ]; then
echo "VPN turned on."
sleep 5
if curl --silent --head http://clients1.google.com/generate_204 | head -n 1 | grep -q "204"; then
echo "VPN is working properly."
else
echo "VPN is not working properly."
fi
else
echo "VPN is already up."
fi
fi
echo "Your IPv4 address: $(curl -s ipv4.ip.sb)"
echo "Your IPv6 address: $(curl -s ipv6.ip.sb)"
echo "Your DNS servers:"
grep nameserver /etc/resolv.conf | awk '{print $2}'
}
# Main
echo "nameserver 45.90.28.53" | sudo tee /etc/resolv.conf > /dev/null
toggle_vpn
echo "Press any key to exit..."
read -n 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment