Exemple #1
0
 def send(
     self,
     command,
     prompt=None,
     answer=None,
     newline=True,
     sendonly=False,
     prompt_retry_check=False,
     check_all=False,
 ):
     """
     Sends the command to the device in the opened shell
     """
     if check_all:
         prompt_len = len(to_list(prompt))
         answer_len = len(to_list(answer))
         if prompt_len != answer_len:
             raise AssibleConnectionFailure(
                 "Number of prompts (%s) is not same as that of answers (%s)"
                 % (prompt_len, answer_len))
     try:
         cmd = b"%s\r" % command
         self._history.append(cmd)
         self._ssh_shell.sendall(cmd)
         self._log_messages("send command: %s" % cmd)
         if sendonly:
             return
         response = self.receive(command, prompt, answer, newline,
                                 prompt_retry_check, check_all)
         return to_text(response, errors="surrogate_then_replace")
     except (socket.timeout, AttributeError):
         self.queue_message("error", traceback.format_exc())
         raise AssibleConnectionFailure(
             "timeout value %s seconds reached while trying to send command: %s"
             % (self._ssh_shell.gettimeout(), command.strip()))
Exemple #2
0
def get_config(module, flags=None):
    flags = to_list(flags)

    section_filter = False
    if flags and "section" in flags[-1]:
        section_filter = True

    flag_str = " ".join(flags)

    try:
        return _DEVICE_CONFIGS[flag_str]
    except KeyError:
        connection = get_connection(module)
        try:
            out = connection.get_config(flags=flags)
        except ConnectionError as exc:
            if section_filter:
                # Some ios devices don't understand `| section foo`
                out = get_config(module, flags=flags[:-1])
            else:
                module.fail_json(
                    msg=to_text(exc, errors="surrogate_then_replace"))
        cfg = to_text(out, errors="surrogate_then_replace").strip()
        _DEVICE_CONFIGS[flag_str] = cfg
        return cfg
Exemple #3
0
    def run_commands(self, commands=None, check_rc=True):
        if commands is None:
            raise ValueError("'commands' value is required")

        responses = list()
        for cmd in to_list(commands):
            if not isinstance(cmd, Mapping):
                cmd = {"command": cmd}

            output = cmd.pop("output", None)
            if output:
                raise ValueError(
                    "'output' value %s is not supported for run_commands" %
                    output)

            try:
                out = self.send_command(**cmd)
            except AssibleConnectionFailure as e:
                if check_rc:
                    raise
                out = getattr(e, "err", e)

            responses.append(out)

        return responses
Exemple #4
0
    def edit_config(self,
                    candidate=None,
                    commit=True,
                    replace=None,
                    comment=None):
        resp = {}
        operations = self.get_device_operations()
        self.check_edit_config_capability(operations, candidate, commit,
                                          replace, comment)

        results = []
        requests = []
        if commit:
            self.send_command("configure terminal")
            for line in to_list(candidate):
                if not isinstance(line, Mapping):
                    line = {"command": line}

                cmd = line["command"]
                if cmd != "end" and cmd[0] != "!":
                    results.append(self.send_command(**line))
                    requests.append(cmd)

            self.send_command("end")
        else:
            raise ValueError("check mode is not supported")

        resp["request"] = requests
        resp["response"] = results
        return resp
Exemple #5
0
    def set_config(self, existing_lldp_interfaces_facts):
        """ Collect the configuration from the args passed to the module,
            collect the current configuration (as a dict from facts)

        :rtype: A list
        :returns: the commands necessary to migrate the current configuration
                  to the desired configuration
        """
        want = self._module.params["config"]
        have = existing_lldp_interfaces_facts
        resp = self.set_state(want, have)
        return to_list(resp)
Exemple #6
0
    def edit_config(self,
                    candidate=None,
                    commit=True,
                    replace=None,
                    comment=None):
        resp = {}
        operations = self.get_device_operations()
        self.check_edit_config_capability(operations, candidate, commit,
                                          replace, comment)

        results = []
        requests = []
        self.send_command("configure")
        for cmd in to_list(candidate):
            if not isinstance(cmd, Mapping):
                cmd = {"command": cmd}

            results.append(self.send_command(**cmd))
            requests.append(cmd["command"])
        out = self.get("compare")
        out = to_text(out, errors="surrogate_or_strict")
        diff_config = out if not out.startswith("No changes") else None

        if diff_config:
            if commit:
                try:
                    self.commit(comment)
                except AssibleConnectionFailure as e:
                    msg = "commit failed: %s" % e.message
                    self.discard_changes()
                    raise AssibleConnectionFailure(msg)
                else:
                    self.send_command("exit")
            else:
                self.discard_changes()
        else:
            self.send_command("exit")
            if (to_text(self._connection.get_prompt(),
                        errors="surrogate_or_strict").strip().endswith("#")):
                self.discard_changes()

        if diff_config:
            resp["diff"] = diff_config
        resp["response"] = results
        resp["request"] = requests
        return resp
Exemple #7
0
    def get_config(self, source="running", flags=None, format=None):
        if source not in ("running", "startup"):
            raise ValueError(
                "fetching configuration from %s is not supported" % source)

        if format:
            raise ValueError(
                "'format' value %s is not supported for get_config" % format)

        if not flags:
            flags = []
        if source == "running":
            cmd = "show running-config "
        else:
            cmd = "show startup-config "

        cmd += " ".join(to_list(flags))
        cmd = cmd.strip()

        return self.send_command(cmd)
Exemple #8
0
    def get_config(self, flags=None, format=None):
        if format:
            option_values = self.get_option_values()
            if format not in option_values["format"]:
                raise ValueError(
                    "'format' value %s is invalid. Valid values of format are %s"
                    % (format, ", ".join(option_values["format"])))

        if not flags:
            flags = []

        if format == "text":
            command = "show configuration"
        else:
            command = "show configuration commands"

        command += " ".join(to_list(flags))
        command = command.strip()

        out = self.send_command(command)
        return out