1 | # py312 |
2 | # requirements: |
3 | # paramiko==5.1.0 |
4 | # pyeapi==1.0.4 |
5 |
|
6 | import base64 |
7 | import hashlib |
8 | import json |
9 | import logging |
10 | import re |
11 | import socket |
12 | import ssl |
13 | import time |
14 | from typing import TypedDict |
15 | from urllib.parse import urlsplit |
16 |
|
17 | import paramiko |
18 | import pyeapi |
19 |
|
20 |
|
21 | class arista_eos(TypedDict): |
22 | host: str |
23 | username: str |
24 | password: str |
25 | port: int |
26 | verify_tls: bool |
27 | allow_http: bool |
28 |
|
29 |
|
30 | def main(auth: arista_eos, host: str = ""): |
31 | """ |
32 | Save Config |
33 | Save the running configuration to startup-config (write memory). Refuses while a config session is pending under a commit timer, so a change about to roll back isn't saved: run Confirm Commit (which saves) or Abort Config Session first. |
34 | """ |
35 | auth = with_host(auth, host) |
36 | eos = node(auth) |
37 | [sessions] = eos.run_commands(["show configuration sessions detail"]) |
38 | if sessions.get("commitTimerSessionName"): |
39 | raise ValueError(f"config session {sessions['commitTimerSessionName']} is pending under a commit timer: confirm or abort it first") |
40 | [result] = eos.run_commands(["write memory"]) |
41 | return {"saved": True, **result} |
42 |
|
43 |
|
44 | # One resource can serve every switch that shares a login: the host input, when set, overrides the resource's host. |
45 | def with_host(auth: arista_eos, host: str): |
46 | host = (host or "").strip() or (auth.get("host") or "").strip() |
47 | if not host: |
48 | raise ValueError("host is required: set it on the resource or pass host") |
49 | return {**auth, "host": host} |
50 |
|
51 |
|
52 | # SSH transport (transport: ssh): the EOS CLI over an SSH shell, behind the part of pyeapi's Node the scripts use |
53 | # (run_commands, connection.socket_error, connection.transport.connect), raising pyeapi's own CommandError and |
54 | # ConnectionError, so the checks and the error mapping are the same for both transports. Show commands in json get |
55 | # "| json", which prints the eAPI JSON; other commands give { messages: [output] } like eAPI, or {} when silent. |
56 | # A line starting with "% " is an error, raised as eAPI's CommandError. The host key is checked when the resource |
57 | # has ssh_host_key (SHA256:... as ssh-keygen -lf prints it). |
58 | class Ssh: |
59 | def __init__(self, auth: arista_eos, timeout: float): |
60 | self.auth, self.timeout = auth, timeout |
61 | self.connection = self.transport = self |
62 | self.socket_error = self.sock = self.chan = None |
63 |
|
64 | # The TCP connection only, like eAPI's transport.connect(): if it fails, nothing was sent. |
65 | def connect(self): |
66 | self.sock = socket.create_connection(ssh_addr(self.auth), self.timeout) |
67 |
|
68 | def lost(self, e): |
69 | self.socket_error = e |
70 | return pyeapi.eapilib.ConnectionError("ssh", f"SSH connection failed ({e})") |
71 |
|
72 | def open(self): |
73 | auth = self.auth |
74 | try: |
75 | if not self.sock: |
76 | self.connect() |
77 | t = paramiko.Transport(self.sock) |
78 | t.start_client(timeout=self.timeout) |
79 | key = t.get_remote_server_key() |
80 | except (OSError, EOFError, paramiko.SSHException) as e: |
81 | raise self.lost(e) |
82 | fp = "SHA256:" + base64.b64encode(hashlib.sha256(key.asbytes()).digest()).decode().rstrip("=") |
83 | if auth.get("ssh_host_key") and auth["ssh_host_key"].strip() != fp: |
84 | t.close() |
85 | raise RuntimeError(f"{auth['host']}: the SSH host key is {fp}, not the resource's ssh_host_key") |
86 | try: |
87 | try: |
88 | t.auth_password(auth["username"], auth["password"]) |
89 | except paramiko.BadAuthenticationType: |
90 | t.auth_interactive( |
91 | auth["username"], lambda _t, _i, prompts: [auth["password"]] * len(prompts) |
92 | ) |
93 | except paramiko.AuthenticationException as e: |
94 | t.close() |
95 | raise pyeapi.eapilib.ConnectionError("ssh", str(e)) |
96 | except (OSError, EOFError, paramiko.SSHException) as e: |
97 | raise self.lost(e) |
98 | try: |
99 | self.chan = t.open_session() |
100 | self.chan.get_pty(width=4000) |
101 | self.chan.invoke_shell() |
102 | self.prompt = None |
103 | out = self.read() |
104 | self.prompt = re.escape(re.split(r"[(>#]", out.splitlines()[-1].strip())[0]) |
105 | if out.rstrip().endswith(">"): |
106 | self.cli("enable") |
107 | self.cli("terminal length 0") |
108 | self.cli("terminal width 32767") |
109 | except (OSError, EOFError, paramiko.SSHException) as e: |
110 | raise self.lost(e) |
111 |
|
112 | # Reads until the prompt. Questions eAPI never asks are answered as eAPI behaves: confirm, don't save. |
113 | def read(self): |
114 | buf, end = "", time.monotonic() + self.timeout |
115 | prompt = (self.prompt or r"[\w.\-]+") + r"(\([^)\r\n]*\))?[>#] ?$" |
116 | while True: |
117 | self.chan.settimeout(max(end - time.monotonic(), 0.01)) |
118 | chunk = self.chan.recv(65536) |
119 | if not chunk: |
120 | raise self.lost("connection closed") |
121 | buf += chunk.decode(errors="replace") |
122 | tail = buf[-300:] |
123 | if re.search(r"(^|\n)" + prompt, tail): |
124 | return buf |
125 | for question, answer in ( |
126 | # enable asks for a password on switches that land the user unprivileged: the login password. |
127 | (r"(^|\n)Password:\s*$", self.auth["password"]), |
128 | (r"\[confirm\]\s*$", ""), |
129 | (r"Save\?.*\[yes/no[^\]]*\]:?\s*$", "no"), |
130 | (r"\[(y|yes)/(n|no)\][:?]?\s*$", "y"), |
131 | ): |
132 | if re.search(question, tail, re.I): |
133 | self.chan.send(answer + "\r") |
134 | buf += "\n" |
135 |
|
136 | # One command: its output without the echoed command and the prompt; progress lines keep their last state. |
137 | def cli(self, cmd): |
138 | try: |
139 | self.chan.send(cmd + "\r") |
140 | out = self.read() |
141 | except (OSError, EOFError, paramiko.SSHException) as e: |
142 | raise self.lost(e) |
143 | self.mode = out.rstrip().splitlines()[-1] |
144 | lines = [l.rstrip("\r").split("\r")[-1] for l in out.split("\n")] |
145 | return "\n".join(lines[1:-1]).strip("\n") |
146 |
|
147 | def run_commands(self, cmds, encoding="json", **_): |
148 | try: |
149 | if not self.chan: |
150 | self.open() |
151 | if "(config" in self.mode: |
152 | self.cli("end") |
153 | results = [] |
154 | for i, c in enumerate(cmds): |
155 | # eAPI's { cmd, revision } form is the CLI's "| json revision N". |
156 | cmd, rev = (c["cmd"], c.get("revision")) if isinstance(c, dict) else (c, None) |
157 | show = encoding == "json" and (rev or re.match(r"\s*sh(ow)?\s", cmd)) and not re.search(r"\|\s*json", cmd) |
158 | # pyeapi sends "<cmd> MULTILINE: <text>" (banners) as cmd + input; the CLI reads the text up to EOF. |
159 | head, multi, text = cmd.partition("MULTILINE:") |
160 | # The shell would run what follows a line break as another command; eAPI refuses it too. |
161 | if re.search(r"[\r\n]", head): |
162 | raise ValueError(f"a command may not contain a line break: {head!r}") |
163 | line = "\r".join([head.strip(), *text.strip().splitlines(), "EOF"]) if multi else cmd |
164 | out = self.cli(f"{cmd} | json{f' revision {rev}' if rev else ''}" if show else line) |
165 | errors = [l[2:] for l in out.splitlines() if l.startswith("% ")] |
166 | code, kind = 1002, "invalid command" |
167 | if show and not errors: |
168 | code, kind = 1000, "could not run command" |
169 | try: |
170 | result = json.loads(out) |
171 | except ValueError: |
172 | errors = [out[:200]] |
173 | else: |
174 | errors = result.get("errors") or [] |
175 | if errors: |
176 | raise pyeapi.eapilib.CommandError( |
177 | code, |
178 | f"CLI command {i + 2} of {len(cmds) + 1} '{cmd}' failed: {kind}", |
179 | command_error="; ".join(errors), |
180 | commands=cmds, |
181 | output=results, |
182 | ) |
183 | if encoding != "json": |
184 | result = {"output": out + "\n" if out else ""} |
185 | elif not show: |
186 | # The CLI prints eAPI's warnings as "! " notices. |
187 | notices = [l[2:].strip() for l in out.splitlines() if l.startswith("! ")] |
188 | out = "\n".join(l for l in out.splitlines() if not l.startswith("! ")).strip() |
189 | result = {"messages": [out]} if out and not multi else {} |
190 | if notices: |
191 | result["warnings"] = notices |
192 | results.append(result) |
193 | return results |
194 | except pyeapi.eapilib.ConnectionError: |
195 | if self.chan: |
196 | self.chan.close() |
197 | self.sock = self.chan = None |
198 | raise |
199 |
|
200 |
|
201 | # paramiko logs a traceback when a rebooting switch drops the session. |
202 | logging.getLogger("paramiko").addHandler(logging.NullHandler()) |
203 |
|
204 |
|
205 | # host, or host:port ([v6]:port), else port, else 22. |
206 | def ssh_addr(auth: arista_eos): |
207 | h = auth["host"] |
208 | if ": |
209 | raise ValueError(f"with transport ssh, host is an address or a hostname (with :port), not a URL: {h}") |
210 | url = urlsplit(f"ssh://{h}" if h.count(":") <= 1 or h.startswith("[") else f"ssh://[{h}]") |
211 | return url.hostname, url.port or int(auth.get("port") or 22) |
212 |
|
213 |
|
214 | # Every action raises DeviceUnreachable when the switch can't be reached and AuthFailure when it refuses the |
215 | # credential, so a flow can retry on result.error.name. Command errors stay pyeapi's CommandError. |
216 | def node(auth: arista_eos, timeout: float = 60): |
217 | eos = open_node(auth, timeout) |
218 | run = eos.run_commands |
219 |
|
220 | def run_commands(*args, **kwargs): |
221 | try: |
222 | return run(*args, **kwargs) |
223 | except pyeapi.eapilib.ConnectionError as e: |
224 | raise connection_error(auth, eos, e) |
225 |
|
226 | eos.run_commands = run_commands |
227 | return eos |
228 |
|
229 |
|
230 | # pyeapi 1.0.4 raises ConnectionError for a socket error (kept in socket_error), an answer that isn't JSON (eAPI |
231 | # still starting, 5xx) and a 401, the only one with neither. |
232 | def connection_error(auth, eos, e): |
233 | # A certificate the resource does not trust is a setting to fix (verify_tls, ca_certificate), not worth a retry. |
234 | if isinstance(eos.connection.socket_error, ssl.SSLCertVerificationError): |
235 | return RuntimeError(f"{auth['host']}: {eos.connection.socket_error}") |
236 | if eos.connection.socket_error is None and e.message != "unable to connect to eAPI": |
237 | return AuthFailure(f"{auth['host']}: {'SSH' if auth.get('transport') == 'ssh' else 'eAPI'} refused the credential ({e.message})") |
238 | return DeviceUnreachable(f"{auth['host']}: {e.message}") |
239 |
|
240 |
|
241 | class DeviceUnreachable(Exception): |
242 | pass |
243 |
|
244 |
|
245 | class AuthFailure(Exception): |
246 | pass |
247 |
|
248 |
|
249 | # pyeapi logs a traceback for every socket error. |
250 | logging.getLogger("pyeapi").addHandler(logging.NullHandler()) |
251 |
|
252 |
|
253 | # 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 |
254 | # resource ticks allow_http (Basic auth then crosses the network in cleartext). pyeapi skips certificate checks unless it |
255 | # is given a context, so one is always passed: verifying, or not when the resource unticks verify_tls (EOS ships a |
256 | # self-signed cert). |
257 | def open_node(auth: arista_eos, timeout: float = 60): |
258 | if auth.get("transport") == "ssh": |
259 | return Ssh(auth, timeout) |
260 | host = auth["host"] |
261 | if "://" not in host: |
262 | host = f"https://[{host}]" if host.count(":") > 1 and "[" not in host else f"https://{host}" |
263 | url = urlsplit(host) |
264 | if not url.hostname or (url.scheme != "https" and not (url.scheme == "http" and auth.get("allow_http"))): |
265 | raise ValueError(f"host must be an address or an https:// URL (http:// needs allow_http on the resource): {auth['host']}") |
266 | # ca_certificate: the PEM of a private CA, trusted instead of the system's CAs. |
267 | context = ssl.create_default_context(cadata=(auth.get("ca_certificate") or "").strip() or None) |
268 | if auth.get("verify_tls") is False: |
269 | context.check_hostname = False |
270 | context.verify_mode = ssl.CERT_NONE |
271 | return pyeapi.connect( |
272 | transport=url.scheme, |
273 | host=url.hostname, |
274 | port=url.port or auth.get("port") or None, |
275 | username=auth["username"], |
276 | password=auth["password"], |
277 | context=context, |
278 | timeout=timeout, |
279 | return_node=True, |
280 | ) |
281 |
|