Edits history of script submission #23913 for ' Push Config (arista_eos)'

  • python3
    One script reply has been approved by the moderators
    Ap­pro­ved
    # py312
    # requirements:
    # paramiko==5.1.0
    # pyeapi==1.0.4
    
    import base64
    import contextlib
    import hashlib
    import json
    import logging
    import re
    import secrets
    import socket
    import ssl
    import time
    from typing import Literal, TypedDict
    from urllib.parse import urlsplit
    
    import paramiko
    import pyeapi
    
    
    class arista_eos(TypedDict):
        host: str
        username: str
        password: str
        port: int
        verify_tls: bool
        allow_http: bool
    
    
    # Commands that leave the session or act on the switch at once (exec commands run inside a session too), matched as
    # EOS abbreviations ("wr" is write), also after no/default. Each is its first words; "*" is any one word. A denylist:
    # an exec command not in it still runs. pyeapi sends "<cmd> MULTILINE: <text>" as cmd + input.
    EXEC_COMMANDS = [c.split() for c in (
        "abort", "bash", "boot", "clear", "commit", "configure", "copy", "delete", "do", "end", "install", "ping", "reload",
        "rename", "reset", "send", "ssh", "telnet", "traceroute", "write", "zerotouch", "agent * terminate", "clock set",
        "redundancy force-switchover",
    )]
    
    
    def main(
        auth: arista_eos,
        lines: list[str],
        host: str = "",
        mode: Literal["diff", "commit", "commit_timer"] = "diff",
        session_name: str = "",
        timer_minutes: int = 10,
        replace: bool = False,
    ):
        """
        Push Config
        Apply configuration lines in a new EOS config session and return the diff. mode diff only shows the diff and aborts (dry run); commit applies it; commit_timer applies it and rolls it back by itself unless Confirm Commit runs within timer_minutes (1 to 5999). lines are configuration only: session control and a list of exec commands (commit, end, abort, configure, write, copy, reload, bash, delete, boot, clear, install, reset, agent terminate, do...) are refused, as is a line with a line break outside MULTILINE: text. A session_name already pending is refused; on any failure the session is aborted. Nothing is saved to startup-config: Confirm Commit saves, and Save Config refuses while a commit timer is pending. replace makes lines the whole running config (the session starts from a clean config): anything not in lines is removed, users and management access included, so check the diff first.
        """
        auth = with_host(auth, host)
        if session_name and not re.fullmatch(r"[A-Za-z0-9_.-]+", session_name):
            raise ValueError(f"session_name may only contain letters, digits, _ . -: {session_name!r}")
        timer_minutes = 10 if timer_minutes is None else timer_minutes
        if mode == "commit_timer" and not (isinstance(timer_minutes, int) and 1 <= timer_minutes <= 5999):
            raise ValueError(f"timer_minutes must be 1 to 5999 (EOS takes up to 99:59:00): {timer_minutes!r}")
        if replace and not lines:
            raise ValueError("replace needs the whole configuration in lines: an empty one would remove everything")
        for line in lines:
            cmd = line.split("MULTILINE:")[0]
            words = cmd.lower().split()
            if words[:1] in (["no"], ["default"]):
                words = words[1:]
            if "\n" in cmd or "\r" in cmd or any(
                len(words) >= len(c) and all(w == "*" or w.startswith(t) for w, t in zip(c, words)) for c in EXEC_COMMANDS
            ):
                raise ValueError(f"lines may only hold configuration commands, not {line!r}")
        session = session_name or f"windmill-{int(time.time() * 1000)}-{secrets.token_hex(3)}"
        eos = node(auth)
        # A session survives across eAPI calls by name, and reopening a pending one adds to it: refuse a live name.
        [sessions] = eos.run_commands(["show configuration sessions detail"])
        if sessions.get("sessions", {}).get(session, {}).get("state") == "pending" or sessions.get("commitTimerSessionName") == session:
            raise ValueError(f"config session {session} is already pending: commit or abort it, or pick another name")
        # Stage the lines, read the diff, then commit or abort. A failure leaves a pending session (EOS allows 5): abort it.
        try:
            clean = ["rollback clean-config"] if replace else []
            eos.run_commands([f"configure session {session}", *clean, *lines, "end"])
            [diff] = eos.run_commands([f"show session-config named {session} diffs"], "text")
            if mode == "commit":
                eos.run_commands([f"configure session {session} commit"])
            elif mode == "commit_timer":
                eos.run_commands(
                    [f"configure session {session} commit timer {timer_minutes // 60:02d}:{timer_minutes % 60:02d}:00"],
                )
            else:
                eos.run_commands([f"configure session {session} abort"])
        except Exception:
            with contextlib.suppress(Exception):
                eos.run_commands([f"configure session {session} abort"])
            raise
        return {
            "session": session,
            "mode": mode or "diff",
            "diff": diff["output"],
            "committed": mode in ("commit", "commit_timer"),
            "replace": bool(replace),
        }
    
    
    # One resource can serve every switch that shares a login: the host input, when set, overrides the resource's host.
    def with_host(auth: arista_eos, host: str):
        host = (host or "").strip() or (auth.get("host") or "").strip()
        if not host:
            raise ValueError("host is required: set it on the resource or pass host")
        return {**auth, "host": host}
    
    
    # SSH transport (transport: ssh): the EOS CLI over an SSH shell, behind the part of pyeapi's Node the scripts use
    # (run_commands, connection.socket_error, connection.transport.connect), raising pyeapi's own CommandError and
    # ConnectionError, so the checks and the error mapping are the same for both transports. Show commands in json get
    # "| json", which prints the eAPI JSON; other commands give { messages: [output] } like eAPI, or {} when silent.
    # A line starting with "% " is an error, raised as eAPI's CommandError. The host key is checked when the resource
    # has ssh_host_key (SHA256:... as ssh-keygen -lf prints it).
    class Ssh:
        def __init__(self, auth: arista_eos, timeout: float):
            self.auth, self.timeout = auth, timeout
            self.connection = self.transport = self
            self.socket_error = self.sock = self.chan = None
    
        # The TCP connection only, like eAPI's transport.connect(): if it fails, nothing was sent.
        def connect(self):
            self.sock = socket.create_connection(ssh_addr(self.auth), self.timeout)
    
        def lost(self, e):
            self.socket_error = e
            return pyeapi.eapilib.ConnectionError("ssh", f"SSH connection failed ({e})")
    
        def open(self):
            auth = self.auth
            try:
                if not self.sock:
                    self.connect()
                t = paramiko.Transport(self.sock)
                t.start_client(timeout=self.timeout)
                key = t.get_remote_server_key()
            except (OSError, EOFError, paramiko.SSHException) as e:
                raise self.lost(e)
            fp = "SHA256:" + base64.b64encode(hashlib.sha256(key.asbytes()).digest()).decode().rstrip("=")
            if auth.get("ssh_host_key") and auth["ssh_host_key"].strip() != fp:
                t.close()
                raise RuntimeError(f"{auth['host']}: the SSH host key is {fp}, not the resource's ssh_host_key")
            try:
                try:
                    t.auth_password(auth["username"], auth["password"])
                except paramiko.BadAuthenticationType:
                    t.auth_interactive(
                        auth["username"], lambda _t, _i, prompts: [auth["password"]] * len(prompts)
                    )
            except paramiko.AuthenticationException as e:
                t.close()
                raise pyeapi.eapilib.ConnectionError("ssh", str(e))
            except (OSError, EOFError, paramiko.SSHException) as e:
                raise self.lost(e)
            try:
                self.chan = t.open_session()
                self.chan.get_pty(width=4000)
                self.chan.invoke_shell()
                self.prompt = None
                out = self.read()
                self.prompt = re.escape(re.split(r"[(>#]", out.splitlines()[-1].strip())[0])
                if out.rstrip().endswith(">"):
                    self.cli("enable")
                self.cli("terminal length 0")
                self.cli("terminal width 32767")
            except (OSError, EOFError, paramiko.SSHException) as e:
                raise self.lost(e)
    
        # Reads until the prompt. Questions eAPI never asks are answered as eAPI behaves: confirm, don't save.
        def read(self):
            buf, end = "", time.monotonic() + self.timeout
            prompt = (self.prompt or r"[\w.\-]+") + r"(\([^)\r\n]*\))?[>#] ?$"
            while True:
                self.chan.settimeout(max(end - time.monotonic(), 0.01))
                chunk = self.chan.recv(65536)
                if not chunk:
                    raise self.lost("connection closed")
                buf += chunk.decode(errors="replace")
                tail = buf[-300:]
                if re.search(r"(^|\n)" + prompt, tail):
                    return buf
                for question, answer in (
                    # enable asks for a password on switches that land the user unprivileged: the login password.
                    (r"(^|\n)Password:\s*$", self.auth["password"]),
                    (r"\[confirm\]\s*$", ""),
                    (r"Save\?.*\[yes/no[^\]]*\]:?\s*$", "no"),
                    (r"\[(y|yes)/(n|no)\][:?]?\s*$", "y"),
                ):
                    if re.search(question, tail, re.I):
                        self.chan.send(answer + "\r")
                        buf += "\n"
    
        # One command: its output without the echoed command and the prompt; progress lines keep their last state.
        def cli(self, cmd):
            try:
                self.chan.send(cmd + "\r")
                out = self.read()
            except (OSError, EOFError, paramiko.SSHException) as e:
                raise self.lost(e)
            self.mode = out.rstrip().splitlines()[-1]
            lines = [l.rstrip("\r").split("\r")[-1] for l in out.split("\n")]
            return "\n".join(lines[1:-1]).strip("\n")
    
        def run_commands(self, cmds, encoding="json", **_):
            try:
                if not self.chan:
                    self.open()
                if "(config" in self.mode:
                    self.cli("end")
                results = []
                for i, c in enumerate(cmds):
                    # eAPI's { cmd, revision } form is the CLI's "| json revision N".
                    cmd, rev = (c["cmd"], c.get("revision")) if isinstance(c, dict) else (c, None)
                    show = encoding == "json" and (rev or re.match(r"\s*sh(ow)?\s", cmd)) and not re.search(r"\|\s*json", cmd)
                    # pyeapi sends "<cmd> MULTILINE: <text>" (banners) as cmd + input; the CLI reads the text up to EOF.
                    head, multi, text = cmd.partition("MULTILINE:")
                    # The shell would run what follows a line break as another command; eAPI refuses it too.
                    if re.search(r"[\r\n]", head):
                        raise ValueError(f"a command may not contain a line break: {head!r}")
                    line = "\r".join([head.strip(), *text.strip().splitlines(), "EOF"]) if multi else cmd
                    out = self.cli(f"{cmd} | json{f' revision {rev}' if rev else ''}" if show else line)
                    errors = [l[2:] for l in out.splitlines() if l.startswith("% ")]
                    code, kind = 1002, "invalid command"
                    if show and not errors:
                        code, kind = 1000, "could not run command"
                        try:
                            result = json.loads(out)
                        except ValueError:
                            errors = [out[:200]]
                        else:
                            errors = result.get("errors") or []
                    if errors:
                        raise pyeapi.eapilib.CommandError(
                            code,
                            f"CLI command {i + 2} of {len(cmds) + 1} '{cmd}' failed: {kind}",
                            command_error="; ".join(errors),
                            commands=cmds,
                            output=results,
                        )
                    if encoding != "json":
                        result = {"output": out + "\n" if out else ""}
                    elif not show:
                        # The CLI prints eAPI's warnings as "! " notices.
                        notices = [l[2:].strip() for l in out.splitlines() if l.startswith("! ")]
                        out = "\n".join(l for l in out.splitlines() if not l.startswith("! ")).strip()
                        result = {"messages": [out]} if out and not multi else {}
                        if notices:
                            result["warnings"] = notices
                    results.append(result)
                return results
            except pyeapi.eapilib.ConnectionError:
                if self.chan:
                    self.chan.close()
                self.sock = self.chan = None
                raise
    
    
    # paramiko logs a traceback when a rebooting switch drops the session.
    logging.getLogger("paramiko").addHandler(logging.NullHandler())
    
    
    # host, or host:port ([v6]:port), else port, else 22.
    def ssh_addr(auth: arista_eos):
        h = auth["host"]
        if "://" in h:
            raise ValueError(f"with transport ssh, host is an address or a hostname (with :port), not a URL: {h}")
        url = urlsplit(f"ssh://{h}" if h.count(":") <= 1 or h.startswith("[") else f"ssh://[{h}]")
        return url.hostname, url.port or int(auth.get("port") or 22)
    
    
    # Every action raises DeviceUnreachable when the switch can't be reached and AuthFailure when it refuses the
    # credential, so a flow can retry on result.error.name. Command errors stay pyeapi's CommandError.
    def node(auth: arista_eos, timeout: float = 60):
        eos = open_node(auth, timeout)
        run = eos.run_commands
    
        def run_commands(*args, **kwargs):
            try:
                return run(*args, **kwargs)
            except pyeapi.eapilib.ConnectionError as e:
                raise connection_error(auth, eos, e)
    
        eos.run_commands = run_commands
        return eos
    
    
    # pyeapi 1.0.4 raises ConnectionError for a socket error (kept in socket_error), an answer that isn't JSON (eAPI
    # still starting, 5xx) and a 401, the only one with neither.
    def connection_error(auth, eos, e):
        # A certificate the resource does not trust is a setting to fix (verify_tls, ca_certificate), not worth a retry.
        if isinstance(eos.connection.socket_error, ssl.SSLCertVerificationError):
            return RuntimeError(f"{auth['host']}: {eos.connection.socket_error}")
        if eos.connection.socket_error is None and e.message != "unable to connect to eAPI":
            return AuthFailure(f"{auth['host']}: {'SSH' if auth.get('transport') == 'ssh' else 'eAPI'} refused the credential ({e.message})")
        return DeviceUnreachable(f"{auth['host']}: {e.message}")
    
    
    class DeviceUnreachable(Exception):
        pass
    
    
    class AuthFailure(Exception):
        pass
    
    
    # pyeapi logs a traceback for every socket error.
    logging.getLogger("pyeapi").addHandler(logging.NullHandler())
    
    
    # host is an address or a URL (https://10.0.0.11:8443); a bare IPv6 address is bracketed. Only https, or http when the
    # resource ticks allow_http (Basic auth then crosses the network in cleartext). pyeapi skips certificate checks unless it
    # is given a context, so one is always passed: verifying, or not when the resource unticks verify_tls (EOS ships a
    # self-signed cert).
    def open_node(auth: arista_eos, timeout: float = 60):
        if auth.get("transport") == "ssh":
            return Ssh(auth, timeout)
        host = auth["host"]
        if "://" not in host:
            host = f"https://[{host}]" if host.count(":") > 1 and "[" not in host else f"https://{host}"
        url = urlsplit(host)
        if not url.hostname or (url.scheme != "https" and not (url.scheme == "http" and auth.get("allow_http"))):
            raise ValueError(f"host must be an address or an https:// URL (http:// needs allow_http on the resource): {auth['host']}")
        # ca_certificate: the PEM of a private CA, trusted instead of the system's CAs.
        context = ssl.create_default_context(cadata=(auth.get("ca_certificate") or "").strip() or None)
        if auth.get("verify_tls") is False:
            context.check_hostname = False
            context.verify_mode = ssl.CERT_NONE
        return pyeapi.connect(
            transport=url.scheme,
            host=url.hostname,
            port=url.port or auth.get("port") or None,
            username=auth["username"],
            password=auth["password"],
            context=context,
            timeout=timeout,
            return_node=True,
        )
    

    Submitted by hugo989 4 days ago

  • python3
    # py312
    # requirements:
    # pyeapi==1.0.4
    
    import contextlib
    import re
    import secrets
    import ssl
    import time
    from typing import Literal, TypedDict
    from urllib.parse import urlsplit
    
    import pyeapi
    
    
    class arista_eos(TypedDict):
        host: str
        username: str
        password: str
        port: int
        verify_tls: bool
        allow_http: bool
    
    
    # Commands that leave the session or act on the switch at once (exec commands run inside a session too), matched as
    # EOS abbreviations ("wr" is write), also after no/default. Each is its first words; "*" is any one word. A denylist:
    # an exec command not in it still runs. pyeapi sends "<cmd> MULTILINE: <text>" as cmd + input.
    EXEC_COMMANDS = [c.split() for c in (
        "abort", "bash", "boot", "clear", "commit", "configure", "copy", "delete", "do", "end", "install", "ping", "reload",
        "rename", "reset", "send", "ssh", "telnet", "traceroute", "write", "zerotouch", "agent * terminate", "clock set",
        "redundancy force-switchover",
    )]
    
    
    def main(
        auth: arista_eos,
        lines: list[str],
        mode: Literal["diff", "commit", "commit_timer"] = "diff",
        session_name: str = "",
        timer_minutes: int = 10,
    ):
        """
        Push Config
        Apply configuration lines in a new EOS config session and return the diff. mode diff only shows the diff and aborts (dry run); commit applies it; commit_timer applies it and rolls it back by itself unless Confirm Commit runs within timer_minutes (1 to 5999). lines are configuration only: session control and a list of exec commands (commit, end, abort, configure, write, copy, reload, bash, delete, boot, clear, install, reset, agent terminate, do...) are refused, as is a line with a line break outside MULTILINE: text. A session_name already pending is refused; on any failure the session is aborted. Nothing is saved to startup-config: Confirm Commit saves, and Save Config refuses while a commit timer is pending.
        """
        if session_name and not re.fullmatch(r"[A-Za-z0-9_.-]+", session_name):
            raise ValueError(f"session_name may only contain letters, digits, _ . -: {session_name!r}")
        timer_minutes = 10 if timer_minutes is None else timer_minutes
        if mode == "commit_timer" and not (isinstance(timer_minutes, int) and 1 <= timer_minutes <= 5999):
            raise ValueError(f"timer_minutes must be 1 to 5999 (EOS takes up to 99:59:00): {timer_minutes!r}")
        for line in lines:
            cmd = line.split("MULTILINE:")[0]
            words = cmd.lower().split()
            if words[:1] in (["no"], ["default"]):
                words = words[1:]
            if "\n" in cmd or "\r" in cmd or any(
                len(words) >= len(c) and all(w == "*" or w.startswith(t) for w, t in zip(c, words)) for c in EXEC_COMMANDS
            ):
                raise ValueError(f"lines may only hold configuration commands, not {line!r}")
        session = session_name or f"windmill-{int(time.time() * 1000)}-{secrets.token_hex(3)}"
        eos = node(auth)
        # A session survives across eAPI calls by name, and reopening a pending one adds to it: refuse a live name.
        [sessions] = eos.run_commands(["show configuration sessions detail"])
        if sessions.get("sessions", {}).get(session, {}).get("state") == "pending" or sessions.get("commitTimerSessionName") == session:
            raise ValueError(f"config session {session} is already pending: commit or abort it, or pick another name")
        # Stage the lines, read the diff, then commit or abort. A failure leaves a pending session (EOS allows 5): abort it.
        try:
            eos.run_commands([f"configure session {session}", *lines, "end"])
            [diff] = eos.run_commands([f"show session-config named {session} diffs"], "text")
            if mode == "commit":
                eos.run_commands([f"configure session {session} commit"])
            elif mode == "commit_timer":
                eos.run_commands(
                    [f"configure session {session} commit timer {timer_minutes // 60:02d}:{timer_minutes % 60:02d}:00"],
                )
            else:
                eos.run_commands([f"configure session {session} abort"])
        except Exception:
            with contextlib.suppress(Exception):
                eos.run_commands([f"configure session {session} abort"])
            raise
        return {
            "session": session,
            "mode": mode or "diff",
            "diff": diff["output"],
            "committed": mode in ("commit", "commit_timer"),
        }
    
    
    # host is an address or a URL (https://10.0.0.11:8443); a bare IPv6 address is bracketed. Only https, or http when the
    # resource ticks allow_http (Basic auth then crosses the network in cleartext). pyeapi skips certificate checks unless it
    # is given a context, so one is always passed: verifying, or not when the resource unticks verify_tls (EOS ships a
    # self-signed cert).
    def node(auth: arista_eos, timeout: float = 60):
        host = auth["host"]
        if "://" not in host:
            host = f"https://[{host}]" if host.count(":") > 1 and "[" not in host else f"https://{host}"
        url = urlsplit(host)
        if not url.hostname or (url.scheme != "https" and not (url.scheme == "http" and auth.get("allow_http"))):
            raise ValueError(f"host must be an address or an https:// URL (http:// needs allow_http on the resource): {auth['host']}")
        context = ssl.create_default_context()
        if auth.get("verify_tls") is False:
            context.check_hostname = False
            context.verify_mode = ssl.CERT_NONE
        return pyeapi.connect(
            transport=url.scheme,
            host=url.hostname,
            port=url.port or auth.get("port") or None,
            username=auth["username"],
            password=auth["password"],
            context=context,
            timeout=timeout,
            return_node=True,
        )
    

    Submitted by hugo989 20 days ago

  • python3
    # py312
    # requirements:
    # pyeapi==1.0.4
    
    import ssl
    import time
    from typing import Literal, TypedDict
    from urllib.parse import urlsplit
    
    import pyeapi
    
    
    class arista_eos(TypedDict):
        host: str
        username: str
        password: str
        port: int
        verify_tls: bool
    
    
    def main(
        auth: arista_eos,
        lines: list[str],
        mode: Literal["diff", "commit", "commit_timer"] = "diff",
        session_name: str = "",
        timer_minutes: int = 10,
    ):
        """
        Push Config
        Apply configuration lines in an EOS config session and return the diff. mode diff only shows the diff and aborts (dry run); commit applies it; commit_timer applies it and rolls it back by itself unless Confirm Commit runs within timer_minutes. Nothing is saved to startup-config: run Save Config (or Confirm Commit) for that.
        """
        session = session_name or f"windmill-{int(time.time() * 1000)}"
        # A session survives across eAPI calls by name: stage the lines, read the diff, then commit or abort it.
        eos = node(auth)
        eos.run_commands([f"configure session {session}", *lines, "end"])
        [diff] = eos.run_commands([f"show session-config named {session} diffs"], "text")
        if mode == "commit":
            eos.run_commands([f"configure session {session} commit"])
        elif mode == "commit_timer":
            m = timer_minutes or 10
            eos.run_commands(
                [f"configure session {session} commit timer {m // 60:02d}:{m % 60:02d}:00"],
            )
        else:
            eos.run_commands([f"configure session {session} abort"])
        return {
            "session": session,
            "mode": mode or "diff",
            "diff": diff["output"],
            "committed": mode in ("commit", "commit_timer"),
        }
    
    
    # host is an address or a URL (https://10.0.0.11:8443). pyeapi skips certificate checks unless it is given a context,
    # so one is always passed: verifying, or not when the resource unticks verify_tls (EOS ships a self-signed cert).
    def node(auth: arista_eos, timeout: float = 60):
        url = urlsplit(auth["host"] if "://" in auth["host"] else f"https://{auth['host']}")
        context = ssl.create_default_context()
        if auth.get("verify_tls") is False:
            context.check_hostname = False
            context.verify_mode = ssl.CERT_NONE
        return pyeapi.connect(
            transport=url.scheme,
            host=url.hostname,
            port=url.port or auth.get("port") or None,
            username=auth["username"],
            password=auth["password"],
            context=context,
            timeout=timeout,
            return_node=True,
        )
    

    Submitted by hugo989 21 days ago