0

Run Commands

Published 20 days ago

Run EOS CLI commands over eAPI (runCmds) and return one result per command. Commands run in privileged mode; config commands need a leading "configure". JSON needs commands with a JSON model (most show commands); use text for the rest.

Script arista_eos Verified

The script

Submitted by hugo989 Python3
Verified 4 days ago
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 Literal, 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(
31
    auth: arista_eos, commands: list[str], host: str = "", format: Literal["json", "text"] = "json"
32
):
33
    """
34
    Run Commands
35
    Run EOS CLI commands over eAPI (runCmds) and return one result per command. Commands run in privileged mode; config commands need a leading "configure". JSON needs commands with a JSON model (most show commands); use text for the rest.
36
    """
37
    auth = with_host(auth, host)
38
    return node(auth).run_commands(commands, format or "json")
39

40

41
# One resource can serve every switch that shares a login: the host input, when set, overrides the resource's host.
42
def with_host(auth: arista_eos, host: str):
43
    host = (host or "").strip() or (auth.get("host") or "").strip()
44
    if not host:
45
        raise ValueError("host is required: set it on the resource or pass host")
46
    return {**auth, "host": host}
47

48

49
# SSH transport (transport: ssh): the EOS CLI over an SSH shell, behind the part of pyeapi's Node the scripts use
50
# (run_commands, connection.socket_error, connection.transport.connect), raising pyeapi's own CommandError and
51
# ConnectionError, so the checks and the error mapping are the same for both transports. Show commands in json get
52
# "| json", which prints the eAPI JSON; other commands give { messages: [output] } like eAPI, or {} when silent.
53
# A line starting with "% " is an error, raised as eAPI's CommandError. The host key is checked when the resource
54
# has ssh_host_key (SHA256:... as ssh-keygen -lf prints it).
55
class Ssh:
56
    def __init__(self, auth: arista_eos, timeout: float):
57
        self.auth, self.timeout = auth, timeout
58
        self.connection = self.transport = self
59
        self.socket_error = self.sock = self.chan = None
60

61
    # The TCP connection only, like eAPI's transport.connect(): if it fails, nothing was sent.
62
    def connect(self):
63
        self.sock = socket.create_connection(ssh_addr(self.auth), self.timeout)
64

65
    def lost(self, e):
66
        self.socket_error = e
67
        return pyeapi.eapilib.ConnectionError("ssh", f"SSH connection failed ({e})")
68

69
    def open(self):
70
        auth = self.auth
71
        try:
72
            if not self.sock:
73
                self.connect()
74
            t = paramiko.Transport(self.sock)
75
            t.start_client(timeout=self.timeout)
76
            key = t.get_remote_server_key()
77
        except (OSError, EOFError, paramiko.SSHException) as e:
78
            raise self.lost(e)
79
        fp = "SHA256:" + base64.b64encode(hashlib.sha256(key.asbytes()).digest()).decode().rstrip("=")
80
        if auth.get("ssh_host_key") and auth["ssh_host_key"].strip() != fp:
81
            t.close()
82
            raise RuntimeError(f"{auth['host']}: the SSH host key is {fp}, not the resource's ssh_host_key")
83
        try:
84
            try:
85
                t.auth_password(auth["username"], auth["password"])
86
            except paramiko.BadAuthenticationType:
87
                t.auth_interactive(
88
                    auth["username"], lambda _t, _i, prompts: [auth["password"]] * len(prompts)
89
                )
90
        except paramiko.AuthenticationException as e:
91
            t.close()
92
            raise pyeapi.eapilib.ConnectionError("ssh", str(e))
93
        except (OSError, EOFError, paramiko.SSHException) as e:
94
            raise self.lost(e)
95
        try:
96
            self.chan = t.open_session()
97
            self.chan.get_pty(width=4000)
98
            self.chan.invoke_shell()
99
            self.prompt = None
100
            out = self.read()
101
            self.prompt = re.escape(re.split(r"[(>#]", out.splitlines()[-1].strip())[0])
102
            if out.rstrip().endswith(">"):
103
                self.cli("enable")
104
            self.cli("terminal length 0")
105
            self.cli("terminal width 32767")
106
        except (OSError, EOFError, paramiko.SSHException) as e:
107
            raise self.lost(e)
108

109
    # Reads until the prompt. Questions eAPI never asks are answered as eAPI behaves: confirm, don't save.
110
    def read(self):
111
        buf, end = "", time.monotonic() + self.timeout
112
        prompt = (self.prompt or r"[\w.\-]+") + r"(\([^)\r\n]*\))?[>#] ?$"
113
        while True:
114
            self.chan.settimeout(max(end - time.monotonic(), 0.01))
115
            chunk = self.chan.recv(65536)
116
            if not chunk:
117
                raise self.lost("connection closed")
118
            buf += chunk.decode(errors="replace")
119
            tail = buf[-300:]
120
            if re.search(r"(^|\n)" + prompt, tail):
121
                return buf
122
            for question, answer in (
123
                # enable asks for a password on switches that land the user unprivileged: the login password.
124
                (r"(^|\n)Password:\s*$", self.auth["password"]),
125
                (r"\[confirm\]\s*$", ""),
126
                (r"Save\?.*\[yes/no[^\]]*\]:?\s*$", "no"),
127
                (r"\[(y|yes)/(n|no)\][:?]?\s*$", "y"),
128
            ):
129
                if re.search(question, tail, re.I):
130
                    self.chan.send(answer + "\r")
131
                    buf += "\n"
132

133
    # One command: its output without the echoed command and the prompt; progress lines keep their last state.
134
    def cli(self, cmd):
135
        try:
136
            self.chan.send(cmd + "\r")
137
            out = self.read()
138
        except (OSError, EOFError, paramiko.SSHException) as e:
139
            raise self.lost(e)
140
        self.mode = out.rstrip().splitlines()[-1]
141
        lines = [l.rstrip("\r").split("\r")[-1] for l in out.split("\n")]
142
        return "\n".join(lines[1:-1]).strip("\n")
143

144
    def run_commands(self, cmds, encoding="json", **_):
145
        try:
146
            if not self.chan:
147
                self.open()
148
            if "(config" in self.mode:
149
                self.cli("end")
150
            results = []
151
            for i, c in enumerate(cmds):
152
                # eAPI's { cmd, revision } form is the CLI's "| json revision N".
153
                cmd, rev = (c["cmd"], c.get("revision")) if isinstance(c, dict) else (c, None)
154
                show = encoding == "json" and (rev or re.match(r"\s*sh(ow)?\s", cmd)) and not re.search(r"\|\s*json", cmd)
155
                # pyeapi sends "<cmd> MULTILINE: <text>" (banners) as cmd + input; the CLI reads the text up to EOF.
156
                head, multi, text = cmd.partition("MULTILINE:")
157
                # The shell would run what follows a line break as another command; eAPI refuses it too.
158
                if re.search(r"[\r\n]", head):
159
                    raise ValueError(f"a command may not contain a line break: {head!r}")
160
                line = "\r".join([head.strip(), *text.strip().splitlines(), "EOF"]) if multi else cmd
161
                out = self.cli(f"{cmd} | json{f' revision {rev}' if rev else ''}" if show else line)
162
                errors = [l[2:] for l in out.splitlines() if l.startswith("% ")]
163
                code, kind = 1002, "invalid command"
164
                if show and not errors:
165
                    code, kind = 1000, "could not run command"
166
                    try:
167
                        result = json.loads(out)
168
                    except ValueError:
169
                        errors = [out[:200]]
170
                    else:
171
                        errors = result.get("errors") or []
172
                if errors:
173
                    raise pyeapi.eapilib.CommandError(
174
                        code,
175
                        f"CLI command {i + 2} of {len(cmds) + 1} '{cmd}' failed: {kind}",
176
                        command_error="; ".join(errors),
177
                        commands=cmds,
178
                        output=results,
179
                    )
180
                if encoding != "json":
181
                    result = {"output": out + "\n" if out else ""}
182
                elif not show:
183
                    # The CLI prints eAPI's warnings as "! " notices.
184
                    notices = [l[2:].strip() for l in out.splitlines() if l.startswith("! ")]
185
                    out = "\n".join(l for l in out.splitlines() if not l.startswith("! ")).strip()
186
                    result = {"messages": [out]} if out and not multi else {}
187
                    if notices:
188
                        result["warnings"] = notices
189
                results.append(result)
190
            return results
191
        except pyeapi.eapilib.ConnectionError:
192
            if self.chan:
193
                self.chan.close()
194
            self.sock = self.chan = None
195
            raise
196

197

198
# paramiko logs a traceback when a rebooting switch drops the session.
199
logging.getLogger("paramiko").addHandler(logging.NullHandler())
200

201

202
# host, or host:port ([v6]:port), else port, else 22.
203
def ssh_addr(auth: arista_eos):
204
    h = auth["host"]
205
    if "://" in h:
206
        raise ValueError(f"with transport ssh, host is an address or a hostname (with :port), not a URL: {h}")
207
    url = urlsplit(f"ssh://{h}" if h.count(":") <= 1 or h.startswith("[") else f"ssh://[{h}]")
208
    return url.hostname, url.port or int(auth.get("port") or 22)
209

210

211
# Every action raises DeviceUnreachable when the switch can't be reached and AuthFailure when it refuses the
212
# credential, so a flow can retry on result.error.name. Command errors stay pyeapi's CommandError.
213
def node(auth: arista_eos, timeout: float = 60):
214
    eos = open_node(auth, timeout)
215
    run = eos.run_commands
216

217
    def run_commands(*args, **kwargs):
218
        try:
219
            return run(*args, **kwargs)
220
        except pyeapi.eapilib.ConnectionError as e:
221
            raise connection_error(auth, eos, e)
222

223
    eos.run_commands = run_commands
224
    return eos
225

226

227
# pyeapi 1.0.4 raises ConnectionError for a socket error (kept in socket_error), an answer that isn't JSON (eAPI
228
# still starting, 5xx) and a 401, the only one with neither.
229
def connection_error(auth, eos, e):
230
    # A certificate the resource does not trust is a setting to fix (verify_tls, ca_certificate), not worth a retry.
231
    if isinstance(eos.connection.socket_error, ssl.SSLCertVerificationError):
232
        return RuntimeError(f"{auth['host']}: {eos.connection.socket_error}")
233
    if eos.connection.socket_error is None and e.message != "unable to connect to eAPI":
234
        return AuthFailure(f"{auth['host']}: {'SSH' if auth.get('transport') == 'ssh' else 'eAPI'} refused the credential ({e.message})")
235
    return DeviceUnreachable(f"{auth['host']}: {e.message}")
236

237

238
class DeviceUnreachable(Exception):
239
    pass
240

241

242
class AuthFailure(Exception):
243
    pass
244

245

246
# pyeapi logs a traceback for every socket error.
247
logging.getLogger("pyeapi").addHandler(logging.NullHandler())
248

249

250
# 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
251
# resource ticks allow_http (Basic auth then crosses the network in cleartext). pyeapi skips certificate checks unless it
252
# is given a context, so one is always passed: verifying, or not when the resource unticks verify_tls (EOS ships a
253
# self-signed cert).
254
def open_node(auth: arista_eos, timeout: float = 60):
255
    if auth.get("transport") == "ssh":
256
        return Ssh(auth, timeout)
257
    host = auth["host"]
258
    if "://" not in host:
259
        host = f"https://[{host}]" if host.count(":") > 1 and "[" not in host else f"https://{host}"
260
    url = urlsplit(host)
261
    if not url.hostname or (url.scheme != "https" and not (url.scheme == "http" and auth.get("allow_http"))):
262
        raise ValueError(f"host must be an address or an https:// URL (http:// needs allow_http on the resource): {auth['host']}")
263
    # ca_certificate: the PEM of a private CA, trusted instead of the system's CAs.
264
    context = ssl.create_default_context(cadata=(auth.get("ca_certificate") or "").strip() or None)
265
    if auth.get("verify_tls") is False:
266
        context.check_hostname = False
267
        context.verify_mode = ssl.CERT_NONE
268
    return pyeapi.connect(
269
        transport=url.scheme,
270
        host=url.hostname,
271
        port=url.port or auth.get("port") or None,
272
        username=auth["username"],
273
        password=auth["password"],
274
        context=context,
275
        timeout=timeout,
276
        return_node=True,
277
    )
278