Helper method to aggregate RemoteTasks into single ssh session.
432173
def _aggregate(self):
        """"""
        # pylint: disable=W0212
        nonremote = [t for t in self._tasks if not isinstance(t, RemoteTask)]
        remote = [t for t in self._tasks if isinstance(t, RemoteTask)]

        host_dict = defaultdict(list)
        for task in remote:
            host_dict[task.host].append(task)

        aggregated = []
        for task_group in host_dict.values():
            # Build up combined command
            combined_cmd = []
            for task in task_group:
                if combined_cmd:
                    combined_cmd.append('&')
                combined_cmd.append(' '.join(task._remote_command))

            # Now, generated aggregate task
            t0 = task_group[0] # pylint: disable=C0103
            task = RemoteTask(
                t0.host, combined_cmd, t0._quiet, t0._return_output,
                t0._kill_remote, t0._identity_file)

            aggregated.append(task)

        self._tasks = nonremote + aggregated
423904
def RunCommandOnHosts(cmd, hostnames, ssh_key):
  
  if not hostnames:
    return
  p = multiprocessing.Pool(1)
  remote_command_args = [(cmd, hostname, ssh_key) for hostname in hostnames]
  #print remote_command_args
  result = None
  while not result:
    try:    
      result = p.map_async(__RemoteExecuteHelper, remote_command_args).get(999999) # allows for keyboard interrupt
    except paramiko.SSHException as e:      
      logging.info( 'failure in RunCommandOnHosts: %s' % (e))
      time.sleep(5)
    
  p.close()
  p.join()
  return result
552464
function createDirs(next) {
      if (!options.files || !options.files.length) {
        return next();
      }

      self.ssh({
        keys: options.keys,
        server: options.server,
        tunnel: options.tunnel,
        remoteUser: options.remoteUser,
        commands: ['mkdir -p ' + options.files.map(function (file) {
          return path.dirname(file.target);
        }).join(' ')]
      }).on('error', function (err) {
        if (!hasErr) {
          hasErr = true;
          next(err);
        }
      }).on('complete', function () {
        if (!hasErr) {
          next();
        }
      });
    }
570734
def sshInstance(self, *args, **kwargs):
        
        kwargs['collectStdout'] = True
        return self.coreSSH(*args, **kwargs)
143368
def list_remote(remote_uri, verbose=False):
    
    remote_uri1, remote_dpath = remote_uri.split(':')
    if not remote_dpath:
        remote_dpath = '.'
    import utool as ut
    out = ut.cmd('ssh', remote_uri1, 'ls -l %s' % (remote_dpath,), verbose=verbose)
    import re
    # Find lines that look like ls output
    split_lines = [re.split(r'\s+', t) for t in out[0].split('\n')]
    paths = [' '.join(t2[8:]) for t2 in split_lines if len(t2) > 8]
    return paths
238265
def ssh(self, vm_name=None, command=None, extra_ssh_args=None):
        '''
        
        '''
        cmd = ['ssh', vm_name, '--command', command]
        if extra_ssh_args is not None:
            cmd += ['--', extra_ssh_args]

        return self._run_vagrant_command(cmd)
328937
def ssh_exec_in_new_loop(server, cmd, timeout=10, **ssh_kwargs):
    
    task = ssh_exec(server, cmd, timeout=timeout, **ssh_kwargs)
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    return loop.run_until_complete(task)
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
871215
def _setup_ssh(self):
        """"""
        global paramiko
        if paramiko is none:
            import paramiko

        self.ssh = paramiko.SSHClient()
        self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        self.ssh.connect(self.server, username=self.user, pkey=self.pkey)
1106248
def scp(cls, vm_id, login, identity, local_file, remote_file):
        """"""
        cmd = ['scp']
        if identity:
            cmd.extend(('-i', identity,))

        version, ip_addr = cls.vm_ip(vm_id)
        if version == 6:
            ip_addr = '[%s]' % ip_addr

        cmd.extend((local_file, '%s@%s:%s' %
                    (login, ip_addr, remote_file),))
        cls.echo('Running %s' % ' '.join(cmd))
        for _ in range(5):
            ret = cls.execute(cmd, False)
            if ret:
                break
            time.sleep(.5)
        return ret
75812
def output_sshkey(gandi, sshkey, output_keys, justify=12):
    
    output_generic(gandi, sshkey, output_keys, justify)
228682
def ssh_file(opts, dest_path, contents=None, kwargs=None, local_file=None):
    '''
    
    '''
    if opts.get('file_transport', 'sftp') == 'sftp':
        return sftp_file(dest_path, contents, kwargs, local_file)
    return scp_file(dest_path, contents, kwargs, local_file)
26250
def _ssh_state(chunks, st_kwargs,
              kwargs, test=False):
    '''
    
    '''
    file_refs = salt.client.ssh.state.lowstate_file_refs(
            chunks,
            _merge_extra_filerefs(
                kwargs.get('extra_filerefs', ''),
                __opts__.get('extra_filerefs', '')
                )
            )
    # Create the tar containing the state pkg and relevant files.
    trans_tar = salt.client.ssh.state.prep_trans_tar(
            __context__['fileclient'],
            chunks,
            file_refs,
            __pillar__,
            st_kwargs['id_'])
    trans_tar_sum = salt.utils.hashutils.get_hash(trans_tar, __opts__['hash_type'])
    cmd = 'state.pkg {0}/salt_state.tgz test={1} pkg_sum={2} hash_type={3}'.format(
            __opts__['thin_dir'],
            test,
            trans_tar_sum,
            __opts__['hash_type'])
    single = salt.client.ssh.Single(
            __opts__,
            cmd,
            fsclient=__context__['fileclient'],
            minion_opts=__salt__.minion_opts,
            **st_kwargs)
    single.shell.send(
            trans_tar,
            '{0}/salt_state.tgz'.format(__opts__['thin_dir']))
    stdout, stderr, _ = single.cmd_block()

    # Clean up our tar
    try:
        os.remove(trans_tar)
    except (OSError, IOError):
        pass

    # Read in the JSON data and return the data structure
    try:
        return salt.utils.data.decode(salt.utils.json.loads(stdout, object_hook=salt.utils.data.encode_dict))
    except Exception as e:
        log.error("JSON Render failed for: %s\n%s", stdout, stderr)
        log.error(str(e))

    # If for some reason the json load fails, return the stdout
    return salt.utils.data.decode(stdout)
428671
def deploy_remote(self, dotfiles):
        """"""
        tempfile_path = None
        tempdir_path = None

        try:
            tempdir_path = tempfile.mkdtemp()
            self.log.debug('Deploying to temp dir %s', tempdir_path)
            self.deploy_local(dotfiles, target_root=tempdir_path)

            if self.args.rsync:
                local_spec = tempdir_path.rstrip('/') + '/'
                remote_spec = self.args.path.rstrip('/') + '/'

                if self.args.user:
                    remote_spec = "{0}@{1}:{2}".format(self.args.user,
                                                       self.args.server,
                                                       remote_spec)
                else:
                    remote_spec = "{0}:{1}".format(self.args.server,
                                                   remote_spec)

                self.log.debug('Using rsync to sync dotfiles to %s',
                               remote_spec)
                self.sh('rsync', '-az', local_spec, remote_spec)

            else:
                fh, tempfile_path = tempfile.mkstemp(suffix='.tar.gz')
                os.close(fh)

                self.log.debug('Creating tar file %s', tempfile_path)
                shutil.make_archive(tempfile_path.replace('.tar.gz', ''),
                                    'gztar', tempdir_path)

                upload_path = '_profile_upload.tgz'
                self.log.debug('Uploading tarball to %s', upload_path)
                self.scp(tempfile_path, upload_path)

                if self.args.path:
                    ssh_command = "'mkdir -p {0} && "\
                                  "tar xf _profile_upload.tgz -C {0}; "\
                                  "rm -f _profile_upload.tgz'"\
                                  "".format(self.args.path)
                else:
                    ssh_command = "tar xf _profile_upload.tgz; "\
                                  "rm -f _profile_upload.tgz"
                self.log.debug('Using ssh to unpack tarball and clean up')
                self.ssh(ssh_command)

        finally:
            if tempdir_path and path.isdir(tempdir_path):
                self.log.debug('Removing temp dir %s', tempdir_path)
                shutil.rmtree(tempdir_path)
            if tempfile_path and path.isfile(tempfile_path):
                self.log.debug('Removing temp file %s', tempfile_path)
                os.unlink(tempfile_path)
670705
def ssh(self, *args, **kwargs):
        '''
        
        '''
        ssh_client = salt.client.ssh.client.SSHClient(mopts=self.opts,
                                                      disable_custom_roster=True)
        return ssh_client.cmd_sync(kwargs)
411876
def ssh_to_task(task) -> paramiko.SSHClient:
  

  username = task.ssh_username
  hostname = task.public_ip
  ssh_key_fn = get_keypair_fn()
  print(f"ssh -i {ssh_key_fn} {username}@{hostname}")
  pkey = paramiko.RSAKey.from_private_key_file(ssh_key_fn)

  ssh_client = paramiko.SSHClient()
  ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
  assert ssh_client

  counter = 1
  while True:
    try:
      ssh_client.connect(hostname=hostname, username=username, pkey=pkey)
      if counter % 11 == 0:  # occasionally re-obtain public ip, machine could've gotten restarted
        hostname = task.public_ip
      break
    except Exception as e:
      print(
        f'{task.name}: Exception connecting to {hostname} via ssh (could be a timeout): {e}')
      time.sleep(RETRY_INTERVAL_SEC)

  return ssh_client
765640
def _ssh_cmd(self, *args):
        
        command = "gerrit {0}".format(" ".join(args))
        _, stdout, stderr = self._client.exec_command(command)
        return (stdout.readlines(), stderr.readlines())