Skip to content

Instantly share code, notes, and snippets.

@nealfennimore
Created October 6, 2019 04:13
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 nealfennimore/a391dff9c5b04a26a1751e1a2981a026 to your computer and use it in GitHub Desktop.
Save nealfennimore/a391dff9c5b04a26a1751e1a2981a026 to your computer and use it in GitHub Desktop.
Toggle VPNs
#!/usr/bin/env bash
IFS=$'\n'
VPNS=($(nmcli con | grep vpn))
UUID_REGEX="^.*\(\w\{8\}.*\w\{12\}\).*$"
is_active_vpn() {
row=$(nmcli con | grep $1 | sed 's/\s*$//g' ) # Trim whitespace so we can test ending column
if [[ $row =~ ^.*--$ ]]; then
echo -n 0
else
echo -n 1
fi
}
toggle_vpn() {
active=$(is_active_vpn $1)
if [ $active = 1 ]; then
stop_vpn $1
else
start_vpn $1
fi
}
start_vpn() {
echo "Starting VPN..."
nmcli con up $1
}
stop_vpn() {
echo "Stopping VPN..."
nmcli con down $1
}
PS3='Please enter your choice: '
# allow the user to choose a vpn
select vpn in "${VPNS[@]}"
do
# leave the loop if the user says 'stop'
if [[ "$REPLY" == stop ]]; then break; fi
# complain if no vpn was selected, and loop to ask again
if [[ "$vpn" == "" ]]
then
echo "'$REPLY' is not a valid number"
continue
fi
# toggle the vpn by uuid
uuid=$(echo $vpn | sed -n "s/$UUID_REGEX/\1/p")
toggle_vpn $uuid
break
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment