0

Push Config

Published 20 days ago

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.

Script arista_eos Verified

The script

Submitted by hugo989 Python3
Verified 4 days ago
1
# py312
2
# requirements:
3
# paramiko==5.1.0
4
# pyeapi==1.0.4
5

6
import base64
7
import contextlib
8
import hashlib
9
import json
10
import logging
11
import re
12
import secrets
13
import socket
14
import ssl
15
import time
16
from typing import Literal, TypedDict
17
from urllib.parse import urlsplit
18

19
import paramiko
20
import pyeapi
21

22

23
class arista_eos(TypedDict):
24
    host: str
25
    username: str
26
    password: str
27
    port: int
28
    verify_tls: bool
29
    allow_http: bool
30

31

32
# Commands that leave the session or act on the switch at once (exec commands run inside a session too), matched as
33
# EOS abbreviations ("wr" is write), also after no/default. Each is its first words; "*" is any one word. A denylist:
34
# an exec command not in it still runs. pyeapi sends "<cmd> MULTILINE: <text>" as cmd + input.
35
EXEC_COMMANDS = [c.split() for c in (
36
    "abort", "bash", "boot", "clear", "commit", "configure", "copy", "delete", "do", "end", "install", "ping", "reload",
37
    "rename", "reset", "send", "ssh", "telnet", "traceroute", "write", "zerotouch", "agent * terminate", "clock set",
38
    "redundancy force-switchover",
39
)]
40

41

42
def main(
43
    auth: arista_eos,
44
    lines: list[str],
45
    host: str = "",
46
    mode: Literal["diff", "commit", "commit_timer"] = "diff",
47
    session_name: str = "",
48
    timer_minutes: int = 10,
49
    replace: bool = False,
50
):
51
    """
52
    Push Config
53
    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.
54
    """
55
    auth = with_host(auth, host)
56
    if session_name and not re.fullmatch(r"[A-Za-z0-9_.-]+", session_name):
57
        raise ValueError(f"session_name may only contain letters, digits, _ . -: {session_name!r}")
58
    timer_minutes = 10 if timer_minutes is None else timer_minutes
59
    if mode == "commit_timer" and not (isinstance(timer_minutes, int) and 1 <= timer_minutes <= 5999):
60
        raise ValueError(f"timer_minutes must be 1 to 5999 (EOS takes up to 99:59:00): {timer_minutes!r}")
61
    if replace and not lines:
62
        raise ValueError("replace needs the whole configuration in lines: an empty one would remove everything")
63
    for line in lines:
64
        cmd = line.split("MULTILINE:")[0]
65
        words = cmd.lower().split()
66
        if words[:1] in (["no"], ["default"]):
67
            words = words[1:]
68
        if "\n" in cmd or "\r" in cmd or any(
69
            len(words) >= len(c) and all(w == "*" or w.startswith(t) for w, t in zip(c, words)) for c in EXEC_COMMANDS
70
        ):
71
            raise ValueError(f"lines may only hold configuration commands, not {line!r}")
72
    session = session_name or f"windmill-{int(time.time() * 1000)}-{secrets.token_hex(3)}"
73
    eos = node(auth)
74
    # A session survives across eAPI calls by name, and reopening a pending one adds to it: refuse a live name.
75
    [sessions] = eos.run_commands(["show configuration sessions detail"])
76
    if sessions.get("sessions", {}).get(session, {}).get("state") == "pending" or sessions.get("commitTimerSessionName") == session:
77
        raise ValueError(f"config session {session} is already pending: commit or abort it, or pick another name")
78
    # Stage the lines, read the diff, then commit or abort. A failure leaves a pending session (EOS allows 5): abort it.
79
    try:
80
        clean = ["rollback clean-config"] if replace else []
81
        eos.run_commands([f"configure session {session}", *clean, *lines, "end"])
82
        [diff] = eos.run_commands([f"show session-config named {session} diffs"], "text")
83
        if mode == "commit":
84
            eos.run_commands([f"configure session {session} commit"])
85
        elif mode == "commit_timer":
86
            eos.run_commands(
87
                [f"configure session {session} commit timer {timer_minutes // 60:02d}:{timer_minutes % 60:02d}:00"],
88
            )
89
        else:
90
            eos.run_commands([f"configure session {session} abort"])
91
    except Exception:
92
        with contextlib.suppress(Exception):
93
            eos.run_commands([f"configure session {session} abort"])
94
        raise
95
    return {
96
        "session": session,
97
        "mode": mode or "diff",
98
        "diff": diff["output"],
99
        "committed": mode in ("commit", "commit_timer"),
100
        "replace": bool(replace),
101
    }
102

103

104
# One resource can serve every switch that shares a login: the host input, when set, overrides the resource's host.
105
def with_host(auth: arista_eos, host: str):
106
    host = (host or "").strip() or (auth.get("host") or "").strip()
107
    if not host:
108
        raise ValueError("host is required: set it on the resource or pass host")
109
    return {**auth, "host": host}
110

111

112
# SSH transport (transport: ssh): the EOS CLI over an SSH shell, behind the part of pyeapi's Node the scripts use
113
# (run_commands, connection.socket_error, connection.transport.connect), raising pyeapi's own CommandError and
114
# ConnectionError, so the checks and the error mapping are the same for both transports. Show commands in json get
115
# "| json", which prints the eAPI JSON; other commands give { messages: [output] } like eAPI, or {} when silent.
116
# A line starting with "% " is an error, raised as eAPI's CommandError. The host key is checked when the resource
117
# has ssh_host_key (SHA256:... as ssh-keygen -lf prints it).
118
class Ssh:
119
    def __init__(self, auth: arista_eos, timeout: float):
120
        self.auth, self.timeout = auth, timeout
121
        self.connection = self.transport = self
122
        self.socket_error = self.sock = self.chan = None
123

124
    # The TCP connection only, like eAPI's transport.connect(): if it fails, nothing was sent.
125
    def connect(self):
126
        self.sock = socket.create_connection(ssh_addr(self.auth), self.timeout)
127

128
    def lost(self, e):
129
        self.socket_error = e
130
        return pyeapi.eapilib.ConnectionError("ssh", f"SSH connection failed ({e})")
131

132
    def open(self):
133
        auth = self.auth
134
        try:
135
            if not self.sock:
136
                self.connect()
137
            t = paramiko.Transport(self.sock)
138
            t.start_client(timeout=self.timeout)
139
            key = t.get_remote_server_key()
140
        except (OSError, EOFError, paramiko.SSHException) as e:
141
            raise self.lost(e)
142
        fp = "SHA256:" + base64.b64encode(hashlib.sha256(key.asbytes()).digest()).decode().rstrip("=")
143
        if auth.get("ssh_host_key") and auth["ssh_host_key"].strip() != fp:
144
            t.close()
145
            raise RuntimeError(f"{auth['host']}: the SSH host key is {fp}, not the resource's ssh_host_key")
146
        try:
147
            try:
148
                t.auth_password(auth["username"], auth["password"])
149
            except paramiko.BadAuthenticationType:
150
                t.auth_interactive(
151
                    auth["username"], lambda _t, _i, prompts: [auth["password"]] * len(prompts)
152
                )
153
        except paramiko.AuthenticationException as e:
154
            t.close()
155
            raise pyeapi.eapilib.ConnectionError("ssh", str(e))
156
        except (OSError, EOFError, paramiko.SSHException) as e:
157
            raise self.lost(e)
158
        try:
159
            self.chan = t.open_session()
160
            self.chan.get_pty(width=4000)
161
            self.chan.invoke_shell()
162
            self.prompt = None
163
            out = self.read()
164
            self.prompt = re.escape(re.split(r"[(>#]", out.splitlines()[-1].strip())[0])
165
            if out.rstrip().endswith(">"):
166
                self.cli("enable")
167
            self.cli("terminal length 0")
168
            self.cli("terminal width 32767")
169
        except (OSError, EOFError, paramiko.SSHException) as e:
170
            raise self.lost(e)
171

172
    # Reads until the prompt. Questions eAPI never asks are answered as eAPI behaves: confirm, don't save.
173
    def read(self):
174
        buf, end = "", time.monotonic() + self.timeout
175
        prompt = (self.prompt or r"[\w.\-]+") + r"(\([^)\r\n]*\))?[>#] ?$"
176
        while True:
177
            self.chan.settimeout(max(end - time.monotonic(), 0.01))
178
            chunk = self.chan.recv(65536)
179
            if not chunk:
180
                raise self.lost("connection closed")
181
            buf += chunk.decode(errors="replace")
182
            tail = buf[-300:]
183
            if re.search(r"(^|\n)" + prompt, tail):
184
                return buf
185
            for question, answer in (
186
                # enable asks for a password on switches that land the user unprivileged: the login password.
187
                (r"(^|\n)Password:\s*$", self.auth["password"]),
188
                (r"\[confirm\]\s*$", ""),
189
                (r"Save\?.*\[yes/no[^\]]*\]:?\s*$", "no"),
190
                (r"\[(y|yes)/(n|no)\][:?]?\s*$", "y"),
191
            ):
192
                if re.search(question, tail, re.I):
193
                    self.chan.send(answer + "\r")
194
                    buf += "\n"
195

196
    # One command: its output without the echoed command and the prompt; progress lines keep their last state.
197
    def cli(self, cmd):
198
        try:
199
            self.chan.send(cmd + "\r")
200
            out = self.read()
201
        except (OSError, EOFError, paramiko.SSHException) as e:
202
            raise self.lost(e)
203
        self.mode = out.rstrip().splitlines()[-1]
204
        lines = [l.rstrip("\r").split("\r")[-1] for l in out.split("\n")]
205
        return "\n".join(lines[1:-1]).strip("\n")
206

207
    def run_commands(self, cmds, encoding="json", **_):
208
        try:
209
            if not self.chan:
210
                self.open()
211
            if "(config" in self.mode:
212
                self.cli("end")
213
            results = []
214
            for i, c in enumerate(cmds):
215
                # eAPI's { cmd, revision } form is the CLI's "| json revision N".
216
                cmd, rev = (c["cmd"], c.get("revision")) if isinstance(c, dict) else (c, None)
217
                show = encoding == "json" and (rev or re.match(r"\s*sh(ow)?\s", cmd)) and not re.search(r"\|\s*json", cmd)
218
                # pyeapi sends "<cmd> MULTILINE: <text>" (banners) as cmd + input; the CLI reads the text up to EOF.
219
                head, multi, text = cmd.partition("MULTILINE:")
220
                # The shell would run what follows a line break as another command; eAPI refuses it too.
221
                if re.search(r"[\r\n]", head):
222
                    raise ValueError(f"a command may not contain a line break: {head!r}")
223
                line = "\r".join([head.strip(), *text.strip().splitlines(), "EOF"]) if multi else cmd
224
                out = self.cli(f"{cmd} | json{f' revision {rev}' if rev else ''}" if show else line)
225
                errors = [l[2:] for l in out.splitlines() if l.startswith("% ")]
226
                code, kind = 1002, "invalid command"
227
                if show and not errors:
228
                    code, kind = 1000, "could not run command"
229
                    try:
230
                        result = json.loads(out)
231
                    except ValueError:
232
                        errors = [out[:200]]
233
                    else:
234
                        errors = result.get("errors") or []
235
                if errors:
236
                    raise pyeapi.eapilib.CommandError(
237
                        code,
238
                        f"CLI command {i + 2} of {len(cmds) + 1} '{cmd}' failed: {kind}",
239
                        command_error="; ".join(errors),
240
                        commands=cmds,
241
                        output=results,
242
                    )
243
                if encoding != "json":
244
                    result = {"output": out + "\n" if out else ""}
245
                elif not show:
246
                    # The CLI prints eAPI's warnings as "! " notices.
247
                    notices = [l[2:].strip() for l in out.splitlines() if l.startswith("! ")]
248
                    out = "\n".join(l for l in out.splitlines() if not l.startswith("! ")).strip()
249
                    result = {"messages": [out]} if out and not multi else {}
250
                    if notices:
251
                        result["warnings"] = notices
252
                results.append(result)
253
            return results
254
        except pyeapi.eapilib.ConnectionError:
255
            if self.chan:
256
                self.chan.close()
257
            self.sock = self.chan = None
258
            raise
259

260

261
# paramiko logs a traceback when a rebooting switch drops the session.
262
logging.getLogger("paramiko").addHandler(logging.NullHandler())
263

264

265
# host, or host:port ([v6]:port), else port, else 22.
266
def ssh_addr(auth: arista_eos):
267
    h = auth["host"]
268
    if "://" in h:
269
        raise ValueError(f"with transport ssh, host is an address or a hostname (with :port), not a URL: {h}")
270
    url = urlsplit(f"ssh://{h}" if h.count(":") <= 1 or h.startswith("[") else f"ssh://[{h}]")
271
    return url.hostname, url.port or int(auth.get("port") or 22)
272

273

274
# Every action raises DeviceUnreachable when the switch can't be reached and AuthFailure when it refuses the
275
# credential, so a flow can retry on result.error.name. Command errors stay pyeapi's CommandError.
276
def node(auth: arista_eos, timeout: float = 60):
277
    eos = open_node(auth, timeout)
278
    run = eos.run_commands
279

280
    def run_commands(*args, **kwargs):
281
        try:
282
            return run(*args, **kwargs)
283
        except pyeapi.eapilib.ConnectionError as e:
284
            raise connection_error(auth, eos, e)
285

286
    eos.run_commands = run_commands
287
    return eos
288

289

290
# pyeapi 1.0.4 raises ConnectionError for a socket error (kept in socket_error), an answer that isn't JSON (eAPI
291
# still starting, 5xx) and a 401, the only one with neither.
292
def connection_error(auth, eos, e):
293
    # A certificate the resource does not trust is a setting to fix (verify_tls, ca_certificate), not worth a retry.
294
    if isinstance(eos.connection.socket_error, ssl.SSLCertVerificationError):
295
        return RuntimeError(f"{auth['host']}: {eos.connection.socket_error}")
296
    if eos.connection.socket_error is None and e.message != "unable to connect to eAPI":
297
        return AuthFailure(f"{auth['host']}: {'SSH' if auth.get('transport') == 'ssh' else 'eAPI'} refused the credential ({e.message})")
298
    return DeviceUnreachable(f"{auth['host']}: {e.message}")
299

300

301
class DeviceUnreachable(Exception):
302
    pass
303

304

305
class AuthFailure(Exception):
306
    pass
307

308

309
# pyeapi logs a traceback for every socket error.
310
logging.getLogger("pyeapi").addHandler(logging.NullHandler())
311

312

313
# 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
314
# resource ticks allow_http (Basic auth then crosses the network in cleartext). pyeapi skips certificate checks unless it
315
# is given a context, so one is always passed: verifying, or not when the resource unticks verify_tls (EOS ships a
316
# self-signed cert).
317
def open_node(auth: arista_eos, timeout: float = 60):
318
    if auth.get("transport") == "ssh":
319
        return Ssh(auth, timeout)
320
    host = auth["host"]
321
    if "://" not in host:
322
        host = f"https://[{host}]" if host.count(":") > 1 and "[" not in host else f"https://{host}"
323
    url = urlsplit(host)
324
    if not url.hostname or (url.scheme != "https" and not (url.scheme == "http" and auth.get("allow_http"))):
325
        raise ValueError(f"host must be an address or an https:// URL (http:// needs allow_http on the resource): {auth['host']}")
326
    # ca_certificate: the PEM of a private CA, trusted instead of the system's CAs.
327
    context = ssl.create_default_context(cadata=(auth.get("ca_certificate") or "").strip() or None)
328
    if auth.get("verify_tls") is False:
329
        context.check_hostname = False
330
        context.verify_mode = ssl.CERT_NONE
331
    return pyeapi.connect(
332
        transport=url.scheme,
333
        host=url.hostname,
334
        port=url.port or auth.get("port") or None,
335
        username=auth["username"],
336
        password=auth["password"],
337
        context=context,
338
        timeout=timeout,
339
        return_node=True,
340
    )
341