Last active
May 12, 2024 22:49
-
-
Save eric-glb/0ca5b65875ec0fb0e57151d424372dee to your computer and use it in GitHub Desktop.
Wireguard: script to enable / disable VPN connection from CLI
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
export LC_ALL=C | |
CLEAR="\e[0;m" | |
RED="\e[1;31m" | |
GREEN="\e[1;32m" | |
YELLOW="\e[1;33m" | |
UP="\e[1A" # Move cursor one line up | |
CL="\r$(printf %$(tput cols)s)\r" # Clear line | |
wg-status(){ | |
local CONNECTIONS=$@ | |
echo "" | |
for i in $CONNECTIONS; do | |
ip ad sh dev $i &>/dev/null \ | |
&& printf "[${YELLOW}%-4s${CLEAR}] ${GREEN}UP${CLEAR}\n" $i \ | |
|| printf "[${YELLOW}%-4s${CLEAR}] ${RED}DOWN${CLEAR}\n" $i | |
done | |
echo -en "\nExternal IP: " | |
external_ip | |
echo "" | |
} | |
external_ip() { | |
local urls=( icanhazip.com ifconfig.me ipquail.com | |
ipinfo.io/ip ip.me wtfismyip.com/text | |
myip.wtf/text ifconfig.io checkip.amazonaws.com | |
api.ipify.org ifconfig.co ) | |
local url=${urls[ $RANDOM % ${#urls[@]} ]} | |
local ip=$(curl -sL $url) | |
grep -q -- "-v" <<<"$*" && echo "$url: $ip" || echo "$ip" | |
} | |
#-[ Main ]--------------------------------------------------------------------- | |
PARAM=$1 | |
CONNECTIONS="$(ls /etc/wireguard/ | grep '.conf$' | sed 's!\.conf!!')" | |
if [ -z "$PARAM" ] && type -p gum &>/dev/null; then | |
wg-status "$CONNECTIONS" | |
echo -e "Start/stop VPN:" | |
PARAM=$(echo $CONNECTIONS | tr " " "\n" | gum choose) | |
echo -en "${UP}${CL}${UP}" | |
fi | |
if [ -z "$PARAM" ]; then | |
echo -e "\n${YELLOW}No parameter. Abort.${CLEAR}" | |
wg-status "$CONNECTIONS" | |
exit 0 | |
fi | |
if ! grep -q "^${PARAM}$" <<<"$CONNECTIONS"; then | |
echo -e "\n${YELLOW}Unknown connection '${RED}$PARAM${YELLOW}'. Abort.${CLEAR}" | |
wg-status "$CONNECTIONS" | |
exit 1 | |
fi | |
if ip ad sh dev ${PARAM} &>/dev/null; then | |
echo -en "\nStopping $PARAM... " | |
wg-quick down "${PARAM}" &>/dev/null | |
if [ $? -eq 0 ]; then | |
echo -e "${GREEN}OK${CLEAR}" | |
else | |
echo -e "${RED}KO${CLEAR}" | |
fi | |
else | |
echo -en "\nStarting $PARAM... " | |
wg-quick up "${PARAM}" &>/dev/null | |
if [ $? -eq 0 ]; then | |
echo -e "${GREEN}OK${CLEAR}" | |
else | |
echo -e "${RED}KO${CLEAR}" | |
fi | |
fi | |
wg-status "$CONNECTIONS" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment