def usable(cls): """Can this store be used?""" if "gnomekeyring" in globals() and gnomekeyring.is_available(): if "gtk" in globals() and not hasattr(gtk, "application_name"): gtk.application_name = "rosie.ws_client" return True return False
def ask_password(self): """A simple routine that ask for password, if it is not yet in the keyring""" display_name = "@".join([self.__bind_dn, self.__uri]) if gnomekeyring.is_available(): for pw_id in gnomekeyring.list_item_ids_sync('login'): pw = gnomekeyring.item_get_info_sync("login", pw_id) if pw.get_display_name() == display_name: return pw.get_secret() # Ask for password... password_dialog = lumPasswordEntry(self.__datapath) password = password_dialog.run() if password is not None: atts = { 'application': 'Ldap User Manager', 'username': self.__bind_dn, 'server': self.__uri, 'protocol': 'ldap', 'port': '389', } pw_id = gnomekeyring.item_create_sync('login', gnomekeyring.ITEM_GENERIC_SECRET, display_name, atts, password, True) return password
def get_storage(): global storage if storage is None: # None is only in first time get_storage is called if gajim.config.get('use_gnomekeyring'): global gnomekeyring try: import gnomekeyring except ImportError: pass else: global USER_HAS_GNOMEKEYRING global USER_USES_GNOMEKEYRING USER_HAS_GNOMEKEYRING = True if gnomekeyring.is_available(): USER_USES_GNOMEKEYRING = True else: USER_USES_GNOMEKEYRING = False if USER_USES_GNOMEKEYRING: try: storage = GnomePasswordStorage() except gnomekeyring.NoKeyringDaemonError: storage = SimplePasswordStorage() except gnomekeyring.DeniedError: storage = SimplePasswordStorage() else: storage = SimplePasswordStorage() return storage
def get_storage(): global storage if storage is None: # None is only in first time get_storage is called if gajim.config.get("use_gnomekeyring"): global gnomekeyring try: import gnomekeyring except ImportError: pass else: global USER_HAS_GNOMEKEYRING global USER_USES_GNOMEKEYRING USER_HAS_GNOMEKEYRING = True if gnomekeyring.is_available(): USER_USES_GNOMEKEYRING = True else: USER_USES_GNOMEKEYRING = False if USER_USES_GNOMEKEYRING: try: storage = GnomePasswordStorage() except gnomekeyring.NoKeyringDaemonError: storage = SimplePasswordStorage() except gnomekeyring.DeniedError: storage = SimplePasswordStorage() else: storage = SimplePasswordStorage() return storage
def __init__(self): self._protocol = "network" self._key = gk.ITEM_NETWORK_PASSWORD if not gk.is_available(): raise KeyringException("The Gnome keyring is not available") logger.debug("default keyring ok") self.loaded = False self.lock = threading.RLock()
def forget_password(self, menu_item = None): if not gnomekeyring.is_available(): return None if self.__uri is None or self.__bind_dn is None: return None display_name = "@".join([self.__bind_dn, self.__uri]) for pw_id in gnomekeyring.list_item_ids_sync("login"): if gnomekeyring.item_get_info_sync("login", pw_id).get_display_name() == display_name: gnomekeyring.item_delete_sync('login', pw_id)
def open_Keyring(self): allowed = False if self.supported()>=0 and G.is_available() : _gnome_keyrings = G.list_keyring_names_sync() allowed = True try : if self.appletName not in _gnome_keyrings : self.prnt.createKeyring("%s: %s doesn`t exist"%(self.name, self.appletName)) return False self.KEYRING_NAME = self.appletName except Exception, err : allowed = False finally : pass
def set_password(self, key, password, _folder = None): if not G.is_available() : self.prnt.Parent.eventNotification("%s not available." % self.name) return None folder = to_unicode(_folder) if _folder else self.appletName try: G.item_create_sync( self.KEYRING_NAME, G.ITEM_NETWORK_PASSWORD, "Password for '%s' in '%s'" % (to_unicode(key), folder), {'user': to_unicode(key), 'domain': folder}, to_unicode(password), True) except G.CancelledError: raise PasswordSetError("cancelled by user") finally : pass
def __init__(self, clerk, keyring): self.clerk = clerk self.keyring = None # check keyring daemon if not gnomekeyring.is_available(): self.clerk.close_shop('Gnome Keyring Daemon is not available') # check keyring self.keyring = self.__find_fuzzy(keyring, gnomekeyring.list_keyring_names_sync()) if not self.keyring: self.clerk.close_shop('There is no keyring with name "{}"'.format( keyring))
def __init__(self): if not gk.is_available(): raise AccountError("Gnome Keyring Unavailable") else: errors = [] errors.append(gk.DeniedError) errors.append(gk.NoKeyringDaemonError) errors.append(gk.AlreadyUnlockedError) errors.append(gk.NoSuchKeyringError) errors.append(gk.BadArgumentsError) errors.append(gk.IOError) errors.append(gk.CancelledError) errors.append(gk.AlreadyExistsError) errors.append(gk.NoMatchError) self.GK_EXCEPT = tuple(errors)
def __init__(self, group, name, *attr, **args): super(AccountOption, self).__init__ (group, name, *attr, **args) # check for availability of keyring if not gnomekeyring.is_available(): raise Exception('GnomeKeyring is not available!!') # THIS IS A WORKAROUND FOR A BUG IN KEYRING (usually we would use # gnomekeyring.get_default_keyring_sync() here): # find first available keyring self.keyring_list = gnomekeyring.list_keyring_names_sync() if len(self.keyring_list) == 0: raise Exception('No keyrings found. Please create one first!') else: # we prefer the default keyring try: self.keyring = gnomekeyring.get_default_keyring_sync() except: if "session" in self.keyring_list: print "Warning: No default keyring found, using session keyring. Storage is not permanent!" self.keyring = "session" else: print "Warning: Neither default nor session keyring found, assuming keyring %s!" % self.keyring_list[0] self.keyring = self.keyring_list[0]
def getPasswd(cls, key): if not gnomekeyring.is_available(): err_str = "Cannot get passwords for " + key + " from gnome keyring: not available" logging.error(err_str) pynotify.init(self.username) notification = pynotify.Notification(err_str) notification.show() return None keys = gnomekeyring.list_item_ids_sync("login") for k in keys: try: item = gnomekeyring.item_get_info_sync("login", k) if key in item.get_display_name(): return item.get_secret() except Exception as ex: logging.info("Need to unlock login keyring: " + ex.message) gnomekeyring.unlock_sync("login", getpass.getpass('Password: ')) err_str = "Cannot get passwords for " + key + " from gnome keyring: not found" logging.error(err_str) pynotify.init(self.username) notification = pynotify.Notification(err_str) notification.show() return None
def get_password(self, key, _folder = None): if not G.is_available() : return None folder = to_unicode(_folder) if _folder else self.appletName item_list = G.list_item_ids_sync(self.appletName) password = None # ♿ ☟ GnomeKeyring is glitch at find_network_password_sync i = 0 _items = None while i < 10 : try : _items = G.find_network_password_sync(to_unicode(key), folder) break except G.CancelledError : i+=1 except G.NoMatchError : i+=1 finally : pass # ♿ ☝ GnomeKeyring is glitch at find_network_password_sync if _items : for item in _items : if item['keyring']==self.appletName : password = item['password'] break return password
def close_Keyring(self): if G.is_available() : G.lock_sync(self.appletName)
def __init__(self): global keyring self.username = None self.password = None self.multiline = False self.separator = False self.gconf = gconf.client_get_default() self.appname = "gtracker" self.username_key = "/apps/gtracker/username" self.password_key = "/apps/gtracker/password" self.interval_key = "/apps/gtracker/interval" self.multi_key = "/apps/gtracker/multiline" self.sep_key = "/apps/gtracker/separator" self.interval = self.gconf.get_int(self.interval_key) if self.interval<1: self.interval = 15 self.gconf.set_int(self.interval_key,self.interval) self.multiline = self.gconf.get_bool(self.multi_key) if self.multiline==None: self.multiline = True self.gconf.set_bool(self.multi_key,self.multiline) self.separator = self.gconf.get_bool(self.sep_key) if self.separator==None: self.separator = True self.gconf.set_bool(self.sep_key,self.separator) if keyring: try: glib.set_application_name(self.appname) except: pass if gk.is_available(): names = gk.list_keyring_names_sync() if not self.appname in names: gk.create_sync(self.appname,"") keys = gk.list_item_ids_sync(self.appname) if len(keys)==1: gk.unlock_sync(self.appname,"") info = gk.item_get_info_sync(self.appname,keys[0]) self.username = info.get_display_name() self.password = info.get_secret() else: self.username = "" self.password = "" else: keyring = False if not keyring: self.username = self.gconf.get_string(self.username_key) if self.username==None or len(self.username)<1: self.username = "" self.gconf.set_string(self.username_key,"") self.password = self.gconf.get_string(self.password_key) if self.password==None or len(self.password)<1: self.password = "" self.gconf.set_string(self.password_key,self.password) else: self.gconf.unset(self.username_key) self.gconf.unset(self.password_key)
# # This work is provided "AS IS" and subject to the Shotgun Pipeline Toolkit # Source Code License included in this distribution package. See LICENSE. # By accessing, using, copying or modifying this work you indicate your # agreement to the Shotgun Pipeline Toolkit Source Code License. All rights # not expressly granted therein are reserved by Shotgun Software Inc. import uuid import gnomekeyring from .base_store import KeyringStoreBase from ..qt_abstraction import QtGui # This module will only import if gnomekeyring is actually available if not gnomekeyring.is_available(): raise ImportError("gnomekeyring not available") class GnomeKeyringStore(KeyringStoreBase): def get_password(self, keyring, login): item, _ = self._get_item(keyring, login) if item is None: return None return item.get_secret() def set_password(self, keyring, login, password): self._get_item(keyring, login, create=True) login_key = self._key_for_login(keyring, login) gnomekeyring.item_create_sync( "Login", gnomekeyring.ITEM_GENERIC_SECRET,
def __init__(self): global keyring self.username = None self.password = None self.multiline = False self.separator = False self.gconf = gconf.client_get_default() self.appname = "gtracker" self.username_key = "/apps/gtracker/username" self.password_key = "/apps/gtracker/password" self.interval_key = "/apps/gtracker/interval" self.multi_key = "/apps/gtracker/multiline" self.sep_key = "/apps/gtracker/separator" self.interval = self.gconf.get_int(self.interval_key) if self.interval < 1: self.interval = 15 self.gconf.set_int(self.interval_key, self.interval) self.multiline = self.gconf.get_bool(self.multi_key) if self.multiline == None: self.multiline = True self.gconf.set_bool(self.multi_key, self.multiline) self.separator = self.gconf.get_bool(self.sep_key) if self.separator == None: self.separator = True self.gconf.set_bool(self.sep_key, self.separator) if keyring: try: glib.set_application_name(self.appname) except: pass if gk.is_available(): names = gk.list_keyring_names_sync() if not self.appname in names: gk.create_sync(self.appname, "") keys = gk.list_item_ids_sync(self.appname) if len(keys) == 1: gk.unlock_sync(self.appname, "") info = gk.item_get_info_sync(self.appname, keys[0]) self.username = info.get_display_name() self.password = info.get_secret() else: self.username = "" self.password = "" else: keyring = False if not keyring: self.username = self.gconf.get_string(self.username_key) if self.username == None or len(self.username) < 1: self.username = "" self.gconf.set_string(self.username_key, "") self.password = self.gconf.get_string(self.password_key) if self.password == None or len(self.password) < 1: self.password = "" self.gconf.set_string(self.password_key, self.password) else: self.gconf.unset(self.username_key) self.gconf.unset(self.password_key)
def parse_args(self): ''' Parse commandline options. Returns False if something is wrong. ''' desc=\ '''By default %prog queries the GNOME keyring for items matching specified arguments. You can define the item exactly by --id, or search for it using --name, -p and/or -i. It is important to understand that the keyring items are divided into several types (see --type) and each contain several properties. Both the item type and item properties can be inspected using a tool like Seahorse. Then you will know what to query for. Zero or more items may match your query. They will be printed out one item a line, by default in the format: ID [TAB] secret You can also create a new keyring item using --set. In this case the arguments -p and/or -i will be used as properties of the new item. When a new keyring item is created, its ID is printed out on the output.''' parser = MyOptionParser(description=desc, version=__version__) parser.add_option('-t', '--type', choices=CLI.ITEM_TYPES.keys(), default='generic', help='type of keyring item: ' 'generic, network or note [default: %default]') parser.add_option('-k', '--keyring', help='keyring name [default: ' 'default keyring]', dest=self.keyring) parser.add_option('--id', type='int', help='key ID') parser.add_option( '-n', '--name', help='keyring item descriptive name [exact match for querying, ' 'mandatory if --set]') parser.add_option( '-p', default='', metavar='PARAM1=VALUE1,PARAM2=VALUE2', dest='params', help='params and values of keyring item, e.g. user, server, ' 'protocol, etc.') parser.add_option( '-i', default='', metavar='PARAM1=VALUE1,PARAM2=VALUE2', dest='params_int', help='same as -p, but values are treated as integers, not strings') parser.add_option('--all', action='store_true', help="Don't query for " "specific keyring items, list all of them") out_group = optparse.OptionGroup( parser, 'Formatting output for ' 'querying keyring items') out_group.add_option( '-o', '--output', default='id,name,secret', help='comma-separated list of columns to be printed on the output. ' "Column name may include keywords 'id', 'name', 'secret' or " "any item's property name (displayed only when available). Columns " "will be separated by tabs. [default: %default]") out_group.add_option('-O', '--output-attribute-names', action='store_true', help='show attribute names in addition to values') out_group.add_option('-l', '--no-newline', action='store_true', help="don't output the trailing newline") out_group.add_option('-1', action='store_true', dest='output1', help="same as '--output secret --no-newline'") parser.add_option_group(out_group) other_group = optparse.OptionGroup(parser, 'Other operations') other_group.add_option( '-s', '--set', action='store_true', help='create a new item in the keyring instead of querying') other_group.add_option( '-d', '--delete', action='store_true', help="delete the item in the keyring identified by '--id'") other_group.add_option('--lock', action='store_true', help='lock the keyring') other_group.add_option('--unlock', action='store_true', help='unlock the keyring') other_group.add_option( '-w', '--password', help='provide a password for operations that require it; otherwise' 'you will be asked for it interactively') parser.add_option_group(other_group) epilog=\ """Example usage: $ %(prog)s --all List all keyring items in the default keyring. $ %(prog)s --id 12 Get keyring item with ID 12 in default keyring. $ %(prog)s --name 'backup' Search for keyring item with name 'backup'. You can easily see item names e.g. in the overview of Seahorse application. $ %(prog)s -p [email protected] -i gajim=1 -1 Search for keyring item with property 'account_name' with value '*****@*****.**' and property 'gajim' with integer value '1'. Output only the secret(s). $ %(prog)s --type network -p server=my.com,protocol=ftp --output user,secret Search for network keyring item with 'server' and 'protocol' properties. Output property 'user' followed by item's secret. $ %(prog)s --set --name 'foo' -p bar=baz --keyring login Create a new item in keyring 'login' with name 'foo' and property 'bar'. $ %(prog)s --delete --id 12 Delete a keyring item with ID 12. $ %(prog)s --lock --keyring login Lock keyring 'login'. $ %(prog)s --unlock --password qux Unlock the default keyring and provide the password 'qux' on the command-line. """ parser.epilog = epilog % {'prog': parser.get_prog_name()} (options, args) = parser.parse_args() self.options = options # ensure that the application name is correctly set # this must be done after parsing args, because # our --name option collides with gtk option --name import gtk if not gk.is_available(): print >> sys.stderr, 'GNOME keyring is not available!' return False # validate mandatory options query_mode = not (options.set or options.delete or options.lock or options.unlock) if query_mode: if not (options.params or options.params_int or options.name or options.id or options.all): parser.error( 'Missing --name, -p, -i, --id or --all! See --help.') if options.set: if not options.name: parser.error('Missing --name! See --help.') if options.delete: if not options.id: parser.error('Missing --id! See --help.') # parse string params try: tuples = options.params.split(',') for tupl in tuples: if not tupl: # empty string continue name, val = tupl.split('=', 1) self.params[name] = val except ValueError, e: parser.error('Incorrect syntax of "-p param1=value1,' 'param2=value2"! See --help.\nDetails:\n%s' % e)
GNOME_KEYRING = False try: import keyring GENERIC_KEYRING = True except: try: import gobject gobject.set_application_name('osc') import gnomekeyring if os.environ['GNOME_DESKTOP_SESSION_ID']: # otherwise gnome keyring bindings spit out errors, when you have # it installed, but you are not under gnome # (even though hundreds of gnome-keyring daemons got started in parallel) # another option would be to support kwallet here GNOME_KEYRING = gnomekeyring.is_available() except: pass def _get_processors(): """ get number of processors (online) based on SC_NPROCESSORS_ONLN (returns 1 if config name does not exist). """ try: return os.sysconf('SC_NPROCESSORS_ONLN') except ValueError as e: return 1
def parse_args(self): ''' Parse commandline options. Returns False if something is wrong. ''' desc=\ '''By default %prog queries the GNOME keyring for items matching specified arguments. You can define the item exactly by --id, or search for it using --name, -p and/or -i. It is important to understand that the keyring items are divided into several types (see --type) and each contain several properties. Both the item type and item properties can be inspected using a tool like Seahorse. Then you will know what to query for. Zero or more items may match your query. They will be printed out one item a line, by default in the format: ID [TAB] secret You can also create a new keyring item using --set. In this case the arguments -p and/or -i will be used as properties of the new item. When a new keyring item is created, its ID is printed out on the output.''' parser = MyOptionParser(description=desc, version=_version) parser.add_option('-t', '--type', choices=CLI.ITEM_TYPES.keys(), default='generic', help='type of keyring item: ' 'generic, network or note [default: %default]') parser.add_option('-k', '--keyring', help='keyring name [default: ' 'default keyring]', dest=self.keyring) parser.add_option('--id', type='int', help='key ID') parser.add_option('-n', '--name', help='keyring item descriptive name [exact match for querying, ' 'mandatory if --set]') parser.add_option('-p', default='', metavar='PARAM1=VALUE1,PARAM2=VALUE2', dest='params', help='params and values of keyring item, e.g. user, server, ' 'protocol, etc.') parser.add_option('-i', default='', metavar='PARAM1=VALUE1,PARAM2=VALUE2', dest='params_int', help='same as -p, but values are treated as integers, not strings') parser.add_option('--all', action='store_true', help="Don't query for " "specific keyring items, list all of them") out_group = optparse.OptionGroup(parser, 'Formatting output for ' 'querying keyring items') out_group.add_option('-o', '--output', default='id,name,secret', help='comma-separated list of columns to be printed on the output. ' "Column name may include keywords 'id', 'name', 'secret' or " "any item's property name (displayed only when available). Columns " "will be separated by tabs. [default: %default]") out_group.add_option('-O', '--output-attribute-names', action='store_true', help='show attribute names in addition to values') out_group.add_option('-l', '--no-newline', action='store_true', help="don't output the trailing newline") out_group.add_option('-1', action='store_true', dest='output1', help="same as '--output secret --no-newline'") parser.add_option_group(out_group) other_group = optparse.OptionGroup(parser, 'Other operations') other_group.add_option('-s', '--set', action='store_true', help='create a new item in the keyring instead of querying') other_group.add_option('-d', '--delete', action='store_true', help="delete the item in the keyring identified by '--id'") other_group.add_option('--lock', action='store_true', help='lock the keyring') other_group.add_option('--unlock', action='store_true', help='unlock the keyring') other_group.add_option('-w', '--password', help='provide a password for operations that require it; otherwise' 'you will be asked for it interactively') parser.add_option_group(other_group) epilog=\ """Example usage: $ %(prog)s --all List all keyring items in the default keyring. $ %(prog)s --id 12 Get keyring item with ID 12 in default keyring. $ %(prog)s --name 'backup' Search for keyring item with name 'backup'. You can easily see item names e.g. in the overview of Seahorse application. $ %(prog)s -p [email protected] -i gajim=1 -1 Search for keyring item with property 'account_name' with value '*****@*****.**' and property 'gajim' with integer value '1'. Output only the secret(s). $ %(prog)s --type network -p server=my.com,protocol=ftp --output user,secret Search for network keyring item with 'server' and 'protocol' properties. Output property 'user' followed by item's secret. $ %(prog)s --set --name 'foo' -p bar=baz --keyring login Create a new item in keyring 'login' with name 'foo' and property 'bar'. $ %(prog)s --delete --id 12 Delete a keyring item with ID 12. $ %(prog)s --lock --keyring login Lock keyring 'login'. $ %(prog)s --unlock --password qux Unlock the default keyring and provide the password 'qux' on the command-line. """ parser.epilog = epilog % {'prog': parser.get_prog_name()} (options, args) = parser.parse_args() self.options = options # ensure that the application name is correctly set # this must be done after parsing args, because # our --name option collides with gtk option --name import gtk if not gk.is_available(): print >>sys.stderr, 'GNOME keyring is not available!' return False # validate mandatory options query_mode = not (options.set or options.delete or options.lock or options.unlock) if query_mode: if not (options.params or options.params_int or options.name or options.id or options.all): parser.error('Missing --name, -p, -i, --id or --all! See --help.') if options.set: if not options.name: parser.error('Missing --name! See --help.') if options.delete: if not options.id: parser.error('Missing --id! See --help.') # parse string params try: tuples = options.params.split(',') for tupl in tuples: if not tupl: # empty string continue name, val = tupl.split('=',1) self.params[name] = val except ValueError, e: parser.error('Incorrect syntax of "-p param1=value1,' 'param2=value2"! See --help.\nDetails:\n%s' % e)
def __init__(self): if not gnomekeyring.is_available(): raise Exception("Gnome keyring not available!") self.keyring_name = gnomekeyring.get_default_keyring_sync()
def check(self): """Determine whether gnome-keyring is available and usable.""" if not GTKInterface.check(self): return False return (gnomekeyring is not None) and (gnomekeyring.is_available())
def get_keyring(): """ Get one of working keyrings. """ global _KEYRING if _KEYRING is not None: # keyring configured return _KEYRING global _KEYRING_NAME try: import gnomekeyring if gnomekeyring.is_available(): # create fake keyring as long way by keyring module not work without # gi. class FakeGnomeKeyring: """ Proxy class emulate standard interface for Gnome Keyring. """ @staticmethod def get_password(plugin_id, username): kr_name = gnomekeyring.get_default_keyring_sync() for id_ in gnomekeyring.list_item_ids_sync(kr_name): attrs = gnomekeyring.item_get_attributes_sync( kr_name, id_) if (attrs.get('plugin_id') == plugin_id and attrs.get('username') == username): return gnomekeyring.item_get_info_sync( kr_name, id_).get_secret() @staticmethod def set_password(plugin_id, username, password): kr_name = gnomekeyring.get_default_keyring_sync() attrs = {'username': username, 'plugin_id': plugin_id} gnomekeyring.item_create_sync( kr_name, gnomekeyring.ITEM_GENERIC_SECRET, _("Password for %s in %s (Kupfer)") % (username, plugin_id), attrs, password, True) @staticmethod def supported(): return 1 _KEYRING = FakeGnomeKeyring _KEYRING_NAME = _("GNOME Keyring") return _KEYRING except ImportError: pass import keyring import keyring.backends kr = None try: from keyring.backend.GnomeKeyring import Keyring kr = Keyring() except ImportError: try: from keyring.backend import GnomeKeyring kr = GnomeKeyring() except ImportError: pretty.print_error(__name__, "GnomeKeyring not found") if kr: keyring.set_keyring(kr) _KEYRING_NAME = _("GNOME Keyring") _KEYRING = kr return kr try: from keyring.backend.kwallet import Keyring kr = Keyring() except ImportError: try: from keyring.backend import KDEKWallet kr = KDEKWallet() except ImportError: pretty.print_error(__name__, "KDEKWallet not found") if kr: keyring.set_keyring(kr) _KEYRING_NAME = _("KWallet") _KEYRING = kr return kr kr = keyring.get_keyring() if hasattr(kr, "crypted_password"): UncryptedFileKeyring = None try: from keyring.backends.file import PlaintextKeyring as UncryptedFileKeyring except ImportError: from keyring.backend import UncryptedFileKeyring keyring.set_keyring(UncryptedFileKeyring()) kr = keyring.get_keyring() if hasattr(kr, "file_path"): kr.file_path = config.save_config_file("keyring.cfg") _KEYRING_NAME = _("Unencrypted File") _KEYRING = kr return kr
def is_available(self): return gnomekeyring.is_available()
def get_keyring(): """ Get one of working keyrings. """ global _KEYRING if _KEYRING is not None: # keyring configured return _KEYRING global _KEYRING_NAME try: import gnomekeyring if gnomekeyring.is_available(): # create fake keyring as long way by keyring module not work without # gi. class FakeGnomeKeyring: """ Proxy class emulate standard interface for Gnome Keyring. """ @staticmethod def get_password(plugin_id, username): kr_name = gnomekeyring.get_default_keyring_sync() for id_ in gnomekeyring.list_item_ids_sync(kr_name): attrs = gnomekeyring.item_get_attributes_sync(kr_name, id_) if (attrs.get('plugin_id') == plugin_id and attrs.get('username') == username): return gnomekeyring.item_get_info_sync(kr_name, id_).get_secret() @staticmethod def set_password(plugin_id, username, password): kr_name = gnomekeyring.get_default_keyring_sync() attrs = {'username': username, 'plugin_id': plugin_id} gnomekeyring.item_create_sync(kr_name, gnomekeyring.ITEM_GENERIC_SECRET, _("Password for %s in %s (Kupfer)") % (username, plugin_id), attrs, password, True) @staticmethod def supported(): return 1 _KEYRING = FakeGnomeKeyring _KEYRING_NAME = _("GNOME Keyring") return _KEYRING except ImportError: pass import keyring import keyring.backends kr = None try: from keyring.backend.GnomeKeyring import Keyring kr = Keyring() except ImportError: try: from keyring.backend import GnomeKeyring kr = GnomeKeyring() except ImportError: pretty.print_error(__name__, "GnomeKeyring not found") if kr: keyring.set_keyring(kr) _KEYRING_NAME = _("GNOME Keyring") _KEYRING = kr return kr try: from keyring.backend.kwallet import Keyring kr = Keyring() except ImportError: try: from keyring.backend import KDEKWallet kr = KDEKWallet() except ImportError: pretty.print_error(__name__, "KDEKWallet not found") if kr: keyring.set_keyring(kr) _KEYRING_NAME = _("KWallet") _KEYRING = kr return kr kr = keyring.get_keyring() if hasattr(kr, "crypted_password"): UncryptedFileKeyring = None try: from keyring.backends.file import PlaintextKeyring as UncryptedFileKeyring except ImportError: from keyring.backend import UncryptedFileKeyring keyring.set_keyring(UncryptedFileKeyring()) kr = keyring.get_keyring() if hasattr(kr, "file_path"): kr.file_path = config.save_config_file("keyring.cfg") _KEYRING_NAME = _("Unencrypted File") _KEYRING = kr return kr
GNOME_KEYRING = False try: import keyring GENERIC_KEYRING = True except: try: import gobject gobject.set_application_name('osc') import gnomekeyring if os.environ['GNOME_DESKTOP_SESSION_ID']: # otherwise gnome keyring bindings spit out errors, when you have # it installed, but you are not under gnome # (even though hundreds of gnome-keyring daemons got started in parallel) # another option would be to support kwallet here GNOME_KEYRING = gnomekeyring.is_available() except: pass def _get_processors(): """ get number of processors (online) based on SC_NPROCESSORS_ONLN (returns 1 if config name does not exist). """ try: return os.sysconf('SC_NPROCESSORS_ONLN') except ValueError as e: return 1 DEFAULTS = {'apiurl': 'https://api.opensuse.org',
def parse_args(self): ''' Parse commandline options. Returns False if something is wrong. ''' desc=\ '''By default %prog queries the GNOME keyring for items matching specified arguments. You can define the item exactly by --id, or search for it using -p and/or -i. It is important to understand that the keyring items are divided into several types (see --type) and each contain several properties. Both the item type and item properties can be inspected using a tool like Seahorse. Then you will know what to query for. Zero or more items may match your query. They will be printed out one item a line, by default in the format: ID [TAB] secret You can also create a new keyring item using --set. In this case the arguments -p and/or -i are mandatory and will be used as properties of the new item. When a new keyring item is created, its ID is printed out on the output.''' parser = MyOptionParser(description=desc, version=_version) parser.add_option('-t', '--type', choices=CLI.ITEM_TYPES.keys(), default='generic', help='type of keyring item: ' 'generic, network or note [default: %default]') parser.add_option('-k', '--keyring', help='keyring name [default: ' 'default keyring]', dest=self.keyring) parser.add_option('--id', type='int', help='key ID') parser.add_option( '-p', default='', metavar='PARAM1=VALUE1,PARAM2=VALUE2', dest='params', help='params and values of keyring item, e.g. user, server, ' 'protocol, etc.') parser.add_option( '-i', default='', metavar='PARAM1=VALUE1,PARAM2=VALUE2', dest='params_int', help='same as -p, but values are treated as integers, not strings') out_group = optparse.OptionGroup( parser, 'Formatting output for ' 'querying keyring items') out_group.add_option( '-o', '--output', default='id,secret', help='comma-separated list of columns to be printed on the output.' " Column name may include any name of item's property or keywords " "'id', 'secret' and 'name'. Columns will be separated by tabs. " "[default: %default]") out_group.add_option('-l', '--no-newline', action='store_true', help="don't output the trailing newline") out_group.add_option('-1', action='store_true', dest='output1', help="same as '--output secret --no-newline'") parser.add_option_group(out_group) set_group = optparse.OptionGroup( parser, 'Options specific for ' 'creating keyring items') set_group.add_option( '-s', '--set', action='store_true', default=False, help='create a new item in the keyring instead of querying') set_group.add_option( '-n', '--name', help='keyring item descriptive name [mandatory if --set]') set_group.add_option('-w', '--password', help='keyring item password') parser.add_option_group(set_group) epilog=\ """Example usage: $ %(prog)s --id 12 Get keyring item with ID 12 in default keyring. $ %(prog)s -p [email protected] -i gajim=1 -1 Search for keyring item with property 'account_name' with value '*****@*****.**' and property 'gajim' with integer value '1'. Output only the secret(s). $ %(prog)s --type network -p server=my.com,protocol=ftp --output user,secret Search for network keyring item with 'server' and 'protocol' properties. Output property 'user' followed by item's secret. $ %(prog)s --set --name 'foo' -p bar=baz --keyring login Create a new item in keyring 'login' with name 'foo' and property 'bar'.""" parser.epilog = epilog % {'prog': parser.get_prog_name()} (options, args) = parser.parse_args() self.options = options # ensure that the application name is correctly set # this must be done after parsing args, because # our --name option collides with gtk option --name import gtk if not gk.is_available(): print >> sys.stderr, 'GNOME keyring is not available!' return False if not options.params and not options.params_int and \ (options.set or not options.id): parser.error('Missing option -p or -i! See --help.') # parse string params try: tuples = options.params.split(',') # Allow ',' in the parameter values if len(tuples) != options.params.count('='): tuples = [] for elem in options.params.split(','): if '=' not in elem: tuples[-1] = tuples[-1] + ',' + elem else: tuples += [ elem, ] for tupl in tuples: if not tupl: # empty string continue name, val = tupl.split('=', 1) self.params[name] = val except ValueError, e: parser.error('Incorrect syntax of "-p param1=value1,' 'param2=value2"! See --help.\nDetails:\n%s' % e)
login_page = login_page.read() except: stderr.write("Error while accessing login page.\ Likely to be a networking problem.\n") exit(-1) try: found = re.search('(?<=<INPUT type=hidden name=chalangeack value=)\w*', login_page) chalangeack = found.group(0) except: stderr.write("Error while manipulating login page.\ Maybe its format has changed.\n") exit(-2) if not gk.is_available(): print "Error with the keyring daemon." exit(-100) if not 'login' in gk.list_keyring_names_sync(): print "Error: no 'login' keyering. Edit the sources to select\ another keyring." exit(-101) creditals = get_creditals() if creditals == None: print "No login data found" from getpass import getpass login = getpass("Login: ") password = getpass()
def test_keyring_available(self): available = gk.is_available() self.assertTrue(available)
def is_available(self): """Return true if we are able to use Gnome keyring""" return keyring is not None and keyring.is_available()
tostr = lambda lts: lts try: import ssl except ImportError: ssl = None try: import hashlib except ImportError: hashlib = None # Optional gnome-keyring integration try: import gnomekeyring # And test to see if it's actually available if not gnomekeyring.is_available(): gnomekeyring = None except ImportError: gnomekeyring = None from getmailcore.exceptions import * logtimeformat = '%Y-%m-%d %H:%M:%S' _bool_values = { 'true': True, 'yes': True, 'on': True, '1': True, 'false': False, 'no': False, 'off': False,
#!/usr/bin/pyhton import gnomekeyring as gk if gk.is_available(): attrs = {'keyring': 'LOCAL:/keyrings/default.keyring'} gk.item_create_sync('login', gk.ITEM_GENERIC_SECRET, 'Unlock password for: default', attrs, 'asfsdgfdfgh', True) else: print "Gnome Keyring is not avaialable." # gk.list_keyring_names_sync() # ['session', 'default', 'mozilla', 'login']