I followed the docs and wrote:
require 'rubygems'
require 'appscript'
loginKeychain = Appscript::app('Keychain Scripting').keychains['login.keychain']
userName = loginKeychain.keys[its.name.eq(name)].password.get
UPDATE: if I run the script via Terminal, it succeeds the first time, and then returns the error below until I quit and restart Terminal; and repeat...
Error returned intermittently:
/Library/Ruby/Gems/1.8/gems/rb-appscript-0.5.3/lib/appscript.rb:539:in `_send_command': CommandError (Appscript::CommandError)
OSERROR: -600
MESSAGE: Application isn't running.
COMMAND: app("/System/Library/ScriptingAdditions/Keychain Scripting.app").keychains["login.keychain"].keys[its.name.eq("a name")].password.get()
UPDATE 2: Due to the mysterious error, and that Keychain Scripting seems buggy in general, I decided to use MacRuby. I found the MacRuby Keychain Wrapper library, which calls Keychain Services directly, rather than going through Scripting:
require 'keychain-wrapper/keychain'
MRKeychain::GenericItem.item_for_service(service_name).password
- Easy
- More efficient
- Works flawlessly
Done.
I didn't use Ruby but I used Python and I have no trouble. I'd try doing regular Applescript and seeing if it can access Keychain Scripting. If not then try rebooting your Mac. But this sounds like more a problem of your computer than Appscript.