Code Monkey home page Code Monkey logo

keyring's Introduction

https://readthedocs.org/projects/keyring/badge/?version=latest https://tidelift.com/badges/github/jaraco/keyring

Installing and Using Python Keyring Lib

What is Python keyring lib?

The Python keyring lib provides an easy way to access the system keyring service from python. It can be used in any application that needs safe password storage.

The keyring library is licensed under both the MIT license and the PSF license.

These recommended keyring backends are supported by the Python keyring lib:

Other keyring implementations are available through Third-Party Backends.

Installation Instructions

Install from Index

Install using your favorite installer. For example:

$ pip install keyring
Linux

On Linux, the KWallet backend relies on dbus-python, which does not always install correctly when using pip (compilation is needed). So we recommend that dbus-python is installed as a system package. The same also applies to the Secret Storage backend under Python 2 (under Python 3 a different D-Bus implementation is used).

Using Keyring

The basic usage of keyring is pretty simple: just call keyring.set_password and keyring.get_password:

>>> import keyring
>>> keyring.set_password("system", "username", "password")
>>> keyring.get_password("system", "username")
'password'

Command-line Utility

Keyring supplies a keyring command 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 information on usage, invoke with no arguments or with --help as so:

$ keyring --help
$ keyring set system username
Password for 'username' in 'system':
$ keyring get system username
password

The 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
password

Configure your keyring lib

The python keyring lib contains implementations for several backends. The library will automatically choose the keyring that is most suitable for your current environment. You can also specify the keyring you like to be used in the config file or by calling the set_keyring() function.

Customize your keyring by config file

This section describes how to change your option in the config file.

Config file path

The configuration of the lib is stored in a file named "keyringrc.cfg". This file must be found in a platform-specific location. To determine where the config file is stored, run the following:

python -c "import keyring.util.platform_; print(keyring.util.platform_.config_root())"

Some keyrings also store the keyring data in the file system. To determine where the data files are stored, run this command:

python -c "import keyring.util.platform_; print(keyring.util.platform_.data_root())"
Config file content

To specify a keyring backend, set the default-keyring option to the full path of the class for that backend, such as keyring.backends.OS_X.Keyring.

If keyring-path is 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 the SimpleKeyring from the simplekeyring module in the ./demo directory (not implemented):

[backend]
default-keyring=simplekeyring.SimpleKeyring
keyring-path=demo

Third-Party Backends

In 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:

Write your own keyring backend

The interface for the backend is defined by keyring.backend.KeyringBackend. Every backend should derive from that base class and define a priority attribute and three functions: get_password(), set_password(), and delete_password(). The get_credential() function may be defined if desired.

See the backend module 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 the keyrings namespace, in a manner modeled by the keyrings.alt package. See the setup.py file in that project for a hint 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.

If you've created an extension for Keyring, please submit a pull request to have your extension mentioned as an available extension.

Set the keyring in runtime

Keyring additionally allows programmatic configuration of the backend calling the api set_keyring(). The indicated backend will subsequently be used to store and retrieve passwords.

Here's an example demonstrating how to invoke set_keyring:

# define a new keyring class which extends the KeyringBackend
import keyring.backend

class TestKeyring(keyring.backend.KeyringBackend):
    """A test keyring which always outputs 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, password):
        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"))

Using Keyring on Ubuntu 16.04

The 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 systems

It is possible to use the SecretService backend on Linux systems without X11 server available (only D-Bus is required). To do that, you need the following:

  • Install the GNOME Keyring daemon.

  • Start a D-Bus session, e.g. run dbus-run-session -- sh and run the following commands inside that shell.

  • Run gnome-keyring-daemon with --unlock option. 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 your password into stdin and press Ctrl+D (end of data). After that the daemon will fork into background (use --foreground option to prevent that).

  • Now you can use the SecretService backend of Keyring. Remember to run your application in the same D-Bus session as the daemon.

Integrate the keyring lib with your application

API interface

The 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 least username and password attributes for the specified service, where the returned username may 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. On Python 2, these parameters are accepted as simple str in the default encoding as they will be implicitly decoded to text. Some backends may accept bytes for these parameters, but such usage is discouraged.

Exceptions

The keyring lib raises following exceptions:

  • keyring.errors.KeyringError: Base Error class for all exceptions in keyring lib.
  • keyring.errors.InitError: Raised when the keyring can't be initialized.
  • keyring.errors.PasswordSetError: Raise when password can't be set in the keyring.
  • keyring.errors.PasswordDeleteError: Raised when the password can't be deleted in the keyring.

Get involved

Python keyring lib is an open community project and highly welcomes new contributors.

Security Contact

If you wish to report a security vulnerability, the public disclosure of which may exacerbate the risk, please Contact Tidelift security, which will coordinate the fix and disclosure privately.

Making Releases

This project makes use of automated releases via Travis-CI. The simple workflow is to tag a commit and push it to Github. If it passes tests on a late Python version, it will be automatically deployed to PyPI.

Other things to consider when making a release:

  • first ensure that tests pass (preferably on Windows and Linux)
  • check that the changelog is current for the intended release

Running Tests

Tests are continuously run using Travis-CI.

To run the tests yourself, you'll want keyring installed to some environment in which it can be tested. Recommended technique is described below.

Using tox

Keyring prefers use of tox to run tests. Simply install and invoke tox.

This technique is the one used by the Travis-CI script.

Background

The project was based on Tarek Ziade's idea in this post. Kang Zhang initially carried it out as a Google Summer of Code project, and Tarek mentored Kang on this project.

Join the chat at https://gitter.im/jaraco/keyring

keyring's People

Contributors

benji-york avatar bretth avatar cournape avatar dholth avatar dsully avatar fraca7 avatar frispete avatar hefee avatar j-martin avatar jaraco avatar jim-easterbrook avatar jonnyjd avatar kangzhang avatar maciex avatar mandel-macaque avatar mata-p avatar mathstuf avatar maxking avatar mekk avatar micahculpepper avatar mindw avatar mitya57 avatar multani avatar n8henrie avatar reece avatar rl-0x0 avatar sborho avatar takluyver avatar tarekziade avatar zooba avatar

Watchers

 avatar  avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.