0

Get Environment

Published today

Temperature sensors, fans, power supplies and memory of the switch (show system environment temperature, cooling and power; show version): returns { temperature, cooling, power, memory: { total_kb, free_kb }, unavailable }. A part the platform does not report (no power supplies on a virtual switch) is null and listed in unavailable.

Script arista_eos Verified

The script

Submitted by hugo989 Python3
Verified 1 day 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 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 Environment
33
    Temperature sensors, fans, power supplies and memory of the switch (show system environment temperature, cooling and power; show version): returns { temperature, cooling, power, memory: { total_kb, free_kb }, unavailable }. A part the platform does not report (no power supplies on a virtual switch) is null and listed in unavailable.
34
    """
35
    auth = with_host(auth, host)
36
    eos = node(auth)
37
    result, unavailable = {}, []
38
    for part in ("temperature", "cooling", "power"):
39
        try:
40
            [result[part]] = eos.run_commands([f"show system environment {part}"])
41
        except pyeapi.eapilib.CommandError as e:
42
            result[part] = None
43
            unavailable.append(f"{part}: {e.command_error or e.message}")
44
    [version] = eos.run_commands(["show version"])
45
    result["memory"] = {"total_kb": version.get("memTotal"), "free_kb": version.get("memFree")}
46
    result["unavailable"] = unavailable
47
    return result
48

49

50
# One resource can serve every switch that shares a login: the host input, when set, overrides the resource's host.
51
def with_host(auth: arista_eos, host: str):
52
    host = (host or "").strip() or (auth.get("host") or "").strip()
53
    if not host:
54
        raise ValueError("host is required: set it on the resource or pass host")
55
    return {**auth, "host": host}
56

57

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

70
    # The TCP connection only, like eAPI's transport.connect(): if it fails, nothing was sent.
71
    def connect(self):
72
        self.sock = socket.create_connection(ssh_addr(self.auth), self.timeout)
73

74
    def lost(self, e):
75
        self.socket_error = e
76
        return pyeapi.eapilib.ConnectionError("ssh", f"SSH connection failed ({e})")
77

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

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

142
    # One command: its output without the echoed command and the prompt; progress lines keep their last state.
143
    def cli(self, cmd):
144
        try:
145
            self.chan.send(cmd + "\r")
146
            out = self.read()
147
        except (OSError, EOFError, paramiko.SSHException) as e:
148
            raise self.lost(e)
149
        self.mode = out.rstrip().splitlines()[-1]
150
        lines = [l.rstrip("\r").split("\r")[-1] for l in out.split("\n")]
151
        return "\n".join(lines[1:-1]).strip("\n")
152

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

206

207
# paramiko logs a traceback when a rebooting switch drops the session.
208
logging.getLogger("paramiko").addHandler(logging.NullHandler())
209

210

211
# host, or host:port ([v6]:port), else port, else 22.
212
def ssh_addr(auth: arista_eos):
213
    h = auth["host"]
214
    if "://" in h:
215
        raise ValueError(f"with transport ssh, host is an address or a hostname (with :port), not a URL: {h}")
216
    url = urlsplit(f"ssh://{h}" if h.count(":") <= 1 or h.startswith("[") else f"ssh://[{h}]")
217
    return url.hostname, url.port or int(auth.get("port") or 22)
218

219

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

226
    def run_commands(*args, **kwargs):
227
        try:
228
            return run(*args, **kwargs)
229
        except pyeapi.eapilib.ConnectionError as e:
230
            raise connection_error(auth, eos, e)
231

232
    eos.run_commands = run_commands
233
    return eos
234

235

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

246

247
class DeviceUnreachable(Exception):
248
    pass
249

250

251
class AuthFailure(Exception):
252
    pass
253

254

255
# pyeapi logs a traceback for every socket error.
256
logging.getLogger("pyeapi").addHandler(logging.NullHandler())
257

258

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