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