You can retrieve keychain items using security(1). On my old PowerBook, I was using

$ security find-internet-password -s mail.antiflux.org -r imap \
-g 2>&1 >/dev/null | cut -d\" -f2

On my new MacBook that stopped working. Debugging it was a little annoying because security only returns the first match. I thought it was something specific to the imap protocol… maybe Mail.app had to do some magic first.

Eventually I changed the server name to “mail2” so I could see what it was returning. It turns out that the protocol isn’t a regular string at all. It’s more like a four-character creator code, stored as an int. And on an Intel chip it’s reversed: pami.

security seems to have all kinds of endian trouble:

$ security find-internet-password -r pami -s mail.antiflux.org
    keychain: "/Users/grant/Library/Keychains/login.keychain"
    class: "teni"
    attributes:
        0x07000000 <blob>="mail.antiflux.org"
        0x08000000 <blob>=<NULL>
        "tcca"<blob>="grant"
        "pyta"<blob>="dflt"
        "tadc"<timedate>=0x32303036313130323136313732305A00  "20061102161720Z\000"
        "rtrc"<uint32>="lpaa"
        "isuc"<sint32>=<NULL>
        "csed"<blob>=<NULL>
        "tmci"<blob>=<NULL>
        "ivni"<sint32>=<NULL>
        "tadm"<timedate>=0x32303036313130333137353535305A00  "20061103175550Z\000"
        "agen"<sint32>=<NULL>
        "htap"<blob>=<NULL>
        "trop"<uint32>=0x00000000 
        "torp"<blob>=<NULL>
        "lctp"<uint32>="pami"
        "prcs"<sint32>=<NULL>
        "nmds"<blob>=<NULL>
        "rvrs"<blob>="mail.antiflux.org"
        "epyt"<uint32>=<NULL>

New command:

$ security find-internet-password -s mail.antiflux.org -r pami \
-g 2>&1 >/dev/null | cut -d\" -f2
3 November 2006
os10