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