Пример #1
0
 def __init__(self, crypter, filename=None, can_create=True,
              cache_timeout=None):
     super(BasicKeyring, self).__init__()
     self._crypter = crypter
     def_fn = os.path.join(platform_.data_root(), self.__class__._filename)
     self._filename = filename or def_fn
     self._can_create = can_create
     self._cache_timeout = cache_timeout
 def __init__(self, crypter, filename=None, can_create=True,
              cache_timeout=None):
     super(BasicKeyring, self).__init__()
     self._crypter = crypter
     def_fn = os.path.join(platform_.data_root(), self.__class__._filename)
     self._filename = filename or def_fn
     self._can_create = can_create
     self._cache_timeout = cache_timeout
Пример #3
0
def run(args):
    """Handle keyring script."""
    parser = argparse.ArgumentParser(
        description=(
            "Modify Home Assistant secrets in the default keyring. "
            "Use the secrets in configuration files with: "
            "!secret <name>"
        )
    )
    parser.add_argument("--script", choices=["keyring"])
    parser.add_argument(
        "action",
        choices=["get", "set", "del", "info"],
        help="Get, set or delete a secret",
    )
    parser.add_argument("name", help="Name of the secret", nargs="?", default=None)

    import keyring
    from keyring.util import platform_ as platform

    args = parser.parse_args(args)

    if args.action == "info":
        keyr = keyring.get_keyring()
        print("Keyring version {}\n".format(REQUIREMENTS[0].split("==")[1]))
        print("Active keyring  : {}".format(keyr.__module__))
        config_name = os.path.join(platform.config_root(), "keyringrc.cfg")
        print("Config location : {}".format(config_name))
        print("Data location   : {}\n".format(platform.data_root()))
    elif args.name is None:
        parser.print_help()
        return 1

    if args.action == "set":
        entered_secret = getpass.getpass(
            "Please enter the secret for {}: ".format(args.name)
        )
        keyring.set_password(_SECRET_NAMESPACE, args.name, entered_secret)
        print("Secret {} set successfully".format(args.name))
    elif args.action == "get":
        the_secret = keyring.get_password(_SECRET_NAMESPACE, args.name)
        if the_secret is None:
            print("Secret {} not found".format(args.name))
        else:
            print("Secret {}={}".format(args.name, the_secret))
    elif args.action == "del":
        try:
            keyring.delete_password(_SECRET_NAMESPACE, args.name)
            print("Deleted secret {}".format(args.name))
        except keyring.errors.PasswordDeleteError:
            print("Secret {} not found".format(args.name))
Пример #4
0
def run(args):
    """Handle keyring script."""
    parser = argparse.ArgumentParser(
        description=("Modify Home Assistant secrets in the default keyring. "
                     "Use the secrets in configuration files with: "
                     "!secret <name>"))
    parser.add_argument('--script', choices=['keyring'])
    parser.add_argument('action',
                        choices=['get', 'set', 'del', 'info'],
                        help="Get, set or delete a secret")
    parser.add_argument('name',
                        help="Name of the secret",
                        nargs='?',
                        default=None)

    import keyring
    from keyring.util import platform_ as platform

    args = parser.parse_args(args)

    if args.action == 'info':
        keyr = keyring.get_keyring()
        print('Keyring version {}\n'.format(REQUIREMENTS[0].split('==')[1]))
        print('Active keyring  : {}'.format(keyr.__module__))
        config_name = os.path.join(platform.config_root(), 'keyringrc.cfg')
        print('Config location : {}'.format(config_name))
        print('Data location   : {}\n'.format(platform.data_root()))
    elif args.name is None:
        parser.print_help()
        return 1

    if args.action == 'set':
        the_secret = getpass.getpass('Please enter the secret for {}: '.format(
            args.name))
        keyring.set_password(_SECRET_NAMESPACE, args.name, the_secret)
        print('Secret {} set successfully'.format(args.name))
    elif args.action == 'get':
        the_secret = keyring.get_password(_SECRET_NAMESPACE, args.name)
        if the_secret is None:
            print('Secret {} not found'.format(args.name))
        else:
            print('Secret {}={}'.format(args.name, the_secret))
    elif args.action == 'del':
        try:
            keyring.delete_password(_SECRET_NAMESPACE, args.name)
            print('Deleted secret {}'.format(args.name))
        except keyring.errors.PasswordDeleteError:
            print('Secret {} not found'.format(args.name))
Пример #5
0
def run(args):
    """Handle keyring script."""
    parser = argparse.ArgumentParser(
        description=("Modify Home Assistant secrets in the default keyring. "
                     "Use the secrets in configuration files with: "
                     "!secret <name>"))
    parser.add_argument(
        '--script', choices=['keyring'])
    parser.add_argument(
        'action', choices=['get', 'set', 'del', 'info'],
        help="Get, set or delete a secret")
    parser.add_argument(
        'name', help="Name of the secret", nargs='?', default=None)

    import keyring
    from keyring.util import platform_ as platform

    args = parser.parse_args(args)

    if args.action == 'info':
        keyr = keyring.get_keyring()
        print('Keyring version {}\n'.format(keyring.__version__))
        print('Active keyring  : {}'.format(keyr.__module__))
        config_name = os.path.join(platform.config_root(), 'keyringrc.cfg')
        print('Config location : {}'.format(config_name))
        print('Data location   : {}\n'.format(platform.data_root()))
    elif args.name is None:
        parser.print_help()
        return 1

    if args.action == 'set':
        the_secret = getpass.getpass(
            'Please enter the secret for {}: '.format(args.name))
        keyring.set_password(_SECRET_NAMESPACE, args.name, the_secret)
        print('Secret {} set successfully'.format(args.name))
    elif args.action == 'get':
        the_secret = keyring.get_password(_SECRET_NAMESPACE, args.name)
        if the_secret is None:
            print('Secret {} not found'.format(args.name))
        else:
            print('Secret {}={}'.format(args.name, the_secret))
    elif args.action == 'del':
        try:
            keyring.delete_password(_SECRET_NAMESPACE, args.name)
            print('Deleted secret {}'.format(args.name))
        except keyring.errors.PasswordDeleteError:
            print('Secret {} not found'.format(args.name))
Пример #6
0
 def __init__(self, crypter, filename=None, can_create=True, cache_timeout=None):
     super(BasicKeyring, self).__init__()
     self._crypter = crypter
     if filename is None:
         self._filename = os.path.join(
             platform_.data_root(), self.__class__._filename
         )
     elif filename.endswith("/"):
         self._filename = os.path.join(filename, self.__class__._filename)
     else:
         self._filename = filename
     self._can_create = can_create
     self._cache_timeout = cache_timeout
     # open the fs for the session.  this in particular is for the
     # transient fs types, like tempfs, memfs, and any other where reopening
     # creates a new store.
     # print(
     #     "Opening file {}, filename {} at path {}".format(
     #         self._filename, self.filename, self.file_path
     #     )
     # )
     self._pyfs = None
     if FS_VER < version.parse("2.0.0"):
         # pre-2.0 version of memoryfs does not handle create_dir flag properly.
         # with nested subdir with more than 2 levels, cause the inner most subdir
         # creation to fail with "no parent" message.
         if self._filename.startswith("mem://") or self._filename.startswith(
             "ram://"
         ):
             self._pyfs = fs.opener.fsopendir(self.file_path, writeable=True)
         else:
             self._pyfs = fs.opener.fsopendir(
                 self.file_path, writeable=True, create_dir=self._can_create
             )
         # cache if permitted
         if self._cache_timeout is not None:
             self._pyfs = fs.remote.CacheFS(
                 self._pyfs, cache_timeout=self._cache_timeout
             )
     else:
         self._pyfs = open_fs(
             self.file_path, writeable=True, create=self._can_create
         )
         # cache if permitted
         if self._cache_timeout is not None:
             self._pyfs = fs.wrap.cache_directory(self._pyfs)
Пример #7
0
def load_config():
    """Load a keyring using the config file.

    The config file can be in the current working directory, or in the user's
    home directory.
    """
    keyring = None

    filename = 'keyringrc.cfg'

    local_path = os.path.join(os.getcwd(), filename)
    config_path = os.path.join(platform.data_root(), filename)

    # search from current working directory and the data root
    keyring_cfg_candidates = [local_path, config_path]

    # initialize the keyring_config with the first detected config file
    keyring_cfg = None
    for path in keyring_cfg_candidates:
        keyring_cfg = path
        if os.path.exists(path):
            break

    if os.path.exists(keyring_cfg):
        config = configparser.RawConfigParser()
        config.read(keyring_cfg)
        _load_keyring_path(config)

        # load the keyring class name, and then load this keyring
        try:
            if config.has_section("backend"):
                keyring_name = config.get("backend", "default-keyring").strip()
            else:
                raise configparser.NoOptionError('backend', 'default-keyring')

            keyring = load_keyring(None, keyring_name)
        except (configparser.NoOptionError, ImportError):
            logger.warning("Keyring config file contains incorrect values.\n" +
                           "Config file: %s" % keyring_cfg)

    return keyring
Пример #8
0
def load_config():
    """Load a keyring using the config file.

    The config file can be in the current working directory, or in the user's
    home directory.
    """
    keyring = None

    filename = 'keyringrc.cfg'

    local_path = os.path.join(os.getcwd(), filename)
    config_path = os.path.join(platform.data_root(), filename)

    # search from current working directory and the data root
    keyring_cfg_candidates = [local_path, config_path]

    # initialize the keyring_config with the first detected config file
    keyring_cfg = None
    for path in keyring_cfg_candidates:
        keyring_cfg = path
        if os.path.exists(path):
            break

    if os.path.exists(keyring_cfg):
        config = configparser.RawConfigParser()
        config.read(keyring_cfg)
        _load_keyring_path(config)

        # load the keyring class name, and then load this keyring
        try:
            if config.has_section("backend"):
                keyring_name = config.get("backend", "default-keyring").strip()
            else:
                raise configparser.NoOptionError('backend', 'default-keyring')

            keyring = load_keyring(None, keyring_name)
        except (configparser.NoOptionError, ImportError):
            logger.warning("Keyring config file contains incorrect values.\n" +
                           "Config file: %s" % keyring_cfg)

    return keyring
Пример #9
0
def _describe_credentials():
    import keyring
    from keyring.util import platform_

    def describe_keyring_backend(be):
        be_repr = repr(be)
        return be.name if 'object at 0' in be_repr else be_repr.strip('<>')

    # might later add information on non-keyring credentials gh-4981
    props = {}

    active_keyring = keyring.get_keyring()
    krp = {
        'config_file':
        Path(platform_.config_root(), 'keyringrc.cfg'),
        'data_root':
        platform_.data_root(),
        'active_backends': [
            describe_keyring_backend(be)
            for be in getattr(active_keyring, 'backends', [active_keyring])
        ],
    }
    props.update(keyring=krp, )
    return props
Пример #10
0
 def file_path(self):
     """
     The path to the file where passwords are stored. This property
     may be overridden by the subclass or at the instance level.
     """
     return os.path.join(platform_.data_root(), self.filename)
Пример #11
0
 def file_path(self):
     """
     The path to the file where passwords are stored. This property
     may be overridden by the subclass or at the instance level.
     """
     return os.path.join(platform_.data_root(), self.filename)