Saturday, February 22, 2025

Storing and Retrieving credentials with Python's Keyring library

 Like most technologists, I've been bumping into the whole credential problem over and over. 

In my case, I'm aiming to write scripts that are portable, and could be used by any of my colleges with minimal or no local machine setup.  I've adopted a mindset that for automation to be adopted, it must be the path of least resistance (will eventually write more on this line of thinking someday in the future)

Python's getpass has been handy, and I'll likely continue to use it in the future. But if I can avoid asking an operator of my script to enter credentials every time they use it, that brings me just that closer to being the path of least resistance. 

I considered .env files for a bit and haven't totally ruled them out in some use cases.  But again .env files puts a bit more burden on the end user than I would really like. 

Did some digging for a solution, and eventually I stumbled upon the Python Keyring library. 

You can read more about it here (https://pypi.org/project/keyring/). The high level is that its just a wrapper that lets you access your local systems keychain in a consistent programmatic way.

First off, if you don't have it already, you'll need to install with pip install keyring

        
   

 

 

 

Once installed, jump into a python interpreter, and import the keyring and getpass library

import keyring

import getpass 

 (if you dont have the getpass library installed, fetch with pip install getpass)

 Now to store credentials lets say for a hypothetical credential pair  , you could run the following

keyring.set_password('VendorAPI', 'Jeff', 'thisisthepassword')

Where VendorAPI is the shorthand you'll use to reference the credential sets, 'Jeff' is your username, and 'thisisthepassword', is obviously your password. But in my example I'm using getpass to obscure my password, which looks like 


Now, from here on out you can retrieve these credentials in a different python script with 

keyring.get_password('VendorAPI', 'Jeff')

 


Also, assuming your on a windows machine, you can view and modify these credentials via the Credential Manager. You can also create credential pairs in the credential manager, then use the keyring library to later retrieve these credentials 

 

 

 Thats it for now! if I find out anything else useful, I'll post updates below





No comments:

Post a Comment

Using Powershell to prep for a DHCP cutover

 Alright, here is the background.  Recently I was working on migrating a few locations off of bog standard Microsoft Windows DHCP server to ...