All posts by David van Enckevort

Even though I'm a Classical Archaeologist by education I work as a Scientific Programmer and Project Leader for the Netherlands Bioinformatics Center (NBIC).

Keeping passwords secure when scripting

Automation of system tasks is an important tool to make your live easier. However, for many tasks require you to login to systems. You often see that people hardcode passwords in scripts and I have done so far too many times as well. However this is far from ideal and poses risks of leaking passwords.

Luckily macOS offers a solution that allows you to retrieve passwords stored in Keychain in your scripts.

Creating a new password

The first step is to create a new password entry in your keychain. You can do so on the command line with the following command (one long line):

security add-internet-password -a username -s https://www.example.com/ -w

This will command will ask you for a new password and then store the account name and password in your keychain. If the keychain is locked it will prompt you for your password.

Alternatively you can create your new password by opening Keychain Access.app and adding a new entry there.

Reading a password

To read your password on the command line you can use the security command as well (one long line)

security find-internet-password -a admin -s https://www.example.com/ -w

You can use this in your scripts to fill in your password in a variable:

#/bin/bash -e
password=$(security find-internet-password -a admin -s https://www.example.com/ -w)

curl -u "admin:${password}" http://www.example.com/

Conclusions

The combination of keychain with the security tool make it easy to move your passwords out of your scripts into a secure location, with the added benefit that you don’t have your password duplicated in many locations, which makes it easier to change the password when necessary.