Storing and Accessing Passwords in Python Using Keyring (Windows 10 and Linux)
Easy password management in Python
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:
Windows has Credential Manager:
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:
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