Skip to content

Instantly share code, notes, and snippets.

@ConnerWill
Created November 7, 2023 16:11
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 ConnerWill/0013064b04494c891d217b9edc0a2523 to your computer and use it in GitHub Desktop.
Save ConnerWill/0013064b04494c891d217b9edc0a2523 to your computer and use it in GitHub Desktop.
Script to connect to Wireguard VPN
#!/usr/bin/env bash
die() {
echo "[-] Error: $1" >&2
exit 1
}
PROGRAM="${0##*/}"
ARGS=( "$@" )
SELF="${BASH_SOURCE[0]}"
[[ $SELF == */* ]] || SELF="./$SELF"
SELF="$(cd "${SELF%/*}" && pwd -P)/${SELF##*/}"
[[ ${BASH_VERSINFO[0]} -ge 4 ]] || die "bash ${BASH_VERSINFO[0]} detected, when bash 4+ required"
[[ $UID == 0 ]] || exec sudo -p "[?] $PROGRAM must be run as root. Please enter the password for %u to continue: " -- "$BASH" -- "$SELF" "${ARGS[@]}"
type wg-quick >/dev/null || die "Please install wireguard (wg-quick) and then try again."
type curl >/dev/null || die "Please install curl and then try again."
set -e
VPN_PROFILE_NAME="br-sao-wg-201"
CONNECTED_TEST_URL="https://am.i.mullvad.net/connected"
WG_DIR="/etc/wireguard"
PREVPWD="$(pwd)"
cd "${WG_DIR}" || die "Unable to cd to ${WG_DIR}"
[[ -f "${WG_DIR}/${VPN_PROFILE_NAME}.conf" ]] || die "Unable to find Wireguard VPN profile: ${VPN_PROFILE_NAME} at ${WG_DIR}/${VPN_PROFILE_NAME}.conf"
while [[ $# -gt 0 ]]; do
key="$1"
case $key in
-c|--connect)
sudo wg-quick up "${VPN_PROFILE_NAME}" || die "Unable to connect to VPN: ${VPN_PROFILE_NAME}"
shouldtest=1
;;
-d|--disconnect)
sudo wg-quick down "${VPN_PROFILE_NAME}" || die "Unable to disconnect to VPN: ${VPN_PROFILE_NAME}"
;;
-t|--test)
shouldtest=1
;;
*)
# Default case: unknown option
die "Unknown option: $key Options: [-c|--connect] [-d|--disconnect] [-t|--test]"
;;
esac
shift
done
if [[ -z "${shouldtest}" ]]; then
printf "Not testing connection\n"
else
curl "${CONNECTED_TEST_URL}" || die "Unable to test if you are connected to the VPN. Try running this command again: curl https://am.i.mullvad.net/connected"
fi
cd "${PREVPWD}" || die "Unable to cd to previous directory: ${PREVPWD}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment