def exec_command(self, cmd, tmp_path, become_user, **kwargs):
        executable = kwargs.get('executable', '/bin/sh')
        sudoable = kwargs.get('sudoable', False)
        if 'su' in kwargs or 'su_user' in kwargs:
            raise errors.AnsibleError("Internal Error: this module does not support running commands via su")

        if kwargs.get('in_data'):
            raise errors.AnsibleError("Internal Error: this module does not support optimized module pipelining")

        if sudoable and getattr(self.runner, 'become', False) and self.runner.become_method not in self.become_methods_supported:
            raise errors.AnsibleError("Internal Error: this module does not support running commands via %s" % self.runner.become_method)

        become = getattr(self.runner, 'become', False) or getattr(self.runner, 'sudo', False)
        remote_cmd = []
        if not become or not sudoable:
            if executable:
                remote_cmd.append(executable + ' -c ' + pipes.quote(cmd))
            else:
                remote_cmd.append(cmd)
        else:
            if hasattr(self.runner, 'become_exe'):
                becomecmd, prompt, success_key = utils.make_become_cmd(cmd, become_user, executable, self.runner.become_method, '', self.runner.become_exe)
            elif hasattr(self.runner, 'sudo_exe'):
                becomecmd, prompt, success_key = utils.make_sudo_cmd(self.runner.sudo_exe, become_user, executable, cmd)
            else:
                becomecmd, prompt, success_key = utils.make_sudo_cmd(become_user, executable, cmd)
            remote_cmd.append(becomecmd)
        remote_cmd = ' '.join(remote_cmd)
        vvv("execnet exec_command %r" % remote_cmd)
        rc, stdout, stderr = self.rpc.exec_command(remote_cmd)
        return (rc, '', stdout, stderr)
Esempio n. 2
0
    def exec_command(self,
                     cmd,
                     tmp_path,
                     become_user=None,
                     sudoable=False,
                     executable='/bin/sh',
                     in_data=None):
        ''' run a command on the remote host '''

        if sudoable and self.runner.become and self.runner.become_method not in self.become_methods_supported:
            raise errors.AnsibleError(
                "Internal Error: this module does not support running commands via %s"
                % self.runner.become_method)

        if in_data:
            raise AnsibleError(
                "Internal Error: this module does not support optimized module pipelining"
            )

        if executable == "":
            executable = constants.DEFAULT_EXECUTABLE

        if self.runner.become and sudoable:
            cmd, prompt, success_key = utils.make_become_cmd(
                cmd, become_user, executable, self.runner.become_method, '',
                self.runner.become_exe)

        vvv("EXEC COMMAND %s" % cmd)

        data = dict(
            mode='command',
            cmd=cmd,
            tmp_path=tmp_path,
            executable=executable,
        )
        data = utils.jsonify(data)
        data = utils.encrypt(self.key, data)
        if self.send_data(data):
            raise AnsibleError("Failed to send command to %s" % self.host)

        while True:
            # we loop here while waiting for the response, because a
            # long running command may cause us to receive keepalive packets
            # ({"pong":"true"}) rather than the response we want.
            response = self.recv_data()
            if not response:
                raise AnsibleError("Failed to get a response from %s" %
                                   self.host)
            response = utils.decrypt(self.key, response)
            response = utils.parse_json(response)
            if "pong" in response:
                # it's a keepalive, go back to waiting
                vvvv("%s: received a keepalive packet" % self.host)
                continue
            else:
                vvvv("%s: received the response" % self.host)
                break

        return (response.get('rc', None), '', response.get('stdout', ''),
                response.get('stderr', ''))
Esempio n. 3
0
 def _su_sudo_cmd(self, cmd):
     if self.runner.become:
         return utils.make_become_cmd(cmd, self.runner.become_user,
                                      '/bin/sh', self.runner.become_method,
                                      '', self.runner.become_exe)
     else:
         return cmd, None, None
Esempio n. 4
0
    def exec_command(self, cmd, tmp_path, become_user=None, sudoable=False, executable='/bin/sh', in_data=None):
        ''' run a command on the local host '''

        # su requires to be run from a terminal, and therefore isn't supported here (yet?)
        if sudoable and self.runner.become and self.runner.become_method not in self.become_methods_supported:
            raise errors.AnsibleError("Internal Error: this module does not support running commands via %s" % self.runner.become_method)

        if in_data:
            raise errors.AnsibleError("Internal Error: this module does not support optimized module pipelining")

        if self.runner.become and sudoable:
            local_cmd, prompt, success_key = utils.make_become_cmd(cmd, become_user, executable, self.runner.become_method, '-H', self.runner.become_exe)
        else:
            if executable:
                local_cmd = executable.split() + ['-c', cmd]
            else:
                local_cmd = cmd
        executable = executable.split()[0] if executable else None

        vvv("EXEC %s" % (local_cmd), host=self.host)
        p = subprocess.Popen(local_cmd, shell=isinstance(local_cmd, basestring),
                             cwd=self.runner.basedir, executable=executable,
                             stdin=subprocess.PIPE,
                             stdout=subprocess.PIPE, stderr=subprocess.PIPE,
                             env=self.envs)

        if self.runner.become and sudoable and self.runner.become_pass:
            fcntl.fcntl(p.stdout, fcntl.F_SETFL,
                        fcntl.fcntl(p.stdout, fcntl.F_GETFL) | os.O_NONBLOCK)
            fcntl.fcntl(p.stderr, fcntl.F_SETFL,
                        fcntl.fcntl(p.stderr, fcntl.F_GETFL) | os.O_NONBLOCK)
            become_output = ''
            while success_key not in become_output:

                if prompt and become_output.endswith(prompt):
                    break
                if utils.su_prompts.check_su_prompt(become_output):
                    break

                rfd, wfd, efd = select.select([p.stdout, p.stderr], [],
                                              [p.stdout, p.stderr], self.runner.timeout)
                if p.stdout in rfd:
                    chunk = p.stdout.read()
                elif p.stderr in rfd:
                    chunk = p.stderr.read()
                else:
                    stdout, stderr = p.communicate()
                    raise errors.AnsibleError('timeout waiting for %s password prompt:\n' % self.runner.become_method + become_output)
                if not chunk:
                    stdout, stderr = p.communicate()
                    raise errors.AnsibleError('%s output closed while waiting for password prompt:\n' % self.runner.become_method + become_output)
                become_output += chunk
            if success_key not in become_output:
                p.stdin.write(self.runner.become_pass + '\n')
            fcntl.fcntl(p.stdout, fcntl.F_SETFL, fcntl.fcntl(p.stdout, fcntl.F_GETFL) & ~os.O_NONBLOCK)
            fcntl.fcntl(p.stderr, fcntl.F_SETFL, fcntl.fcntl(p.stderr, fcntl.F_GETFL) & ~os.O_NONBLOCK)

        stdout, stderr = p.communicate()
        return (p.returncode, '', stdout, stderr)
Esempio n. 5
0
    def exec_command(self,
                     cmd,
                     tmp_path,
                     sudo_user=None,
                     become_user=None,
                     sudoable=False,
                     executable="/bin/sh",
                     in_data=None,
                     su=None,
                     su_user=None):
        """ run a command on the chroot """

        if self.runner.become and sudoable:
            cmd, prompt, success_key = utils.make_become_cmd(
                cmd, become_user, executable, self.runner.become_method, "",
                self.runner.become_exe)

        local_cmd = [cmd]
        if executable:
            local_cmd = [executable, "-c"] + local_cmd

        read_stdout, write_stdout = os.pipe()
        read_stderr, write_stderr = os.pipe()

        vvv("EXEC %s" % (local_cmd), host=self.host)

        pid = self.container.attach(_lxc.attach_run_command,
                                    local_cmd,
                                    env_policy=_lxc.LXC_ATTACH_CLEAR_ENV,
                                    stdout=write_stdout,
                                    stderr=write_stderr)

        if pid == -1:
            raise errors.AnsibleError("failed to attach to container %s",
                                      self.host)

        os.close(write_stdout)
        os.close(write_stderr)
        fds = [read_stdout, read_stderr]

        buf = {read_stdout: [], read_stderr: []}
        while len(fds) > 0:
            ready_fds, _, _ = select.select(fds, [], [])
            for fd in ready_fds:
                data = os.read(fd, 32768)
                if not data:
                    fds.remove(fd)
                    os.close(fd)
                buf[fd].append(data)

        (pid, returncode) = os.waitpid(pid, 0)

        stdout = b"".join(buf[read_stdout])
        stderr = b"".join(buf[read_stderr])

        return (returncode, "", stdout, stderr)
Esempio n. 6
0
    def exec_command(self, cmd, tmp_path, become_user=None, sudoable=False, executable='/bin/sh', in_data=None):
        ''' run a command on the remote host '''

        if sudoable and self.runner.become and self.runner.become_method not in self.become_methods_supported:
            raise AnsibleError("Internal Error: this module does not support running commands via %s" % self.runner.become_method)

        if in_data:
            raise AnsibleError("Internal Error: this module does not support optimized module pipelining")

        if executable == "":
            executable = constants.DEFAULT_EXECUTABLE

        if self.runner.become and sudoable:
            cmd, prompt, success_key = utils.make_become_cmd(cmd, become_user, executable, self.runner.become_method, '', self.runner.become_exe)

        vvv("EXEC COMMAND %s" % cmd)

        data = dict(
            mode='command',
            cmd=cmd,
            tmp_path=tmp_path,
            executable=executable,
        )
        data = utils.jsonify(data)
        data = utils.encrypt(self.key, data)
        if self.send_data(data):
            raise AnsibleError("Failed to send command to %s" % self.host)
        
        while True:
            # we loop here while waiting for the response, because a 
            # long running command may cause us to receive keepalive packets
            # ({"pong":"true"}) rather than the response we want. 
            response = self.recv_data()
            if not response:
                raise AnsibleError("Failed to get a response from %s" % self.host)
            response = utils.decrypt(self.key, response)
            response = utils.parse_json(response)
            if "pong" in response:
                # it's a keepalive, go back to waiting
                vvvv("%s: received a keepalive packet" % self.host)
                continue
            else:
                vvvv("%s: received the response" % self.host)
                break

        return (response.get('rc',None), '', response.get('stdout',''), response.get('stderr',''))
Esempio n. 7
0
    def exec_command(self, cmd, tmp_path, sudo_user=None, become_user=None, sudoable=False, executable="/bin/sh", in_data=None, su=None, su_user=None):
        """ run a command on the chroot """

        if self.runner.become and sudoable:
            cmd, prompt, success_key = utils.make_become_cmd(cmd, become_user, executable, self.runner.become_method, "", self.runner.become_exe)

        local_cmd = [cmd]
        if executable:
            local_cmd = [executable, "-c"] + local_cmd

        read_stdout, write_stdout = os.pipe()
        read_stderr, write_stderr = os.pipe()

        vvv("EXEC %s" % (local_cmd), host=self.host)

        pid = self.container.attach(_lxc.attach_run_command, local_cmd,
                env_policy=_lxc.LXC_ATTACH_CLEAR_ENV,
                stdout=write_stdout,
                stderr=write_stderr)

        if pid == -1:
            raise errors.AnsibleError("failed to attach to container %s", self.host)

        os.close(write_stdout)
        os.close(write_stderr)
        fds = [read_stdout, read_stderr]

        buf = { read_stdout: [], read_stderr: [] }
        while len(fds) > 0:
            ready_fds, _, _ = select.select(fds, [], [])
            for fd in ready_fds:
              data = os.read(fd, 32768)
              if not data:
                  fds.remove(fd)
                  os.close(fd)
              buf[fd].append(data)

        (pid, returncode) = os.waitpid(pid, 0)

        stdout = b"".join(buf[read_stdout])
        stderr = b"".join(buf[read_stderr])

        return (returncode, "", stdout, stderr)
Esempio n. 8
0
    def exec_command(self, cmd, tmp_path, become_user=None, sudoable=False, executable='/bin/sh', in_data=None):
        ''' run a command on the remote host '''

        if sudoable and self.runner.become and self.runner.become_method not in self.become_methods_supported:
            raise errors.AnsibleError("Internal Error: this module does not support running commands via %s" % self.runner.become_method)

        ssh_cmd = self._password_cmd()
        ssh_cmd += ["ssh", "-C"]
        if not in_data:
            # we can only use tty when we are not pipelining the modules. piping data into /usr/bin/python
            # inside a tty automatically invokes the python interactive-mode but the modules are not
            # compatible with the interactive-mode ("unexpected indent" mainly because of empty lines)
            ssh_cmd += ["-tt"]
        if utils.VERBOSITY > 3:
            ssh_cmd += ["-vvv"]
        else:
            if self.runner.module_name == 'raw':
                ssh_cmd += ["-q"]
            else:
                ssh_cmd += ["-v"]
        ssh_cmd += self.common_args

        if self.ipv6:
            ssh_cmd += ['-6']
        ssh_cmd += [self.host]

        if self.runner.become and sudoable:
            becomecmd, prompt, success_key = utils.make_become_cmd(cmd, become_user, executable, self.runner.become_method, '', self.runner.become_exe)
            ssh_cmd.append(becomecmd)
        else:
            prompt = None
            if executable:
                ssh_cmd.append(executable + ' -c ' + pipes.quote(cmd))
            else:
                ssh_cmd.append(cmd)

        vvv("EXEC %s" % ' '.join(ssh_cmd), host=self.host)

        not_in_host_file = self.not_in_host_file(self.host)

        if C.HOST_KEY_CHECKING and not_in_host_file:
            # lock around the initial SSH connectivity so the user prompt about whether to add
            # the host to known hosts is not intermingled with multiprocess output.
            fcntl.lockf(self.runner.process_lockfile, fcntl.LOCK_EX)
            fcntl.lockf(self.runner.output_lockfile, fcntl.LOCK_EX)

        # create process
        (p, stdin) = self._run(ssh_cmd, in_data)

        self._send_password()

        no_prompt_out = ''
        no_prompt_err = ''
        if sudoable and self.runner.become and self.runner.become_pass:
            (no_prompt_out, no_prompt_err) = self.send_su_sudo_password(p, stdin, success_key, sudoable, prompt)

        com = self.CommunicateCallbacks(self.runner, in_data, sudoable=sudoable, prompt=prompt)
        returncode = self._communicate(p, stdin, callbacks=(com.stdin_cb, com.stdout_cb, com.stderr_cb))

        if C.HOST_KEY_CHECKING and not_in_host_file:
            # lock around the initial SSH connectivity so the user prompt about whether to add 
            # the host to known hosts is not intermingled with multiprocess output.
            fcntl.lockf(self.runner.output_lockfile, fcntl.LOCK_UN)
            fcntl.lockf(self.runner.process_lockfile, fcntl.LOCK_UN)
        controlpersisterror = 'Bad configuration option: ControlPersist' in com.stderr or \
                              'unknown configuration option: ControlPersist' in com.stderr

        if C.HOST_KEY_CHECKING:
            if ssh_cmd[0] == "sshpass" and p.returncode == 6:
                raise errors.AnsibleError('Using a SSH password instead of a key is not possible because Host Key checking is enabled and sshpass does not support this.  Please add this host\'s fingerprint to your known_hosts file to manage this host.')

        if p.returncode != 0 and controlpersisterror:
            raise errors.AnsibleError('using -c ssh on certain older ssh versions may not support ControlPersist, set ANSIBLE_SSH_ARGS="" (or ssh_args in [ssh_connection] section of the config file) before running again')
        if p.returncode == 255 and (in_data or self.runner.module_name == 'raw'):
            raise errors.AnsibleError('SSH Error: data could not be sent to the remote host. Make sure this host can be reached over ssh')
        if p.returncode == 255:
            ip = None
            port = None
            for line in stderr.splitlines():
                match = re.search(
                    'Connecting to .*\[(\d+\.\d+\.\d+\.\d+)\] port (\d+)',
                    line)
                if match:
                    ip = match.group(1)
                    port = match.group(2)
            if 'UNPROTECTED PRIVATE KEY FILE' in stderr:
                lines = [line for line in stderr.splitlines()
                         if 'ignore key:' in line]
            else:
                lines = stderr.splitlines()[-1:]
            if ip and port:
                lines.append('    while connecting to %s:%s' % (ip, port))
            lines.append(
                'It is sometimes useful to re-run the command using -vvvv, '
                'which prints SSH debug output to help diagnose the issue.')
            raise errors.AnsibleError('SSH Error: %s' % '\n'.join(lines))

        return (p.returncode, '', no_prompt_out + com.stdout, no_prompt_err + com.stderr)
Esempio n. 9
0
    def exec_command(self, cmd, tmp_path, become_user=None, sudoable=False, executable='/bin/sh', in_data=None):
        ''' run a command on the remote host '''

        if sudoable and self.runner.become and self.runner.become_method not in self.become_methods_supported:
            raise errors.AnsibleError("Internal Error: this module does not support running commands via %s" % self.runner.become_method)

        ssh_cmd = self._password_cmd()
        ssh_cmd += ["ssh", "-C"]
        if not in_data:
            # we can only use tty when we are not pipelining the modules. piping data into /usr/bin/python
            # inside a tty automatically invokes the python interactive-mode but the modules are not
            # compatible with the interactive-mode ("unexpected indent" mainly because of empty lines)
            ssh_cmd += ["-tt"]
        if utils.VERBOSITY > 3:
            ssh_cmd += ["-vvv"]
        else:
            if self.runner.module_name == 'raw':
                ssh_cmd += ["-q"]
            else:
                ssh_cmd += ["-v"]
        ssh_cmd += self.common_args

        if self.ipv6:
            ssh_cmd += ['-6']
        ssh_cmd += [self.host]

        if self.runner.become and sudoable:
            becomecmd, prompt, success_key = utils.make_become_cmd(cmd, become_user, executable, self.runner.become_method, '', self.runner.become_exe)
            ssh_cmd.append(becomecmd)
        else:
            prompt = None
            if executable:
                ssh_cmd.append(executable + ' -c ' + pipes.quote(cmd))
            else:
                ssh_cmd.append(cmd)

        vvv("EXEC %s" % ' '.join(ssh_cmd), host=self.host)

        # Only read hosts file if checking is turned on
        if C.HOST_KEY_CHECKING:
            not_in_host_file = self.not_in_host_file(self.host)

        if C.HOST_KEY_CHECKING and not_in_host_file:
            # lock around the initial SSH connectivity so the user prompt about whether to add
            # the host to known hosts is not intermingled with multiprocess output.
            fcntl.lockf(self.runner.process_lockfile, fcntl.LOCK_EX)
            fcntl.lockf(self.runner.output_lockfile, fcntl.LOCK_EX)

        # create process
        (p, stdin) = self._run(ssh_cmd, in_data)

        self._send_password()

        no_prompt_out = ''
        no_prompt_err = ''
        if sudoable and self.runner.become and self.runner.become_pass:
            # several cases are handled for escalated privileges with password
            # * NOPASSWD (tty & no-tty): detect success_key on stdout
            # * without NOPASSWD:
            #   * detect prompt on stdout (tty)
            #   * detect prompt on stderr (no-tty)
            fcntl.fcntl(p.stdout, fcntl.F_SETFL,
                        fcntl.fcntl(p.stdout, fcntl.F_GETFL) | os.O_NONBLOCK)
            fcntl.fcntl(p.stderr, fcntl.F_SETFL,
                        fcntl.fcntl(p.stderr, fcntl.F_GETFL) | os.O_NONBLOCK)
            become_output = ''
            become_errput = ''

            while True:
                if success_key in become_output or \
                    (prompt and become_output.endswith(prompt)) or \
                    utils.su_prompts.check_su_prompt(become_output):
                    break

                rfd, wfd, efd = select.select([p.stdout, p.stderr], [],
                                              [p.stdout], self.runner.timeout)
                if p.stderr in rfd:
                    chunk = p.stderr.read()
                    if not chunk:
                        raise errors.AnsibleError('ssh connection closed waiting for a privilege escalation password prompt')
                    become_errput += chunk
                    incorrect_password = gettext.dgettext(
                        "become", "Sorry, try again.")
                    if become_errput.strip().endswith("%s%s" % (prompt, incorrect_password)):
                        raise errors.AnsibleError('Incorrect become password')
                    elif prompt and become_errput.endswith(prompt):
                        stdin.write(self.runner.become_pass + '\n')

                if p.stdout in rfd:
                    chunk = p.stdout.read()
                    if not chunk:
                        raise errors.AnsibleError('ssh connection closed waiting for %s password prompt' % self.runner.become_method)
                    become_output += chunk

                if not rfd:
                    # timeout. wrap up process communication
                    stdout = p.communicate()
                    raise errors.AnsibleError('ssh connection error while waiting for %s password prompt' % self.runner.become_method)

            if success_key in become_output:
                no_prompt_out += become_output
                no_prompt_err += become_errput
            elif sudoable:
                stdin.write(self.runner.become_pass + '\n')

        (returncode, stdout, stderr) = self._communicate(p, stdin, in_data, sudoable=sudoable, prompt=prompt)

        if C.HOST_KEY_CHECKING and not_in_host_file:
            # lock around the initial SSH connectivity so the user prompt about whether to add 
            # the host to known hosts is not intermingled with multiprocess output.
            fcntl.lockf(self.runner.output_lockfile, fcntl.LOCK_UN)
            fcntl.lockf(self.runner.process_lockfile, fcntl.LOCK_UN)
        controlpersisterror = 'Bad configuration option: ControlPersist' in stderr or \
                              'unknown configuration option: ControlPersist' in stderr

        if C.HOST_KEY_CHECKING:
            if ssh_cmd[0] == "sshpass" and p.returncode == 6:
                raise errors.AnsibleError('Using a SSH password instead of a key is not possible because Host Key checking is enabled and sshpass does not support this.  Please add this host\'s fingerprint to your known_hosts file to manage this host.')

        if p.returncode != 0 and controlpersisterror:
            raise errors.AnsibleError('using -c ssh on certain older ssh versions may not support ControlPersist, set ANSIBLE_SSH_ARGS="" (or ssh_args in [ssh_connection] section of the config file) before running again')
        if p.returncode == 255 and (in_data or self.runner.module_name == 'raw'):
            raise errors.AnsibleError('SSH Error: data could not be sent to the remote host. Make sure this host can be reached over ssh')
        if p.returncode == 255:
            ip = None
            port = None
            for line in stderr.splitlines():
                match = re.search(
                    'Connecting to .*\[(\d+\.\d+\.\d+\.\d+)\] port (\d+)',
                    line)
                if match:
                    ip = match.group(1)
                    port = match.group(2)
            if 'UNPROTECTED PRIVATE KEY FILE' in stderr:
                lines = [line for line in stderr.splitlines()
                         if 'ignore key:' in line]
            else:
                lines = stderr.splitlines()[-1:]
            if ip and port:
                lines.append('    while connecting to %s:%s' % (ip, port))
            lines.append(
                'It is sometimes useful to re-run the command using -vvvv, '
                'which prints SSH debug output to help diagnose the issue.')
            raise errors.AnsibleError('SSH Error: %s' % '\n'.join(lines))

        return (p.returncode, '', no_prompt_out + stdout, no_prompt_err + stderr)
Esempio n. 10
0
    def exec_command(self,
                     cmd,
                     tmp_path,
                     become_user=None,
                     sudoable=False,
                     executable='/bin/sh',
                     in_data=None):
        ''' run a command on the remote host '''

        if sudoable and self.runner.become and self.runner.become_method not in self.become_methods_supported:
            raise errors.AnsibleError(
                "Internal Error: this module does not support running commands via %s"
                % self.runner.become_method)

        ssh_cmd = self._password_cmd()
        ssh_cmd += ["ssh", "-C"]
        if not in_data:
            # we can only use tty when we are not pipelining the modules. piping data into /usr/bin/python
            # inside a tty automatically invokes the python interactive-mode but the modules are not
            # compatible with the interactive-mode ("unexpected indent" mainly because of empty lines)
            ssh_cmd += ["-tt"]
        if utils.VERBOSITY > 3:
            ssh_cmd += ["-vvv"]
        else:
            ssh_cmd += ["-v"]
        ssh_cmd += self.common_args

        if self.ipv6:
            ssh_cmd += ['-6']
        ssh_cmd += [self.host]

        if self.runner.become and sudoable:
            becomecmd, prompt, success_key = utils.make_become_cmd(
                cmd, become_user, executable, self.runner.become_method, '',
                self.runner.become_exe)
            ssh_cmd.append(becomecmd)
        else:
            prompt = None
            if executable:
                ssh_cmd.append(executable + ' -c ' + pipes.quote(cmd))
            else:
                ssh_cmd.append(cmd)

        vvv("EXEC %s" % ' '.join(ssh_cmd), host=self.host)

        not_in_host_file = self.not_in_host_file(self.host)

        if C.HOST_KEY_CHECKING and not_in_host_file:
            # lock around the initial SSH connectivity so the user prompt about whether to add
            # the host to known hosts is not intermingled with multiprocess output.
            fcntl.lockf(self.runner.process_lockfile, fcntl.LOCK_EX)
            fcntl.lockf(self.runner.output_lockfile, fcntl.LOCK_EX)

        # create process
        (p, stdin) = self._run(ssh_cmd, in_data)

        self._send_password()

        no_prompt_out = ''
        no_prompt_err = ''
        if self.runner.become and sudoable and self.runner.become_pass:
            # several cases are handled for escalated privileges with password
            # * NOPASSWD (tty & no-tty): detect success_key on stdout
            # * without NOPASSWD:
            #   * detect prompt on stdout (tty)
            #   * detect prompt on stderr (no-tty)
            fcntl.fcntl(p.stdout, fcntl.F_SETFL,
                        fcntl.fcntl(p.stdout, fcntl.F_GETFL) | os.O_NONBLOCK)
            fcntl.fcntl(p.stderr, fcntl.F_SETFL,
                        fcntl.fcntl(p.stderr, fcntl.F_GETFL) | os.O_NONBLOCK)
            become_output = ''
            become_errput = ''

            while success_key not in become_output:

                if prompt and become_output.endswith(prompt):
                    break
                if utils.su_prompts.check_su_prompt(become_output):
                    break

                rfd, wfd, efd = select.select([p.stdout, p.stderr], [],
                                              [p.stdout], self.runner.timeout)
                if p.stderr in rfd:
                    chunk = p.stderr.read()
                    if not chunk:
                        raise errors.AnsibleError(
                            'ssh connection closed waiting for a privilege escalation password prompt'
                        )
                    become_errput += chunk
                    incorrect_password = gettext.dgettext(
                        "become", "Sorry, try again.")
                    if become_errput.strip().endswith(
                            "%s%s" % (prompt, incorrect_password)):
                        raise errors.AnsibleError('Incorrect become password')
                    elif prompt and become_errput.endswith(prompt):
                        stdin.write(self.runner.become_pass + '\n')

                if p.stdout in rfd:
                    chunk = p.stdout.read()
                    if not chunk:
                        raise errors.AnsibleError(
                            'ssh connection closed waiting for %s password prompt'
                            % self.runner.become_method)
                    become_output += chunk

                if not rfd:
                    # timeout. wrap up process communication
                    stdout = p.communicate()
                    raise errors.AnsibleError(
                        'ssh connection error while waiting for %s password prompt'
                        % self.runner.become_method)

            if success_key not in become_output:
                if sudoable:
                    stdin.write(self.runner.become_pass + '\n')
            else:
                no_prompt_out += become_output
                no_prompt_err += become_errput

        (returncode, stdout, stderr) = self._communicate(p,
                                                         stdin,
                                                         in_data,
                                                         sudoable=sudoable,
                                                         prompt=prompt)

        if C.HOST_KEY_CHECKING and not_in_host_file:
            # lock around the initial SSH connectivity so the user prompt about whether to add
            # the host to known hosts is not intermingled with multiprocess output.
            fcntl.lockf(self.runner.output_lockfile, fcntl.LOCK_UN)
            fcntl.lockf(self.runner.process_lockfile, fcntl.LOCK_UN)
        controlpersisterror = 'Bad configuration option: ControlPersist' in stderr or \
                              'unknown configuration option: ControlPersist' in stderr

        if C.HOST_KEY_CHECKING:
            if ssh_cmd[0] == "sshpass" and p.returncode == 6:
                raise errors.AnsibleError(
                    'Using a SSH password instead of a key is not possible because Host Key checking is enabled and sshpass does not support this.  Please add this host\'s fingerprint to your known_hosts file to manage this host.'
                )

        if p.returncode != 0 and controlpersisterror:
            raise errors.AnsibleError(
                'using -c ssh on certain older ssh versions may not support ControlPersist, set ANSIBLE_SSH_ARGS="" (or ssh_args in [ssh_connection] section of the config file) before running again'
            )
        if p.returncode == 255 and (in_data
                                    or self.runner.module_name == 'raw'):
            raise errors.AnsibleError(
                'SSH Error: data could not be sent to the remote host. Make sure this host can be reached over ssh'
            )
        if p.returncode == 255:
            ip = None
            port = None
            for line in stderr.splitlines():
                match = re.search(
                    'Connecting to .*\[(\d+\.\d+\.\d+\.\d+)\] port (\d+)',
                    line)
                if match:
                    ip = match.group(1)
                    port = match.group(2)
            if 'UNPROTECTED PRIVATE KEY FILE' in stderr:
                lines = [
                    line for line in stderr.splitlines()
                    if 'ignore key:' in line
                ]
            else:
                lines = stderr.splitlines()[-1:]
            if ip and port:
                lines.append('    while connecting to %s:%s' % (ip, port))
            lines.append(
                'It is sometimes useful to re-run the command using -vvvv, '
                'which prints SSH debug output to help diagnose the issue.')
            raise errors.AnsibleError('SSH Error: %s' % '\n'.join(lines))

        return (p.returncode, '', no_prompt_out + stdout,
                no_prompt_err + stderr)
Esempio n. 11
0
 def _su_sudo_cmd(self, cmd):
     if self.runner.become:
         return utils.make_become_cmd(cmd, self.runner.become_user, '/bin/sh', self.runner.become_method, '', self.runner.become_exe)
     else:
         return cmd, None, None
Esempio n. 12
0
            else:
                quoted_command = cmd
            vvv("EXEC %s" % quoted_command, host=self.host)
            chan.exec_command(quoted_command)

        else:

            # sudo usually requires a PTY (cf. requiretty option), therefore
            # we give it one by default (pty=True in ansble.cfg), and we try
            # to initialise from the calling environment
            if C.PARAMIKO_PTY:
                chan.get_pty(term=os.getenv('TERM', 'vt100'),
                             width=int(os.getenv('COLUMNS', 0)),
                             height=int(os.getenv('LINES', 0)))
            if self.runner.become and sudoable:
                shcmd, prompt, success_key = utils.make_become_cmd(cmd, become_user, executable, self.runner.become_method, '', self.runner.become_exe)

            vvv("EXEC %s" % shcmd, host=self.host)
            become_output = ''

            try:

                chan.exec_command(shcmd)

                if self.runner.become_pass:

                    while True:

                        if success_key in become_output or \
                            (prompt and become_output.endswith(prompt)) or \
                            utils.su_prompts.check_su_prompt(become_output):
Esempio n. 13
0
    def _exec_command(self, cmd, executable='/bin/sh'):
        '''run command'''
        # extract variants
        host = self.host
        basedir = self.runner.basedir
        timeout = self.runner.timeout
        become = self.runner.become
        become_method = self.runner.become_method
        become_exe = self.runner.become_exe
        become_user = self.runner.become_user
        become_pass = self.runner.become_pass

        # calc local_cmd and executable
        if become:
            local_cmd, prompt, success_key = utils.make_become_cmd(
                cmd, become_user, executable, become_method, '-H',
                become_exe)
        elif executable:
            local_cmd = executable.split() + ['-c', cmd]
        else:
            local_cmd = cmd
        executable = executable.split()[0] if executable else None

        vvv("EXEC %s" % (local_cmd), host=host)
        p = subprocess.Popen(local_cmd, shell=isinstance(local_cmd, basestring),
                             cwd=basedir, executable=executable,
                             stdin=subprocess.PIPE,
                             stdout=subprocess.PIPE, stderr=subprocess.PIPE)

        if become and become_pass:
            fcntl.fcntl(p.stdout, fcntl.F_SETFL,
                        fcntl.fcntl(p.stdout, fcntl.F_GETFL) | os.O_NONBLOCK)
            fcntl.fcntl(p.stderr, fcntl.F_SETFL,
                        fcntl.fcntl(p.stderr, fcntl.F_GETFL) | os.O_NONBLOCK)
            become_output = ''
            while success_key not in become_output:

                if prompt and become_output.endswith(prompt):
                    break
                if utils.su_prompts.check_su_prompt(become_output):
                    break

                rfd, wfd, efd = select.select([p.stdout, p.stderr], [],
                                              [p.stdout, p.stderr], timeout)
                if p.stdout in rfd:
                    chunk = p.stdout.read()
                elif p.stderr in rfd:
                    chunk = p.stderr.read()
                else:
                    stdout, stderr = p.communicate()
                    raise errors.AnsibleError(
                        'timeout waiting for %s password prompt:\n'
                        % become_method + become_output)
                if not chunk:
                    stdout, stderr = p.communicate()
                    raise errors.AnsibleError(
                        '%s output closed while waiting for password prompt:\n'
                        % become_method + become_output)
                become_output += chunk
            if success_key not in become_output:
                p.stdin.write(become_pass + '\n')
            fcntl.fcntl(
                p.stdout, fcntl.F_SETFL,
                fcntl.fcntl(p.stdout, fcntl.F_GETFL) & ~os.O_NONBLOCK)
            fcntl.fcntl(
                p.stderr, fcntl.F_SETFL,
                fcntl.fcntl(p.stderr, fcntl.F_GETFL) & ~os.O_NONBLOCK)

        stdout, stderr = p.communicate()
        return (p.returncode, '', stdout, stderr)
Esempio n. 14
0
                quoted_command = cmd
            vvv("EXEC %s" % quoted_command, host=self.host)
            chan.exec_command(quoted_command)

        else:

            # sudo usually requires a PTY (cf. requiretty option), therefore
            # we give it one by default (pty=True in ansble.cfg), and we try
            # to initialise from the calling environment
            if C.PARAMIKO_PTY:
                chan.get_pty(term=os.getenv('TERM', 'vt100'),
                             width=int(os.getenv('COLUMNS', 0)),
                             height=int(os.getenv('LINES', 0)))
            if self.runner.become and sudoable:
                shcmd, prompt, success_key = utils.make_become_cmd(
                    cmd, become_user, executable, self.runner.become_method,
                    '', self.runner.become_exe)

            vvv("EXEC %s" % shcmd, host=self.host)
            become_output = ''

            try:

                chan.exec_command(shcmd)

                if self.runner.become_pass:

                    while True:

                        if success_key in become_output or \
                            (prompt and become_output.endswith(prompt)) or \
Esempio n. 15
0
    def _exec_command(self, cmd, executable='/bin/sh'):
        '''run command'''
        # extract variants
        host = self.host
        basedir = self.runner.basedir
        timeout = self.runner.timeout
        become = self.runner.become
        become_method = self.runner.become_method
        become_exe = self.runner.become_exe
        become_user = self.runner.become_user
        become_pass = self.runner.become_pass

        # calc local_cmd and executable
        if become:
            local_cmd, prompt, success_key = utils.make_become_cmd(
                cmd, become_user, executable, become_method, '-H', become_exe)
        elif executable:
            local_cmd = executable.split() + ['-c', cmd]
        else:
            local_cmd = cmd
        executable = executable.split()[0] if executable else None

        vvv("EXEC %s" % (local_cmd), host=host)
        p = subprocess.Popen(local_cmd,
                             shell=isinstance(local_cmd, basestring),
                             cwd=basedir,
                             executable=executable,
                             stdin=subprocess.PIPE,
                             stdout=subprocess.PIPE,
                             stderr=subprocess.PIPE)

        if become and become_pass:
            fcntl.fcntl(p.stdout, fcntl.F_SETFL,
                        fcntl.fcntl(p.stdout, fcntl.F_GETFL) | os.O_NONBLOCK)
            fcntl.fcntl(p.stderr, fcntl.F_SETFL,
                        fcntl.fcntl(p.stderr, fcntl.F_GETFL) | os.O_NONBLOCK)
            become_output = ''
            while success_key not in become_output:

                if prompt and become_output.endswith(prompt):
                    break
                if utils.su_prompts.check_su_prompt(become_output):
                    break

                rfd, wfd, efd = select.select([p.stdout, p.stderr], [],
                                              [p.stdout, p.stderr], timeout)
                if p.stdout in rfd:
                    chunk = p.stdout.read()
                elif p.stderr in rfd:
                    chunk = p.stderr.read()
                else:
                    stdout, stderr = p.communicate()
                    raise errors.AnsibleError(
                        'timeout waiting for %s password prompt:\n' %
                        become_method + become_output)
                if not chunk:
                    stdout, stderr = p.communicate()
                    raise errors.AnsibleError(
                        '%s output closed while waiting for password prompt:\n'
                        % become_method + become_output)
                become_output += chunk
            if success_key not in become_output:
                p.stdin.write(become_pass + '\n')
            fcntl.fcntl(p.stdout, fcntl.F_SETFL,
                        fcntl.fcntl(p.stdout, fcntl.F_GETFL) & ~os.O_NONBLOCK)
            fcntl.fcntl(p.stderr, fcntl.F_SETFL,
                        fcntl.fcntl(p.stderr, fcntl.F_GETFL) & ~os.O_NONBLOCK)

        stdout, stderr = p.communicate()
        return (p.returncode, '', stdout, stderr)