0

Delete File

Published today

Delete a file at the root of the switch's flash, for example an old EOS image. path is flash:/NAME or NAME. Refuses the image boot-config points to. Returns { path, deleted } (deleted false when the file was not there).

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, path: str, host: str = ""):
31
    """
32
    Delete File
33
    Delete a file at the root of the switch's flash, for example an old EOS image. path is flash:/NAME or NAME. Refuses the image boot-config points to. Returns { path, deleted } (deleted false when the file was not there).
34
    """
35
    auth = with_host(auth, host)
36
    name = flash_name(path)
37
    eos = node(auth)
38
    [boot] = eos.run_commands(["show boot-config"])
39
    if boot.get("softwareImage") == f"flash:/{name}":
40
        raise ValueError(f"flash:/{name} is the boot image: set another one first")
41
    if name not in flash_dir(auth)["entries"]:
42
        return {"path": f"flash:/{name}", "deleted": False}
43
    eos.run_commands([f"delete flash:{name}"])
44
    return {"path": f"flash:/{name}", "deleted": True}
45

46

47
# A file at the root of flash: "flash:/NAME", "flash:NAME" or "NAME", with only A-Z a-z 0-9 _ . + - in NAME (the name
48
# goes into a CLI command). Returns NAME.
49
def flash_name(path: str):
50
    name = re.sub(r"^flash:/?", "", (path or "").strip())
51
    if not re.fullmatch(r"[\w.+-]+", name) or name in (".", ".."):
52
        raise ValueError(f"expected a file at the root of flash (flash:/NAME, NAME of A-Z a-z 0-9 _ . + -): got {path!r}")
53
    return name
54

55

56
def flash_dir(auth):
57
    [d] = node(auth).run_commands([{"cmd": "dir flash:/", "revision": 2}])
58
    return d["urls"]["flash:/"]
59

60

61
# One resource can serve every switch that shares a login: the host input, when set, overrides the resource's host.
62
def with_host(auth: arista_eos, host: str):
63
    host = (host or "").strip() or (auth.get("host") or "").strip()
64
    if not host:
65
        raise ValueError("host is required: set it on the resource or pass host")
66
    return {**auth, "host": host}
67

68

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

81
    # The TCP connection only, like eAPI's transport.connect(): if it fails, nothing was sent.
82
    def connect(self):
83
        self.sock = socket.create_connection(ssh_addr(self.auth), self.timeout)
84

85
    def lost(self, e):
86
        self.socket_error = e
87
        return pyeapi.eapilib.ConnectionError("ssh", f"SSH connection failed ({e})")
88

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

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

153
    # One command: its output without the echoed command and the prompt; progress lines keep their last state.
154
    def cli(self, cmd):
155
        try:
156
            self.chan.send(cmd + "\r")
157
            out = self.read()
158
        except (OSError, EOFError, paramiko.SSHException) as e:
159
            raise self.lost(e)
160
        self.mode = out.rstrip().splitlines()[-1]
161
        lines = [l.rstrip("\r").split("\r")[-1] for l in out.split("\n")]
162
        return "\n".join(lines[1:-1]).strip("\n")
163

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

217

218
# paramiko logs a traceback when a rebooting switch drops the session.
219
logging.getLogger("paramiko").addHandler(logging.NullHandler())
220

221

222
# host, or host:port ([v6]:port), else port, else 22.
223
def ssh_addr(auth: arista_eos):
224
    h = auth["host"]
225
    if "://" in h:
226
        raise ValueError(f"with transport ssh, host is an address or a hostname (with :port), not a URL: {h}")
227
    url = urlsplit(f"ssh://{h}" if h.count(":") <= 1 or h.startswith("[") else f"ssh://[{h}]")
228
    return url.hostname, url.port or int(auth.get("port") or 22)
229

230

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

237
    def run_commands(*args, **kwargs):
238
        try:
239
            return run(*args, **kwargs)
240
        except pyeapi.eapilib.ConnectionError as e:
241
            raise connection_error(auth, eos, e)
242

243
    eos.run_commands = run_commands
244
    return eos
245

246

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

257

258
class DeviceUnreachable(Exception):
259
    pass
260

261

262
class AuthFailure(Exception):
263
    pass
264

265

266
# pyeapi logs a traceback for every socket error.
267
logging.getLogger("pyeapi").addHandler(logging.NullHandler())
268

269

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