コード例 #1
0
    def run(self, command, *args):
        self._check_ansible()
        command = self.get_command(command, *args)
        kwargs = {}
        if self.ansible_inventory is not None:
            kwargs["host_list"] = self.ansible_inventory
        out = ansible.runner.Runner(pattern=self.host,
                                    module_name="shell",
                                    module_args=command,
                                    **kwargs).run()["contacted"][self.host]

        # Ansible return an unicode object but this is bytes ...
        # A simple test case is:
        # >>> assert File("/bin/true").content == open("/bin/true").read()
        stdout_bytes = b"".join(map(chr, map(ord, out['stdout'])))
        stderr_bytes = b"".join(map(chr, map(ord, out['stderr'])))

        return base.CommandResult(
            self,
            out['rc'],
            stdout_bytes,
            stderr_bytes,
            command,
            stdout=out["stdout"],
            stderr=out["stderr"],
        )
コード例 #2
0
 def run(self, command, *args):
     command = self.get_command(command, *args)
     out = self.run_salt("cmd.run_all", [command])
     result = base.CommandResult(self, out['retcode'], out['stdout'],
                                 out['stderr'], command)
     logger.info("RUN %s", result)
     return result
コード例 #3
0
 def run(self, command, *args):
     if self.sudo:
         command = "sudo " + command
     command = self.quote(command, *args)
     out = self.run_salt("cmd.run_all", [command])
     return base.CommandResult(self, out['retcode'], out['stdout'],
                               out['stderr'], command)
コード例 #4
0
 def run(self, command, *args, **kwargs):
     command = self.get_command(command, *args)
     chan = self.client.get_transport().open_session()
     logger.info("RUN %s", command)
     command = self.encode(command)
     chan.exec_command(command)
     rc = chan.recv_exit_status()
     stdout = b''.join(chan.makefile('rb'))
     stderr = b''.join(chan.makefile_stderr('rb'))
     return base.CommandResult(self, rc, stdout, stderr, command)
コード例 #5
0
 def run_local(self, command, *args):
     command = self.quote(command, *args)
     command = self.encode(command)
     p = subprocess.Popen(
         command, shell=True,
         stdin=subprocess.PIPE,
         stdout=subprocess.PIPE,
         stderr=subprocess.PIPE,
     )
     stdout, stderr = p.communicate()
     return base.CommandResult(
         self, p.returncode, stdout, stderr, command,
     )
コード例 #6
0
    def run(self, command, *args, **kwargs):
        orig_command = self.quote(command, *args)

        out = super(SafeSshBackend, self).run(
            ('''of=$(mktemp)&&ef=$(mktemp)&&%s >$of 2>$ef; r=$?;'''
             '''echo "TESTINFRA_START;$r;$(base64 < $of);$(base64 < $ef);'''
             '''TESTINFRA_END";rm -f $of $ef''') % (orig_command, ))

        start = out.stdout.find("TESTINFRA_START;") + len("TESTINFRA_START;")
        end = out.stdout.find("TESTINFRA_END") - 1
        rc, stdout, stderr = out.stdout[start:end].split(";")
        rc = int(rc)
        stdout = base64.b64decode(stdout)
        stderr = base64.b64decode(stderr)
        return base.CommandResult(self, rc, stdout, stderr, orig_command)
コード例 #7
0
    def run(self, command, *args, **kwargs):
        command = self.get_command(command, *args)
        command = self.encode(command)
        try:
            rc, stdout, stderr = self._exec_command(command)
        except paramiko.ssh_exception.SSHException:
            if not self.client.get_transport().is_active():
                # try to reinit connection (once)
                self._client = None
                rc, stdout, stderr = self._exec_command(command)
            else:
                raise

        result = base.CommandResult(self, rc, stdout, stderr, command)
        logger.info("RUN %s", result)
        return result
コード例 #8
0
    def run(self, command, *args):
        command = self.get_command(command, *args)
        out = self.run_ansible("shell", module_args=command)

        # Ansible return an unicode object but this is bytes ...
        # A simple test case is:
        # >>> assert File("/bin/true").content == open("/bin/true").read()
        stdout_bytes = b"".join((chr(ord(c)) for c in out['stdout']))
        stderr_bytes = b"".join((chr(ord(c)) for c in out['stderr']))

        result = base.CommandResult(
            self,
            out['rc'],
            stdout_bytes,
            stderr_bytes,
            command,
            stdout=out["stdout"],
            stderr=out["stderr"],
        )
        logger.info("RUN %s", result)
        return result
コード例 #9
0
 def run(self, command, *args, **kwargs):
     if self.sudo:
         command = "sudo " + command
     command = self.quote(command, *args)
     logger.info("RUN %s", command)
     command = self.encode(command)
     p = subprocess.Popen(
         command,
         shell=True,
         stdin=subprocess.PIPE,
         stdout=subprocess.PIPE,
         stderr=subprocess.PIPE,
     )
     stdout, stderr = p.communicate()
     return base.CommandResult(
         self,
         p.returncode,
         stdout,
         stderr,
         command,
     )
コード例 #10
0
    def run(self, command, *args):
        self._check_ansible()

        if HAS_ANSIBLE_1:
            import ansible.inventory
            import ansible.runner
            command = self.get_command(command, *args)
            kwargs = {}
            if self.ansible_inventory is not None:
                kwargs["host_list"] = self.ansible_inventory
            out = ansible.runner.Runner(pattern=self.host,
                                        module_name="shell",
                                        module_args=command,
                                        **kwargs).run()["contacted"][self.host]

            # Ansible return an unicode object but this is bytes ...
            # A simple test case is:
            # >>> assert File("/bin/true").content == open("/bin/true").read()
            stdout_bytes = b"".join((chr(ord(c)) for c in out['stdout']))
            stderr_bytes = b"".join((chr(ord(c)) for c in out['stderr']))

            result = base.CommandResult(
                self,
                out['rc'],
                stdout_bytes,
                stderr_bytes,
                command,
                stdout=out["stdout"],
                stderr=out["stderr"],
            )
            logger.info("RUN %s", result)

            return result

        if HAS_ANSIBLE_2:
            from collections import namedtuple
            from ansible.parsing.dataloader import DataLoader
            from ansible.vars import VariableManager
            from ansible.inventory import Inventory
            from ansible.playbook.play import Play
            from ansible.executor.task_queue_manager import TaskQueueManager
            from ansible.plugins.callback import CallbackBase

            class SilentCallbackModule(CallbackBase):
                """ A callback module that does not print anything, but keeps tabs
                on what's happening in an Ansible play.
                """
                def __init__(self):
                    self.unreachable = {}
                    self.contacted = {}

                def runner_on_ok(self, host, result):
                    self.contacted[host] = {'success': True, 'result': result}

                def runner_on_failed(self, host, result, ignore_errors=False):
                    self.contacted[host] = {'success': False, 'result': result}

                def runner_on_unreachable(self, host, result):
                    self.unreachable[host] = result

            callback = SilentCallbackModule()
            command = self.get_command(command, *args)
            Options = namedtuple('Options', [
                'connection', 'module_path', 'forks', 'remote_user',
                'private_key_file', 'ssh_common_args', 'ssh_extra_args',
                'sftp_extra_args', 'scp_extra_args', 'become', 'become_method',
                'become_user', 'verbosity', 'check'
            ])
            # initialize needed objects
            variable_manager = VariableManager()
            loader = DataLoader()
            options = Options(connection='smart',
                              module_path=None,
                              forks=100,
                              remote_user=None,
                              private_key_file=None,
                              ssh_common_args=None,
                              ssh_extra_args=None,
                              sftp_extra_args=None,
                              scp_extra_args=None,
                              become=None,
                              become_method=None,
                              become_user=None,
                              verbosity=None,
                              check=False)
            passwords = dict()

            # create inventory and pass to var manager
            inventory = Inventory(loader, variable_manager,
                                  self.ansible_inventory)
            variable_manager.set_inventory(inventory)

            # create play with tasks
            play_source = dict(
                name="Ansible Play",
                hosts=self.host,
                gather_facts='no',
                tasks=[dict(action=dict(module="shell", args=command))])
            play = Play().load(play_source,
                               variable_manager=variable_manager,
                               loader=loader)

            # actually run it
            tqm = None
            try:
                tqm = TaskQueueManager(
                    inventory=inventory,
                    variable_manager=variable_manager,
                    loader=loader,
                    options=options,
                    passwords=passwords,
                    stdout_callback=callback,
                )
                tqm.run(play)

                ret = base.CommandResult(
                    self,
                    0 if callback.contacted[self.host][u'success'] else 1,
                    bytes(callback.contacted[self.host][u'result']
                          ["stdout_lines"]),
                    b"",
                    command,
                    stdout=callback.contacted[self.host][u'result']["stdout"],
                    stderr=callback.contacted[self.host][u'result']["stdout"],
                )

                return ret
            finally:
                if tqm is not None:
                    tqm.cleanup()
コード例 #11
0
 def run(self, command, *args):
     command = self.get_command(command, *args)
     out = self.run_salt("cmd.run_all", [command])
     return base.CommandResult(
         self, out['retcode'], out['stdout'], out['stderr'], command)