Note: This site is currently "Under construction". I'm migrating to a new version of my site building software. Lots of things are in a state of disrepair as a result (for example, footnote links aren't working). It's all part of the process of building in public. Most things should still be readable though.

Set and Retrieve Passwords From Your Systems Password Manager With The keyring Python Module

NOTE: See also this post:

[[/posts/storing-local-environmental-variables-securely-in-password-managers-instead-of-plaintext-env-files--20eonil1bcsz][Storing Local Environmental Variables Securely In Password Managers Instead Of Plaintext env Files]]

### TL;DR

Set passwords form the command line with:

(NOTE: confirmed in march 2022 that `PASSWORD_NAME USER_NAME` is the proper order)

Code

python3 -m keyring set PASSWORD_NAME USER_NAME

Running that will ask you to put in the password.

Then, retrieve them in scripts with:

Code

import keyring 

keyring.get_password(PASSWORD_NAME, USERNAME)

NOTE: Confirmed that this is the order the parameters need to be in to get keys that were added from inside Keychain Access itself

### Details

You can store passwords in your system's credential locker (e.g. Keychain Access on macOs and ... on Windows and ... on Linux) with the keyring Python module.

__Installation__

Install it with either `pip3` or `pip` depending on your configuration. E.g.

Code

pip3 install keyring

### Setting Passwords From Scripts

You can set your passwords in a script with:

Code

import keyring

keyring.set_password("SERVICE", "USERNAME", "PASSWORD")

### Setting Passwords From The Command Line

You can set passwords directly from the command line with:

Code

python3 -m keyring set SERVICE USERNAME

You'll be prompted to enter your password from there

### Retrieving Passwords

And retrieve them with:

Code

import keyring 

keyring.get_password("SERVICE", "PASSWORD")

### Notes

- As far as I can tell "SERVICE" is just for grouping. I simply use my username. - I used to add dates to my passwords, but I stopped doing that. (This is more a reminder to myself that to anyone else)

Note: if you put something directly in Keychain Access, the values you put in for `name` and `account` are used in a backwards order from what you'd expect. i.e.

Code

keyring.get_password(NAME, ACCOUNT)

TODO: Look at the below for setting them to see how it goes in and if it's reversed or not

TODO: Add a python command line version of using the module to add passwords