Simple Gnome Keyring reading with Python

17th November 2012 (12 years ago)

If you've ever need to write a script that needs a password to perform some sort of login, keeping that password in Gnome Keyring is a good idea as it will be properly encrypted with very little effort. I chose to manually add a password to a keyring using the GUI and then access that password with Python. The function below is all that is needed once you know the name of the keyring and the password. If you store your password under the 'login' keyring, it will be automatically unlocked when you login to your desktop session.

import gnomekeyring as gk

def get_password(keyring, name):
    for key_id in gk.list_item_ids_sync(keyring):                               
        item_info = gk.item_get_info_sync(keyring, key_id)                      
        if item_info.get_display_name() == name:                                
            return item_info.get_secret()                                       
    raise KeyError('No such password \'%s\' in keyring \'%s\'' % (name, keyring))

This is the simplest way to use Gnome Keyring but you will probably want to look at locking your passwords to your specific app otherwise other programs could have access while the database is unlocked. You will need to create the passwords from within the app rather than the GUI in this case. Read more about Gnome Keyring and Python in the Mindbending blog series.