How to fetch an AirPort/Wi-Fi password using /usr/bin/security

I have been trying to use /usr/bin/security rather than hard coding login/password information into scripts. For example, here's how you get the password for 'pinboard.in'

security 2>&1 >/dev/null find-internet-password -gs pinboard.in |\
grep '^password: ' |\
sed 's#^password: "##g ; s#"$##'

(Note: Someone who is better at grep/awk can probably combine those last two lines, just be sure to consider for when a password may have a " in it — or a space.)

What I can't do is figure out how to retrieve the password for a Wi-Fi network if all I know is the SSID.

I have even tried specifying the kind of data I am looking for with -D:

security 2>&1 >/dev/null find-generic-password -D "AirPort network password" -s MySSIDhere

but all I get is this

security: SecKeychainSearchCopyNext: The specified item could not be found in the keychain.

All I have found via Google has been about adding SSID password information on the CLI, but I want to retrieve it.


Solution 1:

I got my password with

security find-generic-password -D "AirPort network password" -a YourSSIDhere -g

Main difference is -a SSID. I found that in which field it was stored by letting security take a dump:

security dump-keychain