0

Get Interface Counters

Published today

Traffic and error counters of every interface, or of one (show interfaces): returns { <interface>: { counters: { inOctets, outOctets, in/out Ucast/Multicast/BroadcastPkts, inDiscards, outDiscards, totalInErrors, totalOutErrors, inputErrorsDetail, outputErrorsDetail, linkStatusChanges, ... }, rates: { inBitsRate, outBitsRate, inPktsRate, outPktsRate, updateInterval } } }. Counters count since boot or the last clear; interfaces without counters (Vlan, Loopback) are left out.

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 = "", interface: str = ""):
31
    """
32
    Get Interface Counters
33
    Traffic and error counters of every interface, or of one (show interfaces): returns { <interface>: { counters: { inOctets, outOctets, in/out Ucast/Multicast/BroadcastPkts, inDiscards, outDiscards, totalInErrors, totalOutErrors, inputErrorsDetail, outputErrorsDetail, linkStatusChanges, ... }, rates: { inBitsRate, outBitsRate, inPktsRate, outPktsRate, updateInterval } } }. Counters count since boot or the last clear; interfaces without counters (Vlan, Loopback) are left out.
34
    """
35
    auth = with_host(auth, host)
36
    cmd = f"show interfaces {arg('interface', interface)}" if interface else "show interfaces"
37
    [result] = node(auth).run_commands([cmd])
38
    return {
39
        name: {"counters": i["interfaceCounters"], "rates": i.get("interfaceStatistics") or {}}
40
        for name, i in sorted(result["interfaces"].items())
41
        if i.get("interfaceCounters")
42
    }
43

44

45
# A value that goes into a CLI command: one word of A-Z a-z 0-9 and _ . : / -.
46
def arg(name, value):
47
    value = str(value).strip()
48
    if not re.fullmatch(r"[\w.:/-]+", value):
49
        raise ValueError(f"{name} must be one word of A-Z a-z 0-9 _ . : / -: got {value!r}")
50
    return value
51

52

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

60

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

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

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

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

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

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

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

209

210
# paramiko logs a traceback when a rebooting switch drops the session.
211
logging.getLogger("paramiko").addHandler(logging.NullHandler())
212

213

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

222

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

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

235
    eos.run_commands = run_commands
236
    return eos
237

238

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

249

250
class DeviceUnreachable(Exception):
251
    pass
252

253

254
class AuthFailure(Exception):
255
    pass
256

257

258
# pyeapi logs a traceback for every socket error.
259
logging.getLogger("pyeapi").addHandler(logging.NullHandler())
260

261

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