Load host keys from an openssh :file:`known_hosts`-style file. Can
        be called multiple times.

        If *filename* is not specified, looks in the default locations i.e. :file:`~/.ssh/known_hosts` and :file:`~/ssh/known_hosts` for Windows.
1200
def load_known_hosts(self, filename=None):

        

        if filename is None:
            filename = os.path.expanduser('~/.ssh/known_hosts')
            try:
                self._host_keys.load(filename)
            except IOError:
                # for windows
                filename = os.path.expanduser('~/ssh/known_hosts')
                try:
                    self._host_keys.load(filename)
                except IOError:
                    pass
        else:
            self._host_keys.load(filename)
1289032
def _get_host(self, hostname):
        
        if hostname not in self.hosts:
            self.hosts[hostname] = {
                'groups': set(),
                'hostvars': {}
            }
        return self.hosts[hostname]
626999
def load_keys(path = nil)
        path ||= File.join(@path, @keydir)
        keys = Hash.new {|k,v| k[v] = DirtyProxy.new([])}

        list_keys(path).each do |key|
          new_key = SSHKey.from_file(File.join(path, key))
          owner = new_key.owner

          keys[owner] << new_key
        end
        #Mark key sets as unmodified (for dirty checking)
        keys.values.each{|set| set.clean_up!}

        keys
      end
90391
def _parse_openssh_output(lines, fingerprint_hash_type=None):
    '''
    
    '''
    for line in lines:
        # We don't need any whitespace-only containing lines or arbitrary doubled newlines
        line = line.strip()
        if line == '':
            continue
        line += '\n'

        if line.startswith('#'):
            continue
        try:
            hostname, enc, key = line.split()
        except ValueError:  # incorrect format
            continue
        fingerprint = _fingerprint(key,
                                   fingerprint_hash_type=fingerprint_hash_type)
        if not fingerprint:
            continue
        yield {'hostname': hostname, 'key': key, 'enc': enc,
               'fingerprint': fingerprint}
410998
def __get_known_node_by_host(self, hostname):
        '''
        
        '''
        for n in self.nodes:
            if (n.name == hostname):
                return n
        return None
68633
def ssh_cleanup_known_hosts!(hosts=[host, public_ip])
      hosts = [hosts] unless hosts.respond_to? :each
      hosts.compact.each do |name|
        system_run "ssh-keygen -R %s" % name
      end
    end
1210866
def get_public_keys(vm_):
    '''
    
    '''
    key_filename = config.get_cloud_config_value(
        'ssh_public_key', vm_, __opts__, search_global=False, default=None
    )
    if key_filename is not None:
        key_filename = os.path.expanduser(key_filename)
        if not os.path.isfile(key_filename):
            raise SaltCloudConfigError(
                'The defined ssh_public_key \'{0}\' does not exist'.format(
                    key_filename
                )
            )
        ssh_keys = []
        with salt.utils.files.fopen(key_filename) as rfh:
            for key in rfh.readlines():
                ssh_keys.append(salt.utils.stringutils.to_unicode(key))

        return ssh_keys
650885
def _normalize_hosts(hosts):
    
    # if hosts are empty, just defer to defaults down the line
    if hosts is None:
        return [{}]

    # passed in just one string
    if isinstance(hosts, string_types):
        hosts = [hosts]

    out = []
    # normalize hosts to dicts
    for host in hosts:
        if isinstance(host, string_types):
            if "://" not in host:
                host = "//%s" % host

            parsed_url = urlparse(host)
            h = {"host": parsed_url.hostname}

            if parsed_url.port:
                h["port"] = parsed_url.port

            if parsed_url.scheme == "https":
                h["port"] = parsed_url.port or 443
                h["use_ssl"] = True

            if parsed_url.username or parsed_url.password:
                h["http_auth"] = "%s:%s" % (
                    unquote(parsed_url.username),
                    unquote(parsed_url.password),
                )

            if parsed_url.path and parsed_url.path != "/":
                h["url_prefix"] = parsed_url.path

            out.append(h)
        else:
            out.append(host)
    return out
843040
def gatherkeys(args):
    
    oldmask = os.umask(0o77)
    try:
        try:
            tmpd = tempfile.mkdtemp()
            LOG.info("Storing keys in temp directory %s", tmpd)
            sucess = False
            for host in args.mon:
                sucess = gatherkeys_with_mon(args, host, tmpd)
                if sucess:
                    break
            if not sucess:
                LOG.error("Failed to connect to host:%s" ,', '.join(args.mon))
                raise RuntimeError('Failed to connect any mon')
            had_error = False
            date_string = time.strftime("%Y%m%d%H%M%S")
            for keytype in ["admin", "mds", "mgr", "mon", "osd", "rgw"]:
                filename = keytype_path_to(args, keytype)
                tmp_path = os.path.join(tmpd, filename)
                if not os.path.exists(tmp_path):
                    LOG.error("No key retrived for '%s'" , keytype)
                    had_error = True
                    continue
                if not os.path.exists(filename):
                    LOG.info("Storing %s" % (filename))
                    shutil.move(tmp_path, filename)
                    continue
                if _keyring_equivalent(tmp_path, filename):
                    LOG.info("keyring '%s' already exists" , filename)
                    continue
                backup_keyring = "%s-%s" % (filename, date_string)
                LOG.info("Replacing '%s' and backing up old key as '%s'", filename, backup_keyring)
                shutil.copy(filename, backup_keyring)
                shutil.move(tmp_path, filename)
            if had_error:
                raise RuntimeError('Failed to get all key types')
        finally:
            LOG.info("Destroy temp directory %s" %(tmpd))
            shutil.rmtree(tmpd)
    finally:
        os.umask(oldmask)
523539
def _connect_ssh(spec):
    
    if C.HOST_KEY_CHECKING:
        check_host_keys = 'enforce'
    else:
        check_host_keys = 'ignore'

    # #334: tilde-expand private_key_file to avoid implementation difference
    # between Python and OpenSSH.
    private_key_file = spec.private_key_file()
    if private_key_file is not None:
        private_key_file = os.path.expanduser(private_key_file)

    return {
        'method': 'ssh',
        'kwargs': {
            'check_host_keys': check_host_keys,
            'hostname': spec.remote_addr(),
            'username': spec.remote_user(),
            'compression': convert_bool(
                default(spec.mitogen_ssh_compression(), True)
            ),
            'password': spec.password(),
            'port': spec.port(),
            'python_path': spec.python_path(),
            'identity_file': private_key_file,
            'identities_only': False,
            'ssh_path': spec.ssh_executable(),
            'connect_timeout': spec.ansible_ssh_timeout(),
            'ssh_args': spec.ssh_args(),
            'ssh_debug_level': spec.mitogen_ssh_debug_level(),
            'remote_name': get_remote_name(spec),
        }
    }
493339
def load_configuration(self, configuration_file):
        '''
        '''
        if os.path.isfile(configuration_file):
            if not isinstance(configuration_file, tb.file.File) and os.path.splitext(configuration_file)[1].strip().lower() != ".h5":
                load_configuration_from_text_file(self, configuration_file)
            else:
                load_configuration_from_hdf5(self, configuration_file)
        else:
            raise ValueError('Cannot find configuration file specified: %s' % configuration_file)
62350
def load(self, filename):
        
        # Compute sha1 hash (key)
        with open(filename) as fp:
            key = sha1(fp.read()).hexdigest()
        path = self.key_to_path(key)
        # Return the cached file if available
        if key in self.hashes:
            try:
                with open(path) as fp:
                    return cPickle.load(fp)
            except EOFError:
                os.unlink(path)
                self.hashes.remove(key)
            except IOError:
                self.hashes.remove(key)
        # Create the nested cache directory
        try:
            os.makedirs(os.path.dirname(path))
        except OSError as exc:
            if exc.errno != errno.EEXIST:
                raise
        # Process the file and save in the cache
        scratch = kurt.Project.load(filename)  # can fail
        with os.fdopen(os.open(path, os.O_WRONLY | os.O_CREAT,
                               0400), 'w') as fp:
            # open file for writing but make it immediately read-only
            cPickle.dump(scratch, fp, cPickle.HIGHEST_PROTOCOL)
        self.hashes.add(key)
        return scratch
558023
def keys(self):
        """"""
        keys = Struct.keys(self)
        for key in (
                '_cloud_provider',
                '_naming_policy',
                '_setup_provider',
                'known_hosts_file',
                'repository',
        ):
            if key in keys:
                keys.remove(key)
        return keys
180324
def file_hash(load, fnd):
    '''
    
    '''
    path = fnd['path']
    ret = {}

    if 'env' in load:
        # "env" is not supported; Use "saltenv".
        load.pop('env')

    if load['saltenv'] not in envs():
        return {}

    # if the file doesn't exist, we can't get a hash
    if not path or not os.path.isfile(path):
        return ret

    # set the hash_type as it is determined by config-- so mechanism won't change that
    ret['hash_type'] = __opts__['hash_type']

    # check if the hash is cached
    # cache file's contents should be "hash:mtime"
    cache_path = os.path.join(
        __opts__['cachedir'],
        'minionfs',
        'hash',
        load['saltenv'],
        '{0}.hash.{1}'.format(fnd['rel'], __opts__['hash_type'])
    )
    # if we have a cache, serve that if the mtime hasn't changed
    if os.path.exists(cache_path):
        try:
            with salt.utils.files.fopen(cache_path, 'rb') as fp_:
                try:
                    hsum, mtime = salt.utils.stringutils.to_unicode(fp_.read()).split(':')
                except ValueError:
                    log.debug(
                        'Fileserver attempted to read incomplete cache file. '
                        'Retrying.'
                    )
                    file_hash(load, fnd)
                    return ret
                if os.path.getmtime(path) == mtime:
                    # check if mtime changed
                    ret['hsum'] = hsum
                    return ret
        # Can't use Python select() because we need Windows support
        except os.error:
            log.debug(
                'Fileserver encountered lock when reading cache file. '
                'Retrying.'
            )
            file_hash(load, fnd)
            return ret

    # if we don't have a cache entry-- lets make one
    ret['hsum'] = salt.utils.hashutils.get_hash(path, __opts__['hash_type'])
    cache_dir = os.path.dirname(cache_path)
    # make cache directory if it doesn't exist
    if not os.path.exists(cache_dir):
        os.makedirs(cache_dir)
    # save the cache object "hash:mtime"
    cache_object = '{0}:{1}'.format(ret['hsum'], os.path.getmtime(path))
    with salt.utils.files.flopen(cache_path, 'w') as fp_:
        fp_.write(cache_object)
    return ret
1350577
def load(self, filename):
        """"""
        with open(filename, 'r') as fin:
            proxies = json.load(fin)
        for protocol in proxies:
            for proxy in proxies[protocol]:
                self.proxies[protocol][proxy['addr']] = Proxy(
                    proxy['addr'], proxy['protocol'], proxy['weight'],
                    proxy['last_checked'])
                self.addr_list[protocol].append(proxy['addr'])
113416
def add_to_known_hosts(self, hosts, known_hosts=DEFAULT_KNOWN_HOSTS, dry=False):
        
        to_add = []
        with open(known_hosts) as fh:
            known_hosts_set = set(line.strip() for line in fh.readlines())

        cmd = ['ssh-keyscan'] + [host.hostname for host in hosts]
        logger.debug('Call: %s',  ' '.join(cmd))
        p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        stdout, stderr = p.communicate()
        for line in stdout.splitlines():
            line = line.strip()
            logger.info('[%s] Add the remote host SSH public key to [%s]...', line.split(' ', 1)[0], known_hosts)
            if line not in known_hosts_set:
                known_hosts_set.add(line)
                to_add.append('{0}\n'.format(line))

        if not dry:
            with open(known_hosts, 'a') as fh:
                fh.writelines(to_add)
884240
def open(
        self,
        hostname: Optional[str],
        username: Optional[str],
        password: Optional[str],
        port: Optional[int],
        platform: Optional[str],
        extras: Optional[Dict[str, Any]] = None,
        configuration: Optional[Config] = None,
    ) -> None:
        
        pass