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

$ security find-internet-password -s -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 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
    keychain: "/Users/grant/Library/Keychains/login.keychain"
    class: "teni"
        0x07000000 <blob>=""
        0x08000000 <blob>=<NULL>
        "tadc"<timedate>=0x32303036313130323136313732305A00  "20061102161720Z\000"
        "tadm"<timedate>=0x32303036313130333137353535305A00  "20061103175550Z\000"

New command:

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