Bash – Sudo-like remembrance of passwords for own scripts

bashpasswordpython

I have a script which requires a password for authenticating a web service. A single password for a pre-defined user will suffice, and the password should if possible be stored securely (not plain text).

Obviously I don't want to write the password in clear text in the script for security reasons, so I have the script ask me the password, but entering the password every single time is a drag.

So how can I make it so I don't have to enter the password every time I run the script (like sudo)?

The script in this particular case is Python, but I guess it's better to implement it as a generic solution in Bash, so it can be reused for different languages like PHP or Ruby.

Pseudo-code:

#!/bin/bash
pw = cache.load() or {
  pw = ask_user()
  cache.save(pw, 15min)
}
myscript.py pw

Best Answer

Don't reinvent your own password store. Use an existing one. The Linux world has mostly converged on GNOME Keyring. Seahorse provides a convenient GUI for exploring and modifying the keyring and setting a master password. The keyring can be queried from the command line with the secret-tool utility.

secret-tool store --label='Foobar webservice' service foobar account bob
pw=$(secret-tool lookup service foobar account bob)

The password in the store doesn't expire automatically, but the permission to access the store can.

Related Question