Skip to content

Instantly share code, notes, and snippets.

@gsomoza
Last active September 28, 2020 04:17
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gsomoza/662ccfe13d628ec0a6ae0f858a5d99dc to your computer and use it in GitHub Desktop.
Save gsomoza/662ccfe13d628ec0a6ae0f858a5d99dc to your computer and use it in GitHub Desktop.
ZeroTier VPN Switch Script
#!/bin/bash
ZT_NETWORK="NETWORK_ID"
# colors
RCol='\033[0m' # Text Reset
LGra='\033[0;37m';
Red='\033[0;31m';
Gre='\033[0;32m';
Yel='\033[0;33m';
display_usage() {
echo -e "\nThis script enables / disables the ZeroTier gateway for this device on network $ZT_NETWORK \n\n"
echo -e "Usage:\n $0 <command> | --help\n"
echo -e "Commands:\n"
echo -e " (e)nable\tEnables the VPN functionality\n"
echo -e " (d)isable\tDisables the VPN functionality\n"
echo -e " (s)tatus\tShows the status of the VPN network\n"
}
# check if the zerotier-cli binary is installed
command -v zerotier-cli >/dev/null 2>&1 || \
{ echo -e >&2 "This script requires ${Yel}zerotier-cli${RCol} to run, but it's not installed. Aborting."; \
echo -e >&2 "You can install ZeroTier One by running:\n ${LGra}curl -s https://install.zerotier.com/ | bash${RCol}";
exit 2;
}
# ask for the network ID the user wants to join
if [ $ZT_NETWORK == "NETWORK_ID" ]; then
echo -e "You haven't configured a ZeroTier network for this script yet."
while true; do
read -p "Please enter the network ID you whish to use: " ZT_NETWORK
if [ -z $ZT_NETWORK ]
then true;
else
break
fi;
done
echo -en "\nTo avoid being asked this again in the future, please edit this cript by setting the "
echo -e "ZT_NETWORK variable to your desired network ID.\n"
fi
# check if we're connected to the correct ZT network
if zerotier-cli listnetworks | grep -Fq $ZT_NETWORK
then true # we're connected - so do nothing, just here for portability
else
echo -e >&2 "Oops! Looks like you're not connected to network ${Gre}$ZT_NETWORK${RCol}"
echo -e >&2 "Please connect first by running:"
echo -e >&2 " ${LGra}zerotier-cli join $ZT_NETWORK${RCol}"
exit 3
fi
# validate arguments
while [[ $# -gt 0 ]]
do
key="$1"
case $key in
e|enable|-e|--enable)
ZT_ALLOW=1
shift # past argument
;;
d|disable|-d|--disable)
ZT_ALLOW=0
shift # past argument
;;
s|status|-s|--status)
zerotier-cli /network/$ZT_NETWORK
exit 0
shift
;;
*)
display_usage # unknown option
exit 1
;;
esac
shift # past argument or value
done
if [ -z $ZT_ALLOW ]; then
display_usage
exit 1
fi
# enable / disable allowGlobal and allowDefault
zerotier-cli set $ZT_NETWORK allowGlobal=$ZT_ALLOW &> /dev/null
zerotier-cli set $ZT_NETWORK allowDefault=$ZT_ALLOW &> /dev/null
# show informative output
if [ $ZT_ALLOW -eq 0 ] || [ -z $ZT_ALLOW ]
then VERB="DISABLED"
else VERB="ENABLED"
fi
echo -e "The ZeroTier VPN was successfuly $VERB"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment