Skip to content

Instantly share code, notes, and snippets.

@codyopel
Created April 30, 2015 05:48
Show Gist options
  • Save codyopel/261838e14bdbfd9b65c6 to your computer and use it in GitHub Desktop.
Save codyopel/261838e14bdbfd9b65c6 to your computer and use it in GitHub Desktop.
#!/usr/bin/env sh
# Currently only works with single wireless card (picks first one found)
wireless_interface() { # Find wireless interface name
nmcli d | awk '/802-11-wireless/ {print $1}'
}
wifi_usage() {
cat <<EOF
Wifi is a wrapper for nmcli.
Usage: pkg UTILITY [OPTIONS]
list - List available wireless connections
connections - List saved connections
add - Add a new connection
connect - Connect to a saved connection
disconnect - Disconnect all active connections
status - List active connections
on - Turn wireless on
off - Turn wireless off
-h|--help - print this message
EOF
return 0
}
path_hasbin() { # Test to see if a binary exists in the path
[ "$#" -ne "1" ] && return 2
type $1 > /dev/null 2>&1 || { echo " '$1' not installed" ; return 1 ; }
}
wifi() {
path_hasbin nmcli || return 1
case "$1" in
'list') # List saved connections
nmcli d wifi list
;;
'connections')
nmcli c
;;
'add') # Add a saved connection
shift
ssidWifi="$1"
passwordWifi="$2"
# If no password is provided, assume one is not needed
if [ -z "$passwordWifi" ]; then
passwordWifi=""
else
passwordWifi="password $2"
fi
# Add connection
nmcli d wifi connect "$ssidWifi" $passwordWifi iface "$(wireless_interface)" name "$ssidWifi" || \
{ echo "ERROR: failed to connect to $ssidWifi" ; return 1 ; }
;;
'connect') # Connect to a saved connection
shift
ssidWifi="$1"
nmcli c up id "$ssidWifi"
;;
'disconnect') # Disconnect from current wireless network
nmcli d disconnect iface $(wireless_interface)
;;
'remove') # Remove a saved connection
shift
ssidWifi="$1"
nmcli c delete id "$ssidWifi"
;;
'status') # List active connections if any
nmcli c status
;;
'on') # Turn wireless on
nmcli nm wifi on
;;
'off') # Turn wireless off
nmcli nm wifi off
;;
'-h'|'--help'|'help')
wifi_usage
;;
*)
wifi_usage
echo "ERROR: invalid option: $@"
;;
esac
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment