Shell script to get wifi password in macOS


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 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:


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 
			# If flag is given with argument
			# 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

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

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