Category Archives: HOWTO

Articles that describe in a concise manner how to achieve a certain objective. E.g. how to install some software or how to configure software to do X or Y.

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 -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 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 -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 -w)

curl -u "admin:${password}"


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.