Shell script to get wifi password in macOS

2019-11-05

macOS uses the BSD security command to access information from the system keychain. With this command you can access all the same information which is normally stored in Keychain Access.app and more. I wrote a script which prints the WiFi password for either the current network, or a specified network to the terminal. This was mostly an exercise for me to learn how getopts works.

The script is below:

#!/bin/bash

ssid=$(/System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources/airport -I | grep " SSID:" | awk -F': ' '{print $2}')

while getopts ":n:" opt; do
	case $opt in 
		n)
			# If flag is given with argument
			ssid="$OPTARG"
			;;
		\?)
			# If incorrect flag given
			echo "-$OPTARG is not a valid option" >&2
			exit 1
			;;
		:)
			# If flag is given without argument
			echo "-$OPTARG requires an argument" >&2
			exit 1
			;;
	esac
done

security find-generic-password -wga "$ssid"

If I run ./wifi.sh -n SSID the script will look for a network with the SSID SSID then return its password. If I run ./wifi.sh -n I will get the response: -n requires an argument. If I run ./wifi.sh -a I will get the response: -a is not a valid option. If I run ./wifi.sh I will get the password for the WiFi network I am currently attached to.