Skip to content

Instantly share code, notes, and snippets.

@npodonnell
Created July 18, 2022 03:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save npodonnell/52ef6c3d46c9323858bad759d4d20fcc to your computer and use it in GitHub Desktop.
Save npodonnell/52ef6c3d46c9323858bad759d4d20fcc to your computer and use it in GitHub Desktop.
Wireguard switcher
#!/usr/bin/env bash
#
# Switch between Wireguard tunnels located in /etc/wireguard/
# Each tunnel should be defined with a config file, eg. wg0.conf
#
# N. P. O'Donnell, 2022
if [[ $# -ne 1 ]]; then
echo "Usage: $0 [OPTIONS] [<new tunnel>]"
echo
echo "Options:"
echo " -l: list available tunnels and show active tunnel"
echo " -s: stop running tunnel"
exit 1
fi
old_vpn=$(sudo wg | head -n1 | cut -d" " -f2)
if [[ $1 = "-l" ]]; then
sudo ls -1 /etc/wireguard/*.conf | sed "s/.*\/\([^\/]*\).conf/\1/"
echo -n "Active: "
if [[ -n $old_vpn ]]; then
echo $old_vpn
else
echo "<none>"
fi
exit 0
fi
if [[ $1 = "-s" ]]; then
sudo systemctl stop wg-quick@$old_vpn
exit 0
fi
new_vpn=$1
if [[ -z $(sudo ls -1 /etc/wireguard | grep $new_vpn.conf) ]]; then
echo "No such VPN: $new_vpn"
exit 1
fi
# Start new VPN before stopping the old one so there's no downtime.
sudo systemctl enable wg-quick@$new_vpn
sudo systemctl start wg-quick@$new_vpn
if [[ -n $old_vpn ]]; then
sudo systemctl stop wg-quick@$old_vpn
sudo systemctl disable wg-quick@$old_vpn
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment