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