Use `security` to get the login username and password for use in shell scripts / cron

command linekeychainpasswordSecurity

I'd like to create a cron job that periodically pings an external resource and retrieves some information on my behalf, using my username and password that I logged in to the computer with.

I could hard-code the username and password into the script, but that is a bad practice.

I could use environment variables, but then I have to hard-code the username and password into a different script, which is still a bad practice.

I could create a keychain pair for use with this process, but then when my network password changes every few months, this process is likely to keep running with the wrong password and lock out my account.

My question is: What parameters can I give to the security command to retrieve the password that I used to log in to the machine?

Best Answer

I don’t believe that the Security framework keeps a two-way copy of your password. The best you could do is use a keychain pair as you’ve stated and then have your script check if that password is able to be locally authenticated before trying it over the network. That way at least you get an alert every few months to update your Keychain.