'macOS: retrieve keychain's item's password and username with `security find-internet-password`
I would like to retrieve my appstoreconnect.apple.com username and password from macOS Keychain, to write a script with those credentials afterwards.
When I type security find-internet-password -s "appstoreconnect.apple.com" -g i get
keychain: "/Users/me/Library/Keychains/login.keychain-db"
version: 512
class: "inet"
attributes:
0x00000007 <blob>="appstoreconnect.apple.com"
0x00000008 <blob>=<NULL>
"acct"<blob>="my-username"
"atyp"<blob>="dflt"
"cdat"<timedate>=0x32303230303731363133343131315A00 "20200716134111Z\000"
"crtr"<uint32>=<NULL>
"cusi"<sint32>=<NULL>
"desc"<blob>=<NULL>
"icmt"<blob>=<NULL>
"invi"<sint32>=<NULL>
"mdat"<timedate>=0x32303230303731363133343533395A00 "20200716134539Z\000"
"nega"<sint32>=<NULL>
"path"<blob>="/"
"port"<uint32>=0x00000000
"prot"<blob>=<NULL>
"ptcl"<uint32>="htps"
"scrp"<sint32>=<NULL>
"sdmn"<blob>=<NULL>
"srvr"<blob>="appstoreconnect.apple.com"
"type"<uint32>=<NULL>
password: "my-password"
how, from that, can I retrieve my-username and my-password values, to use as variables in my shell script ?
Solution 1:[1]
try
security find-internet-password -s "appstoreconnect.apple.com" -g | grep -E "acct|password" | rev | cut -d'"' -f2 | rev
Solution 2:[2]
Use this:
security find-internet-password -s 'appstoreconnect.apple.com' -g 2>&1 | grep -E 'acct|password' | sed 's/^ *//' | sort | rev | cut -d'"' -f2 | rev
An important thing to note is the security CLI returns the account name on stdout, but the password on stderr. By adding 2>&1, all stderr output will be redirected to stdout. Then both outputs will be passed along to the next command in the pipeline.
I removed the leading spaces in case it affects the sorting. The sorting makes the account name appear before the password.
I'm not totally satisfied with the output processing here. Using rev a couple of times and treating quotes as delimiters feels kludgy. This is good enough for the moment, I guess. (Because it meets my immediate needs. ?) I will update this later.
It'd be so helpful if macOS would print the account name and password without requiring all this trickery.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Digvijay S |
| Solution 2 | Mr. Lance E Sloan |
