Store and Retrieve Keychain Passwords

It is generally better to use a tool like 1Password or LastPass for storing passwords for web sites, but for some situations (such as when logging in to the when site is just one step in the process, or when using it in places other than a web browser), entering passwords from Keyboard Maestro can be very handy. In this case, its best to store the passwords in the Keychain, rather than in the macro which has no security. Here is an example of two macros that store and then retrieve a Keychain password.


I use the sleep screen action and a set password to wake Applescript action when away from my home wifi network, but have macros actions that need to detect/select iTunes images on the screen during the night even when away.

Is it possible to use this feature to enter the password to unlock the screen after my action wakes the screen? I’ve used the password store actions, but I don’t quite understand how to enter the password from Keychain to unlock the screen.

Probably not. As a rule, while the screen is screen saving or screen locked you cannot use UI actions.

Actually, it can be done, with the proviso that no GUI actions can be used until the screen is awake.

I've developed a technique which works quite well, using shell, python and AppleScript commands, all within KM. This was scraped together using a variety of techniques found from various Internet sources.

The caffeinate command is at the heart of waking the system up such that it can respond to commands.

caffeinate -u -t 1

I use the SCREENSAVER() function to check whether the screen saver is running, or the display is sleeping or locked. Those are the three scenarios that must be considered in order to successfully awaken the screen and be able to perform GUI activity.

I've borrowed nearly every subroutine, whether AppleScript, Python or shell script in the attached file. I haven't given any credit either, but Nigel Garvey, and abarnert on are some of the sources, as I recall.

The upshot of the scripts:

The Python script gets the system values regarding whether the screen is locked and the time it was locked (epoch time, based on 1/1/1970). It also returns whether the current session is being run on the console (a non-GUI session). This latter value may be useful to some (especially those tunneling into a CPU via SSH), so I have included it.

The AppleScript uses the ioreg shell command to determine the status of the screen. Thereafter it massages the values returned from the Python script into the correct formats so they can be used to ascertain the screen state, the state of the screensaver and the need for a password (by comparing the current time (as converted to epoch time) to the locked time. The lock-time seems to be the most accurate measure of whether the screen actually is locked (and needs a password).

Here are the two necessary scripts.

Awaken Macros.kmmacros (21.4 KB)

1 Like