9

Looking into using the command line tool for KeyChain. I am able to do a lot of the things through security; listing my multiple keychains, dumping them and setting defaults. Reading through tutorials and other postings I expect to find my passwords with

security find-generic-password test

But I get

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

This won't work in my default keychain or login.keychain. However, I am able to find my passwords listed as 'internet' with find-internet-password command. Can anyone explain why or what I am doing wrong? Sites I've been reading is the man page and http://blog.macromates.com/2006/keychain-access-from-shell/,

1
  • One minor issue I ran into with find-generic-password: if the service name (-s parameter) contains a period ('.') ('example.com', for example), I can run add-generic-password successfully but can't find the value with find-generic-password. Apr 19, 2022 at 22:17

2 Answers 2

15

Generic passwords are identified by their Service and Account attributes. For example, to search for a password for account "bar" of the "foo" service, use

security find-generic-password -a foo -s bar -g

The -g option displays the value of the password at the end of the output.

The combination of service and account is guaranteed to uniquely identify a particular password. Other queries (comment, label, etc.) are possible, but they may match multiple passwords. find-generic-password displays only the first single matching item, which limits its usefulness for such queries.

3
  • What is the "Service" attribute? I don't see that label anywhere in the Keychain Access app on macOS Mojave 10.14.4. The metadata I see are "Name", "Kind", "Account", "Where", and "Comments". (I tried the obvious guess here, "Name", but that does not work.) Apr 13, 2019 at 20:23
  • 2
    Keychain Access uses the "Where" label for the Service attribute. Apr 23, 2019 at 0:25
  • 1
    Isn't -s the service and -a the account? Seems they are inverted in the example. Feb 24, 2020 at 15:23
3

A more accurate and up to date answer would be to use -w instead of -g if you only need password. I've seen people using -g and parsing output using awk/perl to get the password field, which is not needed (anymore). All you need to do is:

security find-generic-password -a foo -s bar -w

You may use find-internet-password instead of find-generic-password command depending on where your password is stored in keychain.

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.