Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I retrieve a username with Python keyring?

I have a Mercurial keyring on my Windows 7 machine. I am using the Python keyring library to get user credentials from the Mercurial keyring.

I can retrieve the password for a given username with:

keyring.get_password('Mercurial', 'user@@etc')

Is there a similar function to retrieve the username?

like image 315
yoyodunno Avatar asked Mar 05 '13 22:03

yoyodunno


3 Answers

While keyring was only designed to store passwords, you can abuse get_password to store the username separately.

import keyring

# store username & password
keyring.set_password("name_of_app", "username", "user123")
keyring.set_password("name_of_app", "password", "pass123")

# retrieve username & password
username = keyring.get_password("name_of_app", "username")
password = keyring.get_password("name_of_app", "password")

Alternatively, if you want to keep the username paired with the password:

import keyring

service_id = "name_of_app"
username = "user123"

# store username & password
keyring.set_password(service_id, "username", username)
keyring.set_password(service_id, username, "pass123")

# retrieve username & password
username = keyring.get_password(service_id, "username")
password = keyring.get_password(service_id, username)

Credit to Dustin Wyatt & Alex Chan for this solution.

like image 144
Stevoisiak Avatar answered Sep 23 '22 08:09

Stevoisiak


On Windows I was able to get both username and password (i.e. the "credentials") using

c = keyring.get_credential("servicename", None)

Note that this does not work on macOS, the keyring backend does not have capabilities to search for entries - i.e. you need to know the username. I suppose that native code would allow you to do this, though, see official docs

like image 27
MShekow Avatar answered Sep 19 '22 08:09

MShekow


You are expected to have stored the username somewhere else.

The keyring only stores the password, keyed by the application name and username.

like image 25
Martijn Pieters Avatar answered Sep 22 '22 08:09

Martijn Pieters