Package: keyring
The Python keyring library provides an easy way to access the
system keyring service from python. It can be used in any
application that needs safe password storage.These recommended keyring backends are supported:macOSKeychainFreedesktopSecret Servicesupports many DE including
GNOME (requiressecretstorage)KDE4 & KDE5KWallet(requiresdbus)Windows Credential LockerOther keyring implementations are available throughThird-Party Backends.Installation - LinuxOn Linux, the KWallet backend relies ondbus-python, which does not always
install correctly when using pip (compilation is needed). For best results,
install dbus-python as a system package.Compatibility - macOSmacOS keychain supports macOS 11 (Big Sur) and later requires Python 3.8.7
or later with the “universal2” binary. See#525for details.Using KeyringThe basic usage of keyring is pretty simple: just callkeyring.set_passwordandkeyring.get_password:>>> import keyring
>>> keyring.set_password("system", "username", "password")
>>> keyring.get_password("system", "username")
'password'Command-line UtilityKeyring supplies akeyringcommand which is installed with the
package. After installing keyring in most environments, the
command should be available for setting, getting, and deleting
passwords. For more usage information, invoke with no arguments
or with--helpas so:$ keyring --help
$ keyring set system username
Password for 'username' in 'system':
$ keyring get system username
passwordThe command-line functionality is also exposed as an executable
package, suitable for invoking from Python like so:$ python -m keyring --help
$ python -m keyring set system username
Password for 'username' in 'system':
$ python -m keyring get system username
passwordTab CompletionIf installed via a package manager (apt, pacman, nix, homebrew, etc),
these shell completions may already have been distributed with the package
(no action required).Keyring provides tab completion if thecompletionextra is installed:$ pip install 'keyring[completion]'Then, generate shell completions, something like:$ keyring --print-completion bash | sudo tee /usr/share/bash-completion/completions/keyring
$ keyring --print-completion zsh | sudo tee /usr/share/zsh/site-functions/_keyring
$ keyring --print-completion tcsh | sudo tee /etc/profile.d/keyring.cshNote: the path of/usr/shareis mainly for GNU/Linux. For other OSs,
consider:macOS (Homebrew x86): /usr/local/sharemacOS (Homebrew ARM): /opt/homebrew/shareAndroid (Termux): /data/data/com.termux/files/usr/shareWindows (mingw64 of msys2): /mingw64/share…After installing the shell completions, enable them following your shell’s
recommended instructions. e.g.:bash: installbash-completion,
and ensure./usr/share/bash-completion/bash_completionin~/.bashrc.zsh: ensureautoload-Uzcompinit && compinitappears in~/.zshrc,
thengrep-wkeyring~/.zcompdumpto verify keyring appears, indicating
it was installed correctly.ConfiguringThe python keyring lib contains implementations for several backends. The
library will attempt to
automatically choose the most suitable backend for the current
environment. Users may also specify the preferred keyring in a
config file or by calling theset_keyring()function.Config file pathThe configuration is stored in a file named “keyringrc.cfg”
found in a platform-specific location. To determine
where the config file is stored, runkeyring diagnose.Config file contentTo specify a keyring backend, set thedefault-keyringoption to the
full path of the class for that backend, such askeyring.backends.macOS.Keyring.Ifkeyring-pathis indicated, keyring will add that path to the Python
module search path before loading the backend.For example, this config might be used to load theSimpleKeyringfrom thesimplekeyringmodule in
the./demodirectory (not implemented):[backend]
default-keyring=simplekeyring.SimpleKeyring
keyring-path=demoThird-Party BackendsIn addition to the backends provided by the core keyring package for
the most common and secure use cases, there
are additional keyring backend implementations available for other
use cases. Simply install them to make them available:keyrings.cryptfile- Encrypted text file storage.keyrings.alt- “alternate”,
possibly-insecure backends, originally part of the core package, but
available for opt-in.gsheet-keyring- a backend that stores secrets in a Google Sheet. For use withipython-secrets.bitwarden-keyring- a backend that stores secrets in theBitWardenpassword manager.onepassword-keyring- a backend that stores secrets in the1Passwordpassword manager.sagecipher- an encryption
backend which uses the ssh agent protocol’s signature operation to
derive the cipher key.keyrings.osx_keychain_keys- OSX keychain key-management, for private, public, and symmetric keys.keyring_pass.PasswordStoreBackendPassword Store (pass) backend for python’s keyringkeyring_jeepney- a
pure Python backend using the secret service DBus API for desktop
Linux (requireskeyring<24).Write your own keyring backendThe interface for the backend is defined bykeyring.backend.KeyringBackend.
Every backend should derive from that base class and define apriorityattribute and three functions:get_password(),set_password(), anddelete_password(). Theget_credential()function may be defined if
desired.See thebackendmodule for more detail on the interface of this class.Keyring employs entry points to allow any third-party package to implement
backends without any modification to the keyring itself. Those interested in
creating new backends are encouraged to create new, third-party packages
in thekeyringsnamespace, in a manner modeled by thekeyrings.alt
package. See thesetup.cfgfile
in that project for hints on how to create the requisite entry points.
Backends that prove essential may be considered for inclusion in the core
library, although the ease of installing these third-party packages should
mean that extensions may be readily available.To create an extension for Keyring, please submit a pull request to
have your extension mentioned as an available extension.Runtime ConfigurationKeyring additionally allows programmatic configuration of the
backend calling the apiset_keyring(). The indicated backend
will subsequently be used to store and retrieve passwords.To invokeset_keyring:# define a new keyring class which extends the KeyringBackend
import keyring.backend

class TestKeyring(keyring.backend.KeyringBackend):
    """A test keyring which always outputs the same password
    """
    priority = 1

    def set_password(self, servicename, username, password):
        pass

    def get_password(self, servicename, username):
        return "password from TestKeyring"

    def delete_password(self, servicename, username):
        pass

# set the keyring for keyring lib
keyring.set_keyring(TestKeyring())

# invoke the keyring lib
try:
    keyring.set_password("demo-service", "tarek", "passexample")
    print("password stored successfully")
except keyring.errors.PasswordSetError:
    print("failed to store password")
print("password", keyring.get_password("demo-service", "tarek"))Disabling KeyringIn many cases, uninstalling keyring will never be necessary.
Especially on Windows and macOS, the behavior of keyring is
usually degenerate, meaning it will return empty values to
the caller, allowing the caller to fall back to some other
behavior.In some cases, the default behavior of keyring is undesirable and
it would be preferable to disable the keyring behavior altogether.
There are several mechanisms to disable keyring:Uninstall keyring. Most applications are tolerant to keyring
not being installed. Uninstalling keyring should cause those
applications to fall back to the behavior without keyring.
This approach affects the Python environment where keyring
would otherwise have been installed.Configure the Null keyring in the environment. SetPYTHON_KEYRING_BACKEND=keyring.backends.null.Keyringin the environment, and theNull(degenerate) backend
will be used. This approach affects all uses of Keyring where
that variable is set.Permanently configure the Null keyring for the user by runningkeyring--disableorpython-mkeyring--disable.
This approach affects all uses of keyring for that user.Altering Keyring BehaviorKeyring provides a mechanism to alter the keyring’s behavior through
environment variables. Each backend implements aKeyringBackend.set_properties_from_env, which
when invoked will find all environment variables beginning withKEYRING_PROPERTY_{NAME}and will set a property for each{NAME.lower()}on the keyring. This method is invoked during
initialization for the default/configured keyring.This mechanism may be used to set some useful values on various
keyrings, including:keychain; macOS, path to an alternate keychain fileappid; Linux/SecretService, alternate ID for the applicationUsing Keyring on Ubuntu 16.04The following is a complete transcript for installing keyring in a
virtual environment on Ubuntu 16.04.  No config file was used:$ sudo apt install python3-venv libdbus-glib-1-dev
$ cd /tmp
$ pyvenv py3
$ source py3/bin/activate
$ pip install -U pip
$ pip install secretstorage dbus-python
$ pip install keyring
$ python
>>> import keyring
>>> keyring.get_keyring()
<keyring.backends.SecretService.Keyring object at 0x7f9b9c971ba8>
>>> keyring.set_password("system", "username", "password")
>>> keyring.get_password("system", "username")
'password'Using Keyring on headless Linux systemsIt is possible to use the SecretService backend on Linux systems without
X11 server available (only D-Bus is required). In this case:Install theGNOME Keyringdaemon.Start a D-Bus session, e.g. rundbus-run-session--shand run
the following commands inside that shell.Rungnome-keyring-daemonwith--unlockoption. The description of
that option says:Read a password from stdin, and use it to unlock the login keyring
or create it if the login keyring does not exist.When that command is started, enter a password into stdin and
press Ctrl+D (end of data). After that, the daemon will fork into
the background (use--foregroundoption to block).Now you can use the SecretService backend of Keyring. Remember to
run your application in the same D-Bus session as the daemon.Using Keyring on headless Linux systems in a Docker containerIt is possible to use keyring with the SecretService backend in Docker containers as well.
All you need to do is install the necessary dependencies and add the–privilegedflag
to avoid anyOperation not permittederrors when attempting to unlock the system’s keyring.The following is a complete transcript for installing keyring on a Ubuntu 18:04 container:docker run -it -d --privileged ubuntu:18.04

$ apt-get update
$ apt install -y gnome-keyring python3-venv python3-dev
$ python3 -m venv venv
$ source venv/bin/activate # source a virtual environment to avoid polluting your system
$ pip3 install --upgrade pip
$ pip3 install keyring
$ dbus-run-session -- sh # this will drop you into a new D-bus shell
$ echo 'somecredstorepass' | gnome-keyring-daemon --unlock # unlock the system's keyring

$ python
>>> import keyring
>>> keyring.get_keyring()
<keyring.backends.SecretService.Keyring object at 0x7f9b9c971ba8>
>>> keyring.set_password("system", "username", "password")
>>> keyring.get_password("system", "username")
'password'IntegrationAPIThe keyring lib has a few functions:get_keyring(): Return the currently-loaded keyring implementation.get_password(service, username): Returns the password stored in the
active keyring. If the password does not exist, it will return None.get_credential(service, username): Return a credential object stored
in the active keyring. This object contains at leastusernameandpasswordattributes for the specified service, where the returnedusernamemay be different from the argument.set_password(service, username, password): Store the password in the
keyring.delete_password(service, username): Delete the password stored in
keyring. If the password does not exist, it will raise an exception.In all cases, the parameters (service,username,password)
should be Unicode text.ExceptionsThe keyring lib raises the following exceptions:keyring.errors.KeyringError: Base Error class for all exceptions in keyring lib.keyring.errors.InitError: Raised when the keyring cannot be initialized.keyring.errors.PasswordSetError: Raised when the password cannot be set in the keyring.keyring.errors.PasswordDeleteError: Raised when the password cannot be deleted in the keyring.Get InvolvedPython keyring lib is an open community project and eagerly
welcomes contributors.Repository:https://github.com/jaraco/keyring/Bug Tracker:https://github.com/jaraco/keyring/issues/Mailing list:http://groups.google.com/group/python-keyringSecurity ConsiderationsEach built-in backend may have security considerations to understand
before using this library. Authors of tools or libraries utilizingkeyringare encouraged to consider these concerns.As with any list of known security concerns, this list is not exhaustive.
Additional issues can be added as needed.macOS KeychainAny Python script or application can access secrets created bykeyringfrom that same Python executable without the operating
system prompting the user for a password. To cause any specific
secret to prompt for a password every time it is accessed, locate
the credential using theKeychain Accessapplication, and in
theAccess Controlsettings, removePythonfrom the list
of allowed applications.Freedesktop Secret ServiceNo analysis has been performedKDE4 & KDE5 KWalletNo analysis has been performedWindows Credential LockerNo analysis has been performedMaking ReleasesThis project makes use of automated releases and continuous
integration. The
simple workflow is to tag a commit and push it to Github. If it
passes tests in CI, it will be automatically deployed to PyPI.Other things to consider when making a release:Check that the changelog is current for the intended release.Running TestsTests are continuously run in Github Actions.To run the tests locally, install and invoketox.BackgroundThe project was based on Tarek Ziade’s idea inthis post. Kang Zhang
initially carried it out as aGoogle Summer of Codeproject, and Tarek
mentored Kang on this project.For EnterpriseAvailable as part of the Tidelift Subscription.This project and the maintainers of thousands of other packages are working with Tidelift to deliver one enterprise subscription that covers all of the open source you use.Learn more.