1 | # py312 |
2 | # requirements: |
3 | # pyeapi==1.0.4 |
4 |
|
5 | import contextlib |
6 | import re |
7 | import secrets |
8 | import ssl |
9 | import time |
10 | from typing import Literal, TypedDict |
11 | from urllib.parse import urlsplit |
12 |
|
13 | import pyeapi |
14 |
|
15 |
|
16 | class arista_eos(TypedDict): |
17 | host: str |
18 | username: str |
19 | password: str |
20 | port: int |
21 | verify_tls: bool |
22 | allow_http: bool |
23 |
|
24 |
|
25 | # Commands that leave the session or act on the switch at once (exec commands run inside a session too), matched as |
26 | # EOS abbreviations ("wr" is write), also after no/default. Each is its first words; "*" is any one word. A denylist: |
27 | # an exec command not in it still runs. pyeapi sends "<cmd> MULTILINE: <text>" as cmd + input. |
28 | EXEC_COMMANDS = [c.split() for c in ( |
29 | "abort", "bash", "boot", "clear", "commit", "configure", "copy", "delete", "do", "end", "install", "ping", "reload", |
30 | "rename", "reset", "send", "ssh", "telnet", "traceroute", "write", "zerotouch", "agent * terminate", "clock set", |
31 | "redundancy force-switchover", |
32 | )] |
33 |
|
34 |
|
35 | def main( |
36 | auth: arista_eos, |
37 | lines: list[str], |
38 | mode: Literal["diff", "commit", "commit_timer"] = "diff", |
39 | session_name: str = "", |
40 | timer_minutes: int = 10, |
41 | ): |
42 | """ |
43 | Push Config |
44 | 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. |
45 | """ |
46 | if session_name and not re.fullmatch(r"[A-Za-z0-9_.-]+", session_name): |
47 | raise ValueError(f"session_name may only contain letters, digits, _ . -: {session_name!r}") |
48 | timer_minutes = 10 if timer_minutes is None else timer_minutes |
49 | if mode == "commit_timer" and not (isinstance(timer_minutes, int) and 1 <= timer_minutes <= 5999): |
50 | raise ValueError(f"timer_minutes must be 1 to 5999 (EOS takes up to 99:59:00): {timer_minutes!r}") |
51 | for line in lines: |
52 | cmd = line.split("MULTILINE:")[0] |
53 | words = cmd.lower().split() |
54 | if words[:1] in (["no"], ["default"]): |
55 | words = words[1:] |
56 | if "\n" in cmd or "\r" in cmd or any( |
57 | len(words) >= len(c) and all(w == "*" or w.startswith(t) for w, t in zip(c, words)) for c in EXEC_COMMANDS |
58 | ): |
59 | raise ValueError(f"lines may only hold configuration commands, not {line!r}") |
60 | session = session_name or f"windmill-{int(time.time() * 1000)}-{secrets.token_hex(3)}" |
61 | eos = node(auth) |
62 | # A session survives across eAPI calls by name, and reopening a pending one adds to it: refuse a live name. |
63 | [sessions] = eos.run_commands(["show configuration sessions detail"]) |
64 | if sessions.get("sessions", {}).get(session, {}).get("state") == "pending" or sessions.get("commitTimerSessionName") == session: |
65 | raise ValueError(f"config session {session} is already pending: commit or abort it, or pick another name") |
66 | # Stage the lines, read the diff, then commit or abort. A failure leaves a pending session (EOS allows 5): abort it. |
67 | try: |
68 | eos.run_commands([f"configure session {session}", *lines, "end"]) |
69 | [diff] = eos.run_commands([f"show session-config named {session} diffs"], "text") |
70 | if mode == "commit": |
71 | eos.run_commands([f"configure session {session} commit"]) |
72 | elif mode == "commit_timer": |
73 | eos.run_commands( |
74 | [f"configure session {session} commit timer {timer_minutes // 60:02d}:{timer_minutes % 60:02d}:00"], |
75 | ) |
76 | else: |
77 | eos.run_commands([f"configure session {session} abort"]) |
78 | except Exception: |
79 | with contextlib.suppress(Exception): |
80 | eos.run_commands([f"configure session {session} abort"]) |
81 | raise |
82 | return { |
83 | "session": session, |
84 | "mode": mode or "diff", |
85 | "diff": diff["output"], |
86 | "committed": mode in ("commit", "commit_timer"), |
87 | } |
88 |
|
89 |
|
90 | # host is an address or a URL (https: |
91 | # resource ticks allow_http (Basic auth then crosses the network in cleartext). pyeapi skips certificate checks unless it |
92 | # is given a context, so one is always passed: verifying, or not when the resource unticks verify_tls (EOS ships a |
93 | # self-signed cert). |
94 | def node(auth: arista_eos, timeout: float = 60): |
95 | host = auth["host"] |
96 | if "://" not in host: |
97 | host = f"https://[{host}]" if host.count(":") > 1 and "[" not in host else f"https://{host}" |
98 | url = urlsplit(host) |
99 | if not url.hostname or (url.scheme != "https" and not (url.scheme == "http" and auth.get("allow_http"))): |
100 | raise ValueError(f"host must be an address or an https:// URL (http:// needs allow_http on the resource): {auth['host']}") |
101 | context = ssl.create_default_context() |
102 | if auth.get("verify_tls") is False: |
103 | context.check_hostname = False |
104 | context.verify_mode = ssl.CERT_NONE |
105 | return pyeapi.connect( |
106 | transport=url.scheme, |
107 | host=url.hostname, |
108 | port=url.port or auth.get("port") or None, |
109 | username=auth["username"], |
110 | password=auth["password"], |
111 | context=context, |
112 | timeout=timeout, |
113 | return_node=True, |
114 | ) |
115 |
|