Instantly share code, notes, and snippets.

What would you like to do?

Safe-keeping passwords used in ad-hoc scripts

When I need to send small batches of customized emails, I use Craig Kerstiens' and Will Leinweber's Ruby trick.

I've added an additional small hack to this trick that I've used several times: Storing and retrieving passwords in the Mac OSX keychain with minimal pain.

If you read through Craig's post and the code, you'll see that you need to pass in your GMail password. I care deeply about protecting access to my GMail account, so I don't just paste passwords into code or other random files stored on my hard drive. To keep things as secure as possible, I do the following:

  • Turn on two-factor for GMail
  • Now you cannot use your primary password for scripts like this. Instead I generate a per-application password. (click on "App passwords" on Security settings).
  • I store my password in the Mac OSX keychain, by manually opening it up and creating a new entry:

  • I create a small shell script that pulls the password into a local environment variable:
export EMAIL_PASSWORD=$(security find-generic-password -a gmail -gw)
  • Before I run the email script, I now simply need to run:
$ .

It'll pop up a dialog box asking if this script can access your keychain, and you simply have to click "Allow". I don't click "Always Allow" because that would always allow the program security to access your keychain and not just this script and it sort of defies the purpose of per-application approvals.

If you're worried about the password sitting in an environment variable, you can hack the Ruby script to execute the security command directly. But at this point we're getting close to security theatre.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment