Keychain Access from a Shell.sh Script

Jan 17, 2007

Here’s a useful snippet to enable you to securely store passwords in OS X’s keychain and use them in a shell script.

#!/bin/bash 
PASSWORD=\`exec osascript <<EOF | tr "\\r" "\\n"
    
 (\* 
     To use the Keychain to store the admin password then 
     
     Open /Applications/Utilities/Keychain Access.app
     Add a new keychain called "TM" 
     Add a Key with the name "test" and store your password in it.
     
     I'd recommend learning how keychains work then tailoring 
     the process to your security needs.
    \*)

 tell application "Keychain Scripting"
        set myKeyChain to keychain "TM.keychain"
        set theKeyList to every key of myKeyChain
        set thePassword to ""
        repeat with x from 1 to (length of theKeyList)
            set theKey to item x of theKeyList
            if the name of theKey is "test" then
                set thePassword to password of theKey
                \--exit repeat leaves us without 
                \--a value returned to the shell script...
            end if
        end repeat
    end tell
    
EOF\`

echo "$PASSWORD"

exit 0;

Download: Update: As of Leopard it is now possible to do this via the command line tool security