Access OS X keychain from Terminal

At everyday scripting, you often need to access sensible information like passwords. A common practice is to just write them plain text into your script, but at least on a Mac, we can do better.

OS X ships with a tool called keychain. It is a central database where tools can store sensitive information like logins. Luckily, it is accessible from shell scripts with the command line utility security.

Let’s say you want to securely access an FTP server’s username and password. First of all, add a new Internet password to your keychain. To do so, just fire it up, select New password and enter the credentials. Remember to add the prefix http:// or ftp:// to your service name to create an Internet password.

Now you read the username like this from the command line

security find-internet-password -s ftp.home.com | grep "acct" | cut -d '"' -f 4

The service is what you entered in keychain, but without the prefix. And finally your password

security 2>&1 >/dev/null find-internet-password -gs ftp.home.com | cut -d '"' -f 2
That’s all. No more plain text passwords in your script.

8 thoughts on “Access OS X keychain from Terminal

  1. Googled “os x keychain terminal” and BAM – found your blog Maclovin. Thanks for this!

    Was just wondering though.., when retrieving the password through the graphical “Keychain Access” application I have to type in my user password. Yet when I retrieve it through the terminal I am not prompted for a password (I just get a “security wants to use your info…” accept prompt).

    Doesn’t that seem slightly silly to you? As far as I can see if someone physically takes my laptop and I don’t manage to lock it – he can extract all my keychain passwords through the security terminal app even if he doesn’t know my pw.

  2. Right.. doesn’t seem as bad as it looks. I locked the login keychain and tried the security terminal command again – this time was asked for my user password.

    Looks like PW is required only once, then the “security” tool can grab as many passwords as it pleases.

  3. Pingback: Fetch Keychain credentials from Ant « Can’t see nothing but the source code

  4. Thanks this is great!. I am using this for all my projects now (local environments), my amazon db passwords dont have to be in a config file anymore. Just one thing, on OS X lion this still prompts the user to confirm access to keychain by clicking on an “allow” button. Is there a way to disable that? or pass a switch/param that confirms it from terminal/script itself??

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>