Last active
August 27, 2023 07:16
-
-
Save MParvin/3af8906f3d6f1c1c7484d5a75c85cccc to your computer and use it in GitHub Desktop.
Ubuntu CLI VPN manager
This file contains hidden or 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
#!/bin/bash | |
function check_status { | |
# $1 is VPN name | |
vpnName=$1 | |
vpnIP=`nmcli connection show $vpnName | grep 'IP4.ADDRESS\[1\]' | awk '{print $2}' | cut -d'/' -f1` | |
vpnGateway=`nmcli connection show $vpnName | grep IP4.GATEWAY | awk '{print $2}'` | |
if [ "$vpnGateway" == "--" ] | |
then | |
vpnGateway=`echo $vpnIP | sed 's/\.[0-9]\{1,3\}$/\.1/'` | |
fi | |
interfaceName=`ifconfig | grep -w "$vpnIP" -B 1 | head -1 | awk '{print $1}' | cut -d':' -f1 ` | |
pingStatus`ping -c1 -I $interfaceName -W3 $vpnGateway 2>&1 >/dev/null;echo $?` | |
return $pingStatus | |
} | |
# Usage is manage_vpns.sh <connection_name> | |
if [ -z "$1" ]; then | |
show_help | |
exit 1 | |
fi | |
# Show help function | |
function show_help { | |
echo " | |
Usage: manage_vpns.sh <connection_name> | |
This will toggle the VPN connection with the given name." | |
} | |
function enable_vpn { | |
# Enable the one we want to enable | |
nmcli connection up "$1" | |
} | |
function disable_vpn { | |
nmcli connection down "$1" | |
} | |
# Run notify-send and show running VPN connection if -s is passed | |
if [ "$1" == "-s" ]; then | |
wifi_name=`nmcli connection show | grep wifi | grep -v '\-\-' | awk '{print $1}'` | |
vpns=$(nmcli connection show --active | grep vpn | awk '{print $1}') | |
if [ -z "$vpns" ]; then | |
message="No VPN connection is running" | |
else | |
for vpn in $vpns | |
do | |
vpns_statuses+="$vpn is connected\n" | |
done | |
# notify-send "VPN" "VPN connection is running: $vpns" | |
message="VPN Statuses:\n $vpns_statuses" | |
fi | |
notify-send -t 1000 "Network status" "Wifi: $wifi_name \n\n\n$message" | |
exit 0 | |
fi | |
# Check if the connection is already running | |
if [ "$(nmcli connection show $1 | grep -c "activated")" -eq 1 ]; then | |
echo "Disabling $1" | |
# If it is, deactivate it | |
disable_vpn $1 | |
else | |
# If it isn't, activate it | |
enable_vpn $1 | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment