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