Execute a `salt-ssh` command
327408
def salt_ssh(project, target, module, args=None, kwargs=None):
    
    cmd = ['salt-ssh']
    cmd.extend(generate_salt_cmd(target, module, args, kwargs))
    cmd.append('--state-output=mixed')
    cmd.append('--roster-file=%s' % project.roster_path)
    cmd.append('--config-dir=%s' % project.salt_ssh_config_dir)
    cmd.append('--ignore-host-keys')
    cmd.append('--force-color')
    cmd = ' '.join(cmd)
    logger.debug('salt-ssh cmd: %s', cmd)

    proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    out, err = proc.communicate()
    if proc.returncode != 0 or err:
        raise Exception(err)
    return out + err
980382
def setup_salt_ssh(self):
        
        self.copy_salt_and_pillar()
        self.create_roster_file()
        self.salt_ssh_create_dirs()
        self.salt_ssh_create_master_file()
488437
def ssh(self, *command):
        """"""
        if self.args.user:
            ssh_spec = '{0}@{1}'.format(self.args.user, self.args.server)
        else:
            ssh_spec = self.args.server

        return self.sh('ssh', ssh_spec, *command)
995595
def execute_command(command=None):
    """"""
    process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    stdout, stdin = process.communicate()
    process.wait()
    return (stdout, stdin), process.returncode
190629
def do(cmdline, runas=None, env=None):
    '''
    
    '''
    if not cmdline:
        # This is a positional argument so this should never happen, but this
        # will handle cases where someone explicitly passes a false value for
        # cmdline.
        raise SaltInvocationError('Command must be specified')

    path = _rbenv_path(runas)
    if not env:
        env = {}

    # NOTE: Env vars (and their values) need to be str type on both Python 2
    # and 3. The code below first normalizes all path components to unicode to
    # stitch them together, and then converts the result back to a str type.
    env[str('PATH')] = salt.utils.stringutils.to_str(   # future lint: disable=blacklisted-function
        os.pathsep.join((
            salt.utils.path.join(path, 'shims'),
            salt.utils.stringutils.to_unicode(os.environ['PATH'])
        ))
    )

    try:
        cmdline = salt.utils.args.shlex_split(cmdline)
    except AttributeError:
        cmdauth = salt.utils.args.shlex_split(six.text_type(cmdline))

    result = __salt__['cmd.run_all'](
        cmdline,
        runas=runas,
        env=env,
        python_shell=False
    )

    if result['retcode'] == 0:
        rehash(runas=runas)
        return result['stdout']
    else:
        return False
1299068
def get_file(path,
             dest,
             saltenv='base',
             makedirs=False,
             template=None,
             gzip=None):
    '''
    
    '''
    if gzip is not None:
        log.warning('The gzip argument to cp.get_file in salt-ssh is '
                    'unsupported')

    if template is not None:
        (path, dest) = _render_filenames(path, dest, saltenv, template)

    src = __context__['fileclient'].cache_file(
        path,
        saltenv,
        cachedir=os.path.join('salt-ssh', __salt__.kwargs['id_']))
    single = salt.client.ssh.Single(
            __opts__,
            '',
            **__salt__.kwargs)
    ret = single.shell.send(src, dest, makedirs)
    return not ret[2]
1043721
def _run_cmd(self, cmd, key_accept=False, passwd_retries=3):
        '''
        
        '''
        if not cmd:
            return '', 'No command or passphrase', 245

        term = salt.utils.vt.Terminal(
                cmd,
                shell=True,
                log_stdout=True,
                log_stdout_level='trace',
                log_stderr=True,
                log_stderr_level='trace',
                stream_stdout=False,
                stream_stderr=False)
        sent_passwd = 0
        send_password = True
        ret_stdout = ''
        ret_stderr = ''
        old_stdout = ''

        try:
            while term.has_unread_data:
                stdout, stderr = term.recv()
                if stdout:
                    ret_stdout += stdout
                    buff = old_stdout + stdout
                else:
                    buff = stdout
                if stderr:
                    ret_stderr += stderr
                if buff and RSTR_RE.search(buff):
                    # We're getting results back, don't try to send passwords
                    send_password = False
                if buff and SSH_PRIVATE_KEY_PASSWORD_PROMPT_RE.search(buff):
                    if not self.priv_passwd:
                        return '', 'Private key file need passphrase', 254
                    term.sendline(self.priv_passwd)
                    continue
                if buff and SSH_PASSWORD_PROMPT_RE.search(buff) and send_password:
                    if not self.passwd:
                        return '', 'Permission denied, no authentication information', 254
                    if sent_passwd < passwd_retries:
                        term.sendline(self.passwd)
                        sent_passwd += 1
                        continue
                    else:
                        # asking for a password, and we can't seem to send it
                        return '', 'Password authentication failed', 254
                elif buff and KEY_VALID_RE.search(buff):
                    if key_accept:
                        term.sendline('yes')
                        continue
                    else:
                        term.sendline('no')
                        ret_stdout = ('The host key needs to be accepted, to '
                                      'auto accept run salt-ssh with the -i '
                                      'flag:\n{0}').format(stdout)
                        return ret_stdout, '', 254
                elif buff and buff.endswith('_||ext_mods||_'):
                    mods_raw = salt.utils.json.dumps(self.mods, separators=(',', ':')) + '|_E|0|'
                    term.sendline(mods_raw)
                if stdout:
                    old_stdout = stdout
                time.sleep(0.01)
            return ret_stdout, ret_stderr, term.exitstatus
        finally:
            term.close(terminate=True, kill=True)
1183558
def sshagent_run(cmd):
    
    # Handle context manager modifications
    wrapped_cmd = _prefix_commands(_prefix_env_vars(cmd), 'remote')
    try:
        host, port = env.host_string.split(':')
        return local(
            u"ssh -p %s -A -o StrictHostKeyChecking=no %s@%s '%s'" % (
                port, env.user, host, wrapped_cmd
            )
        )
    except ValueError:
        return local(
            u"ssh -A -o StrictHostKeyChecking=no %s@%s '%s'" % (
                env.user, env.host_string, wrapped_cmd
            )
        )
1201596
def salt_ssh_create_dirs(self):
        
        logger.debug('Creating salt-ssh dirs into: %s', self.settings_dir)
        utils.create_dir(os.path.join(self.settings_dir, 'salt'))
        utils.create_dir(os.path.join(self.settings_dir, 'pillar'))
        utils.create_dir(os.path.join(self.settings_dir, 'etc', 'salt'))
        utils.create_dir(os.path.join(self.settings_dir, 'var', 'cache', 'salt'))
        utils.create_dir(os.path.join(self.settings_dir, 'var', 'log', 'salt'))
477931
def run(self, cmd, user='root', sudo=False, ignore_error=False,
            success_status=(0,), error_callback=None, custom_log=None, retry=0):
        
        self.enable_user(user)
        return self.ssh_pool.run(
            user, cmd, sudo=sudo, ignore_error=ignore_error,
            success_status=success_status, error_callback=error_callback,
            custom_log=custom_log, retry=retry)
507746
def _call_salt_command(self,
                           fun,
                           args,
                           kwargs,
                           assertion_section=None):
        '''
        
        '''
        value = False
        try:
            if args and kwargs:
                value = self.salt_lc.cmd(fun, *args, **kwargs)
            elif args and not kwargs:
                value = self.salt_lc.cmd(fun, *args)
            elif not args and kwargs:
                value = self.salt_lc.cmd(fun, **kwargs)
            else:
                value = self.salt_lc.cmd(fun)
        except salt.exceptions.SaltException:
            raise
        except Exception:
            raise
        if isinstance(value, dict) and assertion_section:
            return value.get(assertion_section, False)
        else:
            return value
486729
def _deploy_salt_minion(name, session, vm_):
    '''
    
    '''
    # Get bootstrap values
    vm_['ssh_host'] = get_vm_ip(name, session)
    vm_['user'] = vm_.get('user', 'root')
    vm_['password'] = vm_.get('password', 'p@ssw0rd!')
    vm_['provider'] = vm_.get('provider', 'xen')
    log.debug('%s has IP of %s', name, vm_['ssh_host'])
    # Bootstrap Salt minion!
    if vm_['ssh_host'] is not None:
        log.info('Installing Salt minion on %s', name)
        boot_ret = __utils__['cloud.bootstrap'](vm_, __opts__)
        log.debug('boot return: %s', boot_ret)
882043
def key_deploy(self, host, ret):
        '''
        
        '''
        if not isinstance(ret[host], dict) or self.opts.get('ssh_key_deploy'):
            target = self.targets[host]
            if target.get('passwd', False) or self.opts['ssh_passwd']:
                self._key_deploy_run(host, target, False)
            return ret
        if ret[host].get('stderr', '').count('Permission denied'):
            target = self.targets[host]
            # permission denied, attempt to auto deploy ssh key
            print(('Permission denied for host {0}, do you want to deploy '
                   'the salt-ssh key? (password required):').format(host))
            deploy = input('[Y/n] ')
            if deploy.startswith(('n', 'N')):
                return ret
            target['passwd'] = getpass.getpass(
                    'Password for {0}@{1}: '.format(target['user'], host)
                )
            return self._key_deploy_run(host, target, True)
        return ret
1065288
def _cli_command(commands,
                 method='cli',
                 **kwargs):
    '''
    
    '''
    if not isinstance(commands, (list, tuple)):
        commands = [commands]
    rpc_responses = rpc(commands,
                        method=method,
                        **kwargs)
    txt_responses = []
    for rpc_reponse in rpc_responses:
        error = rpc_reponse.get('error')
        if error:
            cmd = rpc_reponse.get('command')
            if 'data' in error:
                msg = 'The command "{cmd}" raised the error "{err}".'.format(cmd=cmd, err=error['data']['msg'])
                raise SaltException(msg)
            else:
                msg = 'Invalid command: "{cmd}".'.format(cmd=cmd)
                raise SaltException(msg)
        txt_responses.append(rpc_reponse['result'])
    return txt_responses
59566
def _execute_cmd(plugin, args='', run_type='cmd.retcode'):
    '''
    
    '''
    data = {}

    all_plugins = list_plugins()
    if plugin in all_plugins:
        data = __salt__[run_type](
                '{0}{1} {2}'.format(PLUGINDIR, plugin, args),
                python_shell=False)

    return data
491020
def exec_command(self, cmd, tmp_path, sudo_user, sudoable=False, executable='/bin/sh'):
        '''  '''

        bufsize = 4096
        try:
            chan = self.ssh.get_transport().open_session()
        except Exception, e:
            msg = "Failed to open session"
            if len(str(e)) > 0:
                msg += ": %s" % str(e)
            raise errors.AnsibleConnectionFailed(msg)
        chan.get_pty()

        if not self.runner.sudo or not sudoable:
            if executable:
                quoted_command = executable + ' -c ' + pipes.quote(cmd)
            else:
                quoted_command = cmd
            vvv("EXEC %s" % quoted_command, host=self.host)
            chan.exec_command(quoted_command)
        else:
            shcmd, prompt = utils.make_sudo_cmd(sudo_user, executable, cmd)
            vvv("EXEC %s" % shcmd, host=self.host)
            sudo_output = ''
            try:
                chan.exec_command(shcmd)
                if self.runner.sudo_pass:
                    while not sudo_output.endswith(prompt):
                        chunk = chan.recv(bufsize)
                        if not chunk:
                            if 'unknown user' in sudo_output:
                                raise errors.AnsibleError(
                                    'user %s does not exist' % sudo_user)
                            else:
                                raise errors.AnsibleError('ssh connection ' +
                                    'closed waiting for password prompt')
                        sudo_output += chunk
                    chan.sendall(self.runner.sudo_pass + '\n')
            except socket.timeout:
                raise errors.AnsibleError('ssh timed out waiting for sudo.\n' + sudo_output)

        stdout = ''.join(chan.makefile('rb', bufsize))
        stderr = ''.join(chan.makefile_stderr('rb', bufsize))
        return (chan.recv_exit_status(), '', stdout, stderr)
1266698
def ssh_exec!(node, command)
      r = on node, command, { :acceptable_exit_codes => (0..127) }
      {
        :exit_status => r.exit_code,
        :stdout      => r.stdout,
        :stderr      => r.stderr
      }
    end