Copy the SSH keys to the given host.

        :param host: the `Host` object to copy the SSH keys to.
        :param known_hosts: the `known_hosts` file to store the SSH public keys.
        :raise paramiko.ssh_exception.AuthenticationException:
779793
def copy_ssh_keys_to_host(self, host, known_hosts=DEFAULT_KNOWN_HOSTS):
        
        password = host.password or self.sshcopyid.default_password
        try:
            self.sshcopyid.copy_ssh_keys_to_host(host, password=password, no_add_host=self.args.no_add_host,
                                                 known_hosts=known_hosts)

        except paramiko.ssh_exception.AuthenticationException:
            if password:
                # A password was given, and it is wrong
                raise
            else:
                # Ask for password
                password = utils.get_password()
                self.sshcopyid.default_password = password

                # Try to connect again
                self.sshcopyid.copy_ssh_keys_to_host(host, password=password, no_add_host=self.args.no_add_host,
                                                     known_hosts=known_hosts)
1053586
def _can_connect(host, port=22):  # type: (str, int) -> bool
    
    try:
        logger.debug('Testing connection to host %s', host)
        client = paramiko.SSHClient()
        client.load_system_host_keys()
        client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        client.connect(host,
                       port=port)
        client.close()
        logger.info('Can connect to host %s', host)
        return True
    except Exception as e:
        logger.info('Cannot connect to host %s', host)

        logger.info('Connection failed with exception: \n %s', str(e))
        return False
961431
def get_password(self, host=None):
        
        if host is None:
            return self._password_dict
        else:
            try:
                return self._password_dict[host]
            except (KeyError, TypeError):
                try:
                    return self._password_dict['default']
                except (KeyError, TypeError):
                    return None
110359
def merge(self, hosts):
        
        for extinfo in self:
            host_name = extinfo.get_name()
            host = hosts.find_by_name(host_name)
            if host is not None:
                # Fusion
                self.merge_extinfo(host, extinfo)
712571
async def add_ssh_key(self, user, key):
        
        key_facade = client.KeyManagerFacade.from_connection(self.connection())
        return await key_facade.AddKeys([key], user)
791928
def remote_ssh(self, host):
        
        logger.info('Starting remote execution of task {0} on host {1}'.format(self.name, host['hostname']))
        try:
            self.remote_client = paramiko.SSHClient()
            self.remote_client.load_system_host_keys()
            self.remote_client.set_missing_host_key_policy(
                paramiko.AutoAddPolicy())
            self.remote_client.connect(host['hostname'], username=host['user'],
                                       key_filename=host['identityfile'][0],
                                       timeout=82800)
            transport = self.remote_client.get_transport()
            transport.set_keepalive(10)

            self.remote_channel = transport.open_session()
            self.remote_channel.get_pty()
            self.remote_channel.exec_command(self.command)
        except Exception as e:
            logger.warn('Exception encountered in remote task execution')
            self.remote_failure = True
            self.stderr += 'Exception when trying to SSH related to: '
            self.stderr += '{0}: {1}\n"'.format(type(e).__name__, str(e))
            self.stderr += 'Was looking for host "{0}"\n'.format(str(host))
            self.stderr += 'Found in config:\n'
            self.stderr += 'host: "{0}"\n'.format(str(host))
            self.stderr += 'hostname: "{0}"\n'.format(str(host.get('hostname')))
            self.stderr += 'user: "{0}"\n'.format(str(host.get('user')))
            self.stderr += 'identityfile: "{0}"\n'.format(str(host.get('identityfile')))
            self.remote_client.close()
769630
def _verifyHostKey(self, hostKey, fingerprint):
        
        if fingerprint in self.knownHosts:
            return defer.succeed(True)
        return defer.fail(UnknownHostKey(hostKey, fingerprint))
94080
def setup(self):
        ''''''
        log.debug( 'New request from address %s, port %d',  self.client_address )
        
        try:
            self.transport.load_server_moduli()
        except:
            log.exception( '(Failed to load moduli -- gex will be unsupported.)' )
            raise
        try:
            self.transport.add_server_key(self.host_key)
        except:
            if self.host_key is None:
                log.critical('Host key not set!  SSHHandler MUST define the host_key parameter.')
                raise NotImplementedError('Host key not set!  SSHHandler instance must define the host_key parameter.  Try host_key = paramiko_ssh.getRsaKeyFile("server_rsa.key").')
        
        try:
            # Tell transport to use this object as a server
            log.debug( 'Starting SSH server-side negotiation' )
            self.transport.start_server(server=self)
        except SSHException, e:
           log.warn('SSH negotiation failed. %s', e)
           raise
        
        # Accept any requested channels
        while True:
            channel = self.transport.accept(20)
            if channel is None:
                # check to see if any thread is running
                any_running = False
                for c, thread in self.channels.items():
                    if thread.is_alive():
                        any_running = True
                        break
                if not any_running:
                    break
            else:
                log.info( 'Accepted channel %s', channel )
13312
def _use_ssh_config(self, dict_arg):
        
        connect_dict = dict_arg.copy()

        # Use SSHConfig to generate source content.
        full_path = path.abspath(path.expanduser(self.ssh_config_file))
        if path.exists(full_path):
            ssh_config_instance = paramiko.SSHConfig()
            with io.open(full_path, "rt", encoding="utf-8") as f:
                ssh_config_instance.parse(f)
                source = ssh_config_instance.lookup(self.host)
        else:
            source = {}

        if "proxycommand" in source:
            proxy = paramiko.ProxyCommand(source["proxycommand"])
        elif "ProxyCommand" in source:
            proxy = paramiko.ProxyCommand(source["ProxyCommand"])
        else:
            proxy = None

        # Only update 'hostname', 'sock', 'port', and 'username'
        # For 'port' and 'username' only update if using object defaults
        if connect_dict["port"] == 22:
            connect_dict["port"] = int(source.get("port", self.port))
        if connect_dict["username"] == "":
            connect_dict["username"] = source.get("user", self.username)
        if proxy:
            connect_dict["sock"] = proxy
        connect_dict["hostname"] = source.get("hostname", self.host)

        return connect_dict
245374
def _server_known(cls, host, port):
        
        with PostgreSql._known_servers_lock:
            return (host, port) in PostgreSql._known_servers
396914
def _key_deploy_run(self, host, target, re_run=True):
        '''
        
        '''
        argv = [
            'ssh.set_auth_key',
            target.get('user', 'root'),
            self.get_pubkey(),
        ]

        single = Single(
                self.opts,
                argv,
                host,
                mods=self.mods,
                fsclient=self.fsclient,
                thin=self.thin,
                **target)
        if salt.utils.path.which('ssh-copy-id'):
            # we have ssh-copy-id, use it!
            stdout, stderr, retcode = single.shell.copy_id()
        else:
            stdout, stderr, retcode = single.run()
        if re_run:
            target.pop('passwd')
            single = Single(
                    self.opts,
                    self.opts['argv'],
                    host,
                    mods=self.mods,
                    fsclient=self.fsclient,
                    thin=self.thin,
                    **target)
            stdout, stderr, retcode = single.cmd_block()
            try:
                data = salt.utils.json.find_json(stdout)
                return {host: data.get('local', data)}
            except Exception:
                if stderr:
                    return {host: stderr}
                return {host: 'Bad Return'}
        if salt.defaults.exitcodes.EX_OK != retcode:
            return {host: stderr}
        return {host: stdout}
1022483
def get_ssh_host_keys()
      # Try to read the sshd_config file first
      keys = File.readlines(
        File.join(RightScale::Platform.filesystem.ssh_cfg_dir, 'sshd_config')).map do |l|
          key = nil
          /^\s*HostKey\s+([^ ].*)/.match(l) { |m| key = m.captures[0] }
          key
        end.compact

      # If the config file was empty, try these defaults
      keys = keys.empty? ? SSH_DEFAULT_KEYS : keys

      # Assume the public keys are just the public keys with '.pub' extended and
      # read in each existing key.
      keys.map { |k| k="#{k}.pub"; File.exists?(k) ? File.read(k) : nil }.compact
    end
1001980
def GetUnreachableHosts(hostnames, ssh_key):
  
  ssh_status = AreHostsReachable(hostnames, ssh_key)
  assert(len(hostnames) == len(ssh_status))
  nonresponsive_hostnames = [host for (host, ssh_ok) in
                             zip(hostnames, ssh_status) if not ssh_ok]
  return nonresponsive_hostnames
188228
def host=(new_host)
      if new_host && !new_host.respond_to?(:to_str)
        raise TypeError, "Can't convert #{new_host.class} into String."
      end
      @host = new_host ? new_host.to_str : nil

      # Reset dependent values
      remove_instance_variable(:@authority) if defined?(@authority)
      remove_instance_variable(:@normalized_host) if defined?(@normalized_host)
      remove_composite_values

      # Ensure we haven't created an invalid URI
      validate()
    end
746935
def _prepare_connection(**kwargs):
    '''
    
    '''
    paramiko_kwargs, scp_kwargs = _select_kwargs(**kwargs)
    ssh = paramiko.SSHClient()
    if paramiko_kwargs.pop('auto_add_policy', False):
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(**paramiko_kwargs)
    scp_client = scp.SCPClient(ssh.get_transport(),
                               **scp_kwargs)
    return scp_client
1060096
def PrivateToPublicOpenSSH(key, host):
  
  # Create public key from private key.
  ssh_rsa = '00000007' + base64.b16encode('ssh-rsa')
  # Exponent.
  exponent = '%x' % (key.e,)
  if len(exponent) % 2:
      exponent = '0' + exponent
  ssh_rsa += '%08x' % (len(exponent) / 2,)
  ssh_rsa += exponent
  modulus = '%x' % (key.n,)
  if len(modulus) % 2:
      modulus = '0' + modulus
  if modulus[0] in '89abcdef':
      modulus = '00' + modulus
  ssh_rsa += '%08x' % (len(modulus) / 2,)
  ssh_rsa += modulus
  hash_string = base64.b64encode(base64.b16decode(ssh_rsa.upper()))
  public_key = 'ssh-rsa %s %s' % (hash_string, host)
  return public_key
595299
def copy(self):
        
        c = copy.deepcopy(self)
        for key in c.conns:
            c.conns[key] = self.conns[key].copy()
        return c