Storing and Accessing Passwords in Python Using Keyring (Windows 10 and Linux)

Easy password management in Python

Jamie Southchurch
2 min readOct 27, 2022

Problem

From time to time, you will need to use credentials to access data or services (APIs, email servers, etc.) The time honoured solution of saving passwords in text files has many, dangerous, security based problems.

Solution

The Keyring package in Python is designed for storing encrypted passwords in your operating systems password vault (Window’s Credential Manager, KWallet for KDE in Linux)

I’ll show you how to store and access passwords, both through Python and using the OS GUI on Windows 10 and Linux (using KDE Plasma as the desktop environment)

First you’ll need to install Keyring through PIP

pip install keyring

Once installed, you can store passwords by importing the keyring module and using the set_password function.

The function takes 3 positional arguments:

  • service_name: A name for the credential (the system, service or API the credentials are for)
  • username: The username
  • password: The password to be stored
import keyringkeyring.set_password('system', 'username', 'password')

Once you’ve stored your password, you can retrieve it using the get_password function, which takes 2 positional arguments:

  • service_name: Credential name (as above)
  • username
password = keyring.get_password('system', 'username')
print(password)
'password'

You can also check the password through your Operating system’s password vault UI.

For a KDE plasma session in Linux, this will be KWallet:

Saved credential shown in KWallet on Manjaro Linuw running KDE plasma

Windows has Credential Manager:

Saved credential shown in Credential Manager on Windows 10

As you can see, Windows isn’t as forthcoming with the passwords as Linux (it can still be viewed via Python though.

If you prefer to use a UI to manage your credentials, this is only really possible via Windows Credential Manager (although I’m happy to be proven wrong if someone has worked out how to create a credential in KWallet that can be accessed using Keyring):

Click ‘Add a generic credential’ then fill in details below:

Creating a new credential in Windows Credential Manager

The boxes relate to the positional agruments in set_password as follows:

  • Internet or network address = service_name
  • Username = username
  • Password = password

Conclusion

Storing passwords using Keyring is an easy and secure way to save and access credentials to be used in Python scripts.

Code

The code (what little of it there is) for this article can be found at:

https://github.com/jammage13/medium_articles/tree/main/keyring

--

--

Jamie Southchurch
Jamie Southchurch

Written by Jamie Southchurch

0 Followers

Senior data scientist working for a large Insurance company. I mostly deal with motor insurance fraud, so most of what I do involves heavily imbalanced data.

No responses yet