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

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.
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.
Handy tip. Thanks a bunch!
To protect the keychain automatically, goto edit -> settings (for the chosen keychain), and set locking options.