0

Ping

Published today

Ping a destination from the switch (ping vrf <vrf> <destination> repeat <count>), optionally from a source interface or address and with a packet size: returns { destination, transmitted, received, loss_percent, rtt_min_ms, rtt_avg_ms, rtt_max_ms, output }; no reply is a result (received 0), not an error.

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(
31
    auth: arista_eos,
32
    destination: str,
33
    host: str = "",
34
    vrf: str = "default",
35
    count: int = 5,
36
    source: str = "",
37
    size: int = 0,
38
):
39
    """
40
    Ping
41
    Ping a destination from the switch (ping vrf <vrf> <destination> repeat <count>), optionally from a source interface or address and with a packet size: returns { destination, transmitted, received, loss_percent, rtt_min_ms, rtt_avg_ms, rtt_max_ms, output }; no reply is a result (received 0), not an error.
42
    """
43
    auth = with_host(auth, host)
44
    count = 5 if count is None else count
45
    if not (isinstance(count, int) and 1 <= count <= 1000):
46
        raise ValueError(f"count must be 1 to 1000: {count!r}")
47
    cmd = f"ping vrf {arg('vrf', vrf or 'default')} {arg('destination', destination)} repeat {count}"
48
    if source:
49
        cmd += f" source {arg('source', source)}"
50
    if size:
51
        cmd += f" size {int(size)}"
52
    # About one second per packet, plus the time a dead destination takes to give up.
53
    [result] = node(auth, timeout=count * 2 + 30).run_commands([cmd])
54
    out = "".join(result.get("messages") or [])
55
    stats = re.search(r"(\d+) packets transmitted, (\d+) (?:packets )?received", out)
56
    if not stats:
57
        raise RuntimeError(f"ping printed no statistics: {out.strip()[-300:]}")
58
    rtt = re.search(r"= ([\d.]+)/([\d.]+)/([\d.]+)", out)
59
    sent, got = int(stats[1]), int(stats[2])
60
    return {
61
        "destination": destination,
62
        "transmitted": sent,
63
        "received": got,
64
        "loss_percent": round(100 * (sent - got) / sent, 1) if sent else 100.0,
65
        "rtt_min_ms": float(rtt[1]) if rtt else None,
66
        "rtt_avg_ms": float(rtt[2]) if rtt else None,
67
        "rtt_max_ms": float(rtt[3]) if rtt else None,
68
        "output": out,
69
    }
70

71

72
# A value that goes into a CLI command: one word of A-Z a-z 0-9 and _ . : / -.
73
def arg(name, value):
74
    value = str(value).strip()
75
    if not re.fullmatch(r"[\w.:/-]+", value):
76
        raise ValueError(f"{name} must be one word of A-Z a-z 0-9 _ . : / -: got {value!r}")
77
    return value
78

79

80
# One resource can serve every switch that shares a login: the host input, when set, overrides the resource's host.
81
def with_host(auth: arista_eos, host: str):
82
    host = (host or "").strip() or (auth.get("host") or "").strip()
83
    if not host:
84
        raise ValueError("host is required: set it on the resource or pass host")
85
    return {**auth, "host": host}
86

87

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

100
    # The TCP connection only, like eAPI's transport.connect(): if it fails, nothing was sent.
101
    def connect(self):
102
        self.sock = socket.create_connection(ssh_addr(self.auth), self.timeout)
103

104
    def lost(self, e):
105
        self.socket_error = e
106
        return pyeapi.eapilib.ConnectionError("ssh", f"SSH connection failed ({e})")
107

108
    def open(self):
109
        auth = self.auth
110
        try:
111
            if not self.sock:
112
                self.connect()
113
            t = paramiko.Transport(self.sock)
114
            t.start_client(timeout=self.timeout)
115
            key = t.get_remote_server_key()
116
        except (OSError, EOFError, paramiko.SSHException) as e:
117
            raise self.lost(e)
118
        fp = "SHA256:" + base64.b64encode(hashlib.sha256(key.asbytes()).digest()).decode().rstrip("=")
119
        if auth.get("ssh_host_key") and auth["ssh_host_key"].strip() != fp:
120
            t.close()
121
            raise RuntimeError(f"{auth['host']}: the SSH host key is {fp}, not the resource's ssh_host_key")
122
        try:
123
            try:
124
                t.auth_password(auth["username"], auth["password"])
125
            except paramiko.BadAuthenticationType:
126
                t.auth_interactive(
127
                    auth["username"], lambda _t, _i, prompts: [auth["password"]] * len(prompts)
128
                )
129
        except paramiko.AuthenticationException as e:
130
            t.close()
131
            raise pyeapi.eapilib.ConnectionError("ssh", str(e))
132
        except (OSError, EOFError, paramiko.SSHException) as e:
133
            raise self.lost(e)
134
        try:
135
            self.chan = t.open_session()
136
            self.chan.get_pty(width=4000)
137
            self.chan.invoke_shell()
138
            self.prompt = None
139
            out = self.read()
140
            self.prompt = re.escape(re.split(r"[(>#]", out.splitlines()[-1].strip())[0])
141
            if out.rstrip().endswith(">"):
142
                self.cli("enable")
143
            self.cli("terminal length 0")
144
            self.cli("terminal width 32767")
145
        except (OSError, EOFError, paramiko.SSHException) as e:
146
            raise self.lost(e)
147

148
    # Reads until the prompt. Questions eAPI never asks are answered as eAPI behaves: confirm, don't save.
149
    def read(self):
150
        buf, end = "", time.monotonic() + self.timeout
151
        prompt = (self.prompt or r"[\w.\-]+") + r"(\([^)\r\n]*\))?[>#] ?$"
152
        while True:
153
            self.chan.settimeout(max(end - time.monotonic(), 0.01))
154
            chunk = self.chan.recv(65536)
155
            if not chunk:
156
                raise self.lost("connection closed")
157
            buf += chunk.decode(errors="replace")
158
            tail = buf[-300:]
159
            if re.search(r"(^|\n)" + prompt, tail):
160
                return buf
161
            for question, answer in (
162
                # enable asks for a password on switches that land the user unprivileged: the login password.
163
                (r"(^|\n)Password:\s*$", self.auth["password"]),
164
                (r"\[confirm\]\s*$", ""),
165
                (r"Save\?.*\[yes/no[^\]]*\]:?\s*$", "no"),
166
                (r"\[(y|yes)/(n|no)\][:?]?\s*$", "y"),
167
            ):
168
                if re.search(question, tail, re.I):
169
                    self.chan.send(answer + "\r")
170
                    buf += "\n"
171

172
    # One command: its output without the echoed command and the prompt; progress lines keep their last state.
173
    def cli(self, cmd):
174
        try:
175
            self.chan.send(cmd + "\r")
176
            out = self.read()
177
        except (OSError, EOFError, paramiko.SSHException) as e:
178
            raise self.lost(e)
179
        self.mode = out.rstrip().splitlines()[-1]
180
        lines = [l.rstrip("\r").split("\r")[-1] for l in out.split("\n")]
181
        return "\n".join(lines[1:-1]).strip("\n")
182

183
    def run_commands(self, cmds, encoding="json", **_):
184
        try:
185
            if not self.chan:
186
                self.open()
187
            if "(config" in self.mode:
188
                self.cli("end")
189
            results = []
190
            for i, c in enumerate(cmds):
191
                # eAPI's { cmd, revision } form is the CLI's "| json revision N".
192
                cmd, rev = (c["cmd"], c.get("revision")) if isinstance(c, dict) else (c, None)
193
                show = encoding == "json" and (rev or re.match(r"\s*sh(ow)?\s", cmd)) and not re.search(r"\|\s*json", cmd)
194
                # pyeapi sends "<cmd> MULTILINE: <text>" (banners) as cmd + input; the CLI reads the text up to EOF.
195
                head, multi, text = cmd.partition("MULTILINE:")
196
                # The shell would run what follows a line break as another command; eAPI refuses it too.
197
                if re.search(r"[\r\n]", head):
198
                    raise ValueError(f"a command may not contain a line break: {head!r}")
199
                line = "\r".join([head.strip(), *text.strip().splitlines(), "EOF"]) if multi else cmd
200
                out = self.cli(f"{cmd} | json{f' revision {rev}' if rev else ''}" if show else line)
201
                errors = [l[2:] for l in out.splitlines() if l.startswith("% ")]
202
                code, kind = 1002, "invalid command"
203
                if show and not errors:
204
                    code, kind = 1000, "could not run command"
205
                    try:
206
                        result = json.loads(out)
207
                    except ValueError:
208
                        errors = [out[:200]]
209
                    else:
210
                        errors = result.get("errors") or []
211
                if errors:
212
                    raise pyeapi.eapilib.CommandError(
213
                        code,
214
                        f"CLI command {i + 2} of {len(cmds) + 1} '{cmd}' failed: {kind}",
215
                        command_error="; ".join(errors),
216
                        commands=cmds,
217
                        output=results,
218
                    )
219
                if encoding != "json":
220
                    result = {"output": out + "\n" if out else ""}
221
                elif not show:
222
                    # The CLI prints eAPI's warnings as "! " notices.
223
                    notices = [l[2:].strip() for l in out.splitlines() if l.startswith("! ")]
224
                    out = "\n".join(l for l in out.splitlines() if not l.startswith("! ")).strip()
225
                    result = {"messages": [out]} if out and not multi else {}
226
                    if notices:
227
                        result["warnings"] = notices
228
                results.append(result)
229
            return results
230
        except pyeapi.eapilib.ConnectionError:
231
            if self.chan:
232
                self.chan.close()
233
            self.sock = self.chan = None
234
            raise
235

236

237
# paramiko logs a traceback when a rebooting switch drops the session.
238
logging.getLogger("paramiko").addHandler(logging.NullHandler())
239

240

241
# host, or host:port ([v6]:port), else port, else 22.
242
def ssh_addr(auth: arista_eos):
243
    h = auth["host"]
244
    if "://" in h:
245
        raise ValueError(f"with transport ssh, host is an address or a hostname (with :port), not a URL: {h}")
246
    url = urlsplit(f"ssh://{h}" if h.count(":") <= 1 or h.startswith("[") else f"ssh://[{h}]")
247
    return url.hostname, url.port or int(auth.get("port") or 22)
248

249

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

256
    def run_commands(*args, **kwargs):
257
        try:
258
            return run(*args, **kwargs)
259
        except pyeapi.eapilib.ConnectionError as e:
260
            raise connection_error(auth, eos, e)
261

262
    eos.run_commands = run_commands
263
    return eos
264

265

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

276

277
class DeviceUnreachable(Exception):
278
    pass
279

280

281
class AuthFailure(Exception):
282
    pass
283

284

285
# pyeapi logs a traceback for every socket error.
286
logging.getLogger("pyeapi").addHandler(logging.NullHandler())
287

288

289
# 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
290
# resource ticks allow_http (Basic auth then crosses the network in cleartext). pyeapi skips certificate checks unless it
291
# is given a context, so one is always passed: verifying, or not when the resource unticks verify_tls (EOS ships a
292
# self-signed cert).
293
def open_node(auth: arista_eos, timeout: float = 60):
294
    if auth.get("transport") == "ssh":
295
        return Ssh(auth, timeout)
296
    host = auth["host"]
297
    if "://" not in host:
298
        host = f"https://[{host}]" if host.count(":") > 1 and "[" not in host else f"https://{host}"
299
    url = urlsplit(host)
300
    if not url.hostname or (url.scheme != "https" and not (url.scheme == "http" and auth.get("allow_http"))):
301
        raise ValueError(f"host must be an address or an https:// URL (http:// needs allow_http on the resource): {auth['host']}")
302
    # ca_certificate: the PEM of a private CA, trusted instead of the system's CAs.
303
    context = ssl.create_default_context(cadata=(auth.get("ca_certificate") or "").strip() or None)
304
    if auth.get("verify_tls") is False:
305
        context.check_hostname = False
306
        context.verify_mode = ssl.CERT_NONE
307
    return pyeapi.connect(
308
        transport=url.scheme,
309
        host=url.hostname,
310
        port=url.port or auth.get("port") or None,
311
        username=auth["username"],
312
        password=auth["password"],
313
        context=context,
314
        timeout=timeout,
315
        return_node=True,
316
    )
317