Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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