Skip to main content

Command Palette

Search for a command to run...

Secure Password Storage in Python: A Guide to Keyring

Python keyring makes system keyring access simple and secure.

Updated
1 min read
Secure Password Storage in Python: A Guide to Keyring
import os
import keyring


def set_password(service_name, username, password):
    try:
        # Set the password in the keyring
        keyring.set_password(service_name, username, password)
        print("Password set for service '{}' and username '{}'".format(service_name, username))
    except keyring.errors.KeyringError as e:
        # Handle any errors that occur during password setting
        print("Error setting password: '{}'".format(str(e)))


def get_password(service_name, username):
    try:
        # Retrieve the password from the keyring
        password = keyring.get_password(service_name, username)
        if password:
              print("Password set for service '{}' and username '{}'".format(service_name, username))
        else:
            print("No password found '{}' and username '{}'".format(service_name, username))
    except keyring.errors.KeyringError as e:
        # Handle any errors that occur during password retrieval
        print("Error retrieving password: '{}'".format(str(e)))


# Usage example
service_name = 'test_svcaccount'
username = 'test-user'
pssword = os.environ['SECRET_PARAM']
#pssword = 'fhvjh'

# Set the password
set_password(service_name, username, pssword)

# Get the password
get_password(service_name, username)