acex-driver-fortinet-fortios-cli 0.2.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- acex_driver_fortinet_fortios_cli-0.2.0/PKG-INFO +17 -0
- acex_driver_fortinet_fortios_cli-0.2.0/pyproject.toml +36 -0
- acex_driver_fortinet_fortios_cli-0.2.0/src/acex_driver_fortinet_fortios_cli/__init__.py +1 -0
- acex_driver_fortinet_fortios_cli-0.2.0/src/acex_driver_fortinet_fortios_cli/changelog.json +24 -0
- acex_driver_fortinet_fortios_cli-0.2.0/src/acex_driver_fortinet_fortios_cli/codec.py +54 -0
- acex_driver_fortinet_fortios_cli-0.2.0/src/acex_driver_fortinet_fortios_cli/fortios_cli.py +19 -0
- acex_driver_fortinet_fortios_cli-0.2.0/src/acex_driver_fortinet_fortios_cli/framing.py +86 -0
- acex_driver_fortinet_fortios_cli-0.2.0/src/acex_driver_fortinet_fortios_cli/normalizer.py +28 -0
- acex_driver_fortinet_fortios_cli-0.2.0/src/acex_driver_fortinet_fortios_cli/state.py +24 -0
- acex_driver_fortinet_fortios_cli-0.2.0/src/acex_driver_fortinet_fortios_cli/syntax.py +15 -0
- acex_driver_fortinet_fortios_cli-0.2.0/src/acex_driver_fortinet_fortios_cli/transport/__init__.py +0 -0
- acex_driver_fortinet_fortios_cli-0.2.0/src/acex_driver_fortinet_fortios_cli/transport/transport.py +108 -0
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: acex-driver-fortinet-fortios-cli
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: ACE-X Driver: Fortinet FortiOS CLI SSH
|
|
5
|
+
License: AGPL-3.0
|
|
6
|
+
Author: Isak Ljunggren
|
|
7
|
+
Author-email: Isak.Ljunggren@Acebit.se
|
|
8
|
+
Requires-Python: >=3.13,<4.0
|
|
9
|
+
Classifier: License :: OSI Approved :: GNU Affero General Public License v3
|
|
10
|
+
Classifier: Programming Language :: Python :: 3
|
|
11
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.15
|
|
14
|
+
Requires-Dist: acex-devkit (>=3,<4)
|
|
15
|
+
Requires-Dist: asyncssh (>=2.14,<3.0)
|
|
16
|
+
Project-URL: Homepage, https://github.com/acex-labs/acex
|
|
17
|
+
Project-URL: Repository, https://github.com/acex-labs/acex
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
[tool.poetry]
|
|
2
|
+
name = "acex-driver-fortinet-fortios-cli"
|
|
3
|
+
version = "0.2.0"
|
|
4
|
+
description = "ACE-X Driver: Fortinet FortiOS CLI SSH"
|
|
5
|
+
authors = ["Isak Ljunggren <Isak.Ljunggren@Acebit.se>"]
|
|
6
|
+
license = "AGPL-3.0"
|
|
7
|
+
homepage = "https://github.com/acex-labs/acex"
|
|
8
|
+
repository = "https://github.com/acex-labs/acex"
|
|
9
|
+
|
|
10
|
+
packages = [
|
|
11
|
+
{ include = "acex_driver_fortinet_fortios_cli", from="src" }
|
|
12
|
+
]
|
|
13
|
+
|
|
14
|
+
[tool.poetry.dependencies]
|
|
15
|
+
python = "^3.13"
|
|
16
|
+
asyncssh = "^2.14"
|
|
17
|
+
acex-devkit = "^3"
|
|
18
|
+
|
|
19
|
+
[build-system]
|
|
20
|
+
requires = ["poetry-core>=2.0.0,<3.0.0"]
|
|
21
|
+
build-backend = "poetry.core.masonry.api"
|
|
22
|
+
|
|
23
|
+
[tool.poetry.plugins."acex.neds"]
|
|
24
|
+
fortinet_fortios_cli = "acex_driver_fortinet_fortios_cli.fortios_cli:FortiOSCLIDriver"
|
|
25
|
+
|
|
26
|
+
[tool.poetry.plugins."acex.changelog"]
|
|
27
|
+
acex-driver-fortinet-fortios-cli = "acex_driver_fortinet_fortios_cli"
|
|
28
|
+
|
|
29
|
+
# Shown as the component's name in Settings > What's new.
|
|
30
|
+
[tool.acex.changelog]
|
|
31
|
+
name = "Fortinet FortiOS CLI driver"
|
|
32
|
+
|
|
33
|
+
[dependency-groups]
|
|
34
|
+
dev = [
|
|
35
|
+
"ipython (>=9.10.0,<10.0.0)"
|
|
36
|
+
]
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
from .fortios_cli import FortiOSCLIDriver as FortiOSCLIDriver
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
{
|
|
2
|
+
"schema_version": 1,
|
|
3
|
+
"component": "acex-driver-fortinet-fortios-cli",
|
|
4
|
+
"name": "Fortinet FortiOS CLI driver",
|
|
5
|
+
"releases": [
|
|
6
|
+
{
|
|
7
|
+
"version": "0.2.0",
|
|
8
|
+
"date": "2026-11-24",
|
|
9
|
+
"entries": [
|
|
10
|
+
{
|
|
11
|
+
"id": "20261120-a-driver-for-fortinet-fortigate-devices",
|
|
12
|
+
"kind": "added",
|
|
13
|
+
"title": "A driver for Fortinet FortiGate devices (first step)",
|
|
14
|
+
"description": "ACEX can now reach a FortiGate over SSH and read its configuration with `show full-configuration`. Of that configuration it understands the hostname so far, and every other line is listed as one ACEX has no field for yet, so a node shows how much of the device is covered. Secrets in the configuration, passwords, pre-shared keys and private keys, are masked before it is stored. Writing configuration to a FortiGate and comparing it is not available yet: a change that ACEX would have made is reported as not rendered.",
|
|
15
|
+
"breaking": false,
|
|
16
|
+
"audience": "user",
|
|
17
|
+
"refs": []
|
|
18
|
+
}
|
|
19
|
+
]
|
|
20
|
+
}
|
|
21
|
+
],
|
|
22
|
+
"coming": [],
|
|
23
|
+
"highlights": []
|
|
24
|
+
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
from acex_devkit.configdiffer import Diff
|
|
2
|
+
from acex_devkit.drivers import Codec
|
|
3
|
+
from acex_devkit.drivers.mapper import Context, Mapper
|
|
4
|
+
from acex_devkit.models.codec_result import ParseResult, RenderMetadata, RenderResult, UnmatchedLine
|
|
5
|
+
from acex_devkit.models.composed_configuration import ComposedConfiguration
|
|
6
|
+
from acex_devkit.models.node_response import NodeInstance
|
|
7
|
+
|
|
8
|
+
from acex_driver_fortinet_fortios_cli import framing
|
|
9
|
+
from acex_driver_fortinet_fortios_cli.normalizer import FortiOSNormalizer
|
|
10
|
+
from acex_driver_fortinet_fortios_cli.syntax import BLOCKS
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class FortiOSCodec(Codec[str]):
|
|
14
|
+
"""FortiOS CLI syntax. Render and parse share one Mapper, so the two directions cannot drift apart.
|
|
15
|
+
|
|
16
|
+
FortiOS nests by indentation like the mapper does, but four spaces a level where the mapper takes a one
|
|
17
|
+
character indent, and it closes every `config` with `end` and every `edit` with `next`, which the mapper knows
|
|
18
|
+
nothing of. `render` reframes what the mapper wrote and `parse` what it is about to read (see `framing`),
|
|
19
|
+
moving the spans of both so they still point at the right lines.
|
|
20
|
+
|
|
21
|
+
A patch is not rendered yet. The mapper removes a component by negating its line with `no`, where FortiOS
|
|
22
|
+
uses `delete` and `unset`, so every change is reported as unrendered."""
|
|
23
|
+
|
|
24
|
+
mapper = Mapper(BLOCKS, indent=" ")
|
|
25
|
+
normalizer = FortiOSNormalizer()
|
|
26
|
+
|
|
27
|
+
def render(self, config: ComposedConfiguration, node: NodeInstance) -> RenderResult[str]:
|
|
28
|
+
rendered = self.mapper.render(config, Context(node))
|
|
29
|
+
layout = framing.insert(rendered.payload)
|
|
30
|
+
spans = [layout.span(span) for span in rendered.metadata.spans]
|
|
31
|
+
return RenderResult(payload=layout.text, metadata=rendered.metadata.model_copy(update={"spans": spans}))
|
|
32
|
+
|
|
33
|
+
def parse(self, raw: str, node: NodeInstance) -> ParseResult:
|
|
34
|
+
layout = framing.remove(self.normalize(raw))
|
|
35
|
+
parsed = self.mapper.parse(layout.text, Context(node))
|
|
36
|
+
spans = [layout.span(span) for span in parsed.metadata.spans]
|
|
37
|
+
unmatched = [
|
|
38
|
+
UnmatchedLine(line=framing.widen(entry.line), parents=[framing.widen(parent) for parent in entry.parents])
|
|
39
|
+
for entry in parsed.metadata.unmatched
|
|
40
|
+
]
|
|
41
|
+
metadata = parsed.metadata.model_copy(update={"spans": spans, "unmatched": unmatched})
|
|
42
|
+
return parsed.model_copy(update={"metadata": metadata})
|
|
43
|
+
|
|
44
|
+
def render_patch(self, diff: Diff, node: NodeInstance) -> RenderResult[str]:
|
|
45
|
+
return RenderResult(
|
|
46
|
+
payload="",
|
|
47
|
+
metadata=RenderMetadata(unrendered=[change.path for change in diff.get_all_changes()]),
|
|
48
|
+
)
|
|
49
|
+
|
|
50
|
+
def normalize(self, raw: str) -> str:
|
|
51
|
+
return self.normalizer.normalize(raw).config
|
|
52
|
+
|
|
53
|
+
def mask(self, raw: str) -> str:
|
|
54
|
+
return self.normalizer.mask(raw).config
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
from acex_devkit.drivers import NetworkElementDriver
|
|
2
|
+
from acex_devkit.models.ned import Platform
|
|
3
|
+
from acex_devkit.models.platform import OS, Vendor
|
|
4
|
+
|
|
5
|
+
from acex_driver_fortinet_fortios_cli.codec import FortiOSCodec
|
|
6
|
+
from acex_driver_fortinet_fortios_cli.state import FortiOSState
|
|
7
|
+
from acex_driver_fortinet_fortios_cli.transport.transport import FortiOSTransport
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class FortiOSCLIDriver(NetworkElementDriver):
|
|
11
|
+
"""Fortinet FortiOS CLI driver."""
|
|
12
|
+
|
|
13
|
+
codec_class = FortiOSCodec
|
|
14
|
+
transport_class = FortiOSTransport
|
|
15
|
+
state_class = FortiOSState
|
|
16
|
+
|
|
17
|
+
platforms = [Platform(vendor=Vendor.fortinet, os=OS.fortinet_fortios)]
|
|
18
|
+
|
|
19
|
+
interface_version = 2
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
from dataclasses import dataclass
|
|
2
|
+
|
|
3
|
+
from acex_devkit.models.codec_result import Span
|
|
4
|
+
|
|
5
|
+
# FortiOS closes every `config` with `end` and every `edit` with `next`, and indents four spaces a level. The devkit
|
|
6
|
+
# mapper nests by a one character indent and writes no closing line, so the codec reframes what it renders and what
|
|
7
|
+
# it parses: a render gets the closing lines and the four space indent, a parse loses them.
|
|
8
|
+
OPENERS = {"config": "end", "edit": "next"}
|
|
9
|
+
CLOSERS = frozenset(OPENERS.values())
|
|
10
|
+
STEP = " "
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@dataclass
|
|
14
|
+
class Layout:
|
|
15
|
+
"""The text in the other framing, and where the lines went. Line numbers are 1-based. `numbers` maps a line
|
|
16
|
+
of the mapper's text, the one without closing lines, to its line in FortiOS text, and `closers_after` lists,
|
|
17
|
+
for a line of the mapper's text, the header lines whose closing lines follow it in FortiOS text, innermost
|
|
18
|
+
first."""
|
|
19
|
+
|
|
20
|
+
text: str
|
|
21
|
+
numbers: dict[int, int]
|
|
22
|
+
closers_after: dict[int, list[int]]
|
|
23
|
+
|
|
24
|
+
def span(self, span: Span) -> Span:
|
|
25
|
+
"""A span of the mapper's text as it reads in FortiOS text, taking in the closing lines of the
|
|
26
|
+
components it holds."""
|
|
27
|
+
closers = sum(1 for header in self.closers_after.get(span.end, []) if header >= span.start)
|
|
28
|
+
return Span(start=self.numbers[span.start], end=self.numbers[span.end] + closers, path=span.path)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def widen(line: str) -> str:
|
|
32
|
+
"""A line of the mapper's text with the four space indent FortiOS writes."""
|
|
33
|
+
body = line.lstrip(" ")
|
|
34
|
+
return STEP * (len(line) - len(body)) + body
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def first_word(line: str) -> str:
|
|
38
|
+
words = line.split(maxsplit=1)
|
|
39
|
+
return words[0] if words else ""
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def insert(text: str) -> Layout:
|
|
43
|
+
"""The mapper's `text` as FortiOS writes it: a closing line where each `config` and `edit` block ends, found
|
|
44
|
+
from the indentation, and four spaces a level."""
|
|
45
|
+
lines = text.splitlines()
|
|
46
|
+
out: list[str] = []
|
|
47
|
+
numbers: dict[int, int] = {}
|
|
48
|
+
closers_after: dict[int, list[int]] = {}
|
|
49
|
+
open_blocks: list[tuple[int, str, int]] = []
|
|
50
|
+
|
|
51
|
+
def close(depth: int, after: int) -> None:
|
|
52
|
+
while open_blocks and open_blocks[-1][0] >= depth:
|
|
53
|
+
level, closer, header = open_blocks.pop()
|
|
54
|
+
out.append(STEP * level + closer)
|
|
55
|
+
closers_after.setdefault(after, []).append(header)
|
|
56
|
+
|
|
57
|
+
for number, line in enumerate(lines, start=1):
|
|
58
|
+
body = line.lstrip(" ")
|
|
59
|
+
level = len(line) - len(body)
|
|
60
|
+
if body:
|
|
61
|
+
close(level, number - 1)
|
|
62
|
+
out.append(widen(line))
|
|
63
|
+
numbers[number] = len(out)
|
|
64
|
+
if first_word(body) in OPENERS:
|
|
65
|
+
open_blocks.append((level, OPENERS[first_word(body)], number))
|
|
66
|
+
close(0, len(lines))
|
|
67
|
+
return Layout("\n".join(out) + ("\n" if text.endswith("\n") else ""), numbers, closers_after)
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def remove(text: str) -> Layout:
|
|
71
|
+
"""FortiOS `text` as the mapper reads it: without closing lines, one space a level."""
|
|
72
|
+
kept: list[str] = []
|
|
73
|
+
numbers: dict[int, int] = {}
|
|
74
|
+
closers_after: dict[int, list[int]] = {}
|
|
75
|
+
open_blocks: list[int] = []
|
|
76
|
+
for number, line in enumerate(text.splitlines(), start=1):
|
|
77
|
+
body = line.lstrip(" ")
|
|
78
|
+
if body.strip() in CLOSERS:
|
|
79
|
+
if open_blocks and kept:
|
|
80
|
+
closers_after.setdefault(len(kept), []).append(open_blocks.pop())
|
|
81
|
+
continue
|
|
82
|
+
kept.append(" " * ((len(line) - len(body)) // len(STEP)) + body)
|
|
83
|
+
numbers[len(kept)] = number
|
|
84
|
+
if first_word(body) in OPENERS:
|
|
85
|
+
open_blocks.append(len(kept))
|
|
86
|
+
return Layout("\n".join(kept) + ("\n" if text.endswith("\n") else ""), numbers, closers_after)
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import re
|
|
2
|
+
|
|
3
|
+
from acex_devkit.normalizer import MASK, BaseNormalizer, LineRule, OpResult, RewriteRule
|
|
4
|
+
|
|
5
|
+
SECRET_SETTINGS = "password|passwd|psksecret|psksecret-remote|secret|auth-pwd|priv-pwd|key|md5-key"
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class FortiOSNormalizer(BaseNormalizer):
|
|
9
|
+
line_rules = [
|
|
10
|
+
# The `#config-version=...` and `#conf_file_ver=...` header FortiOS writes ahead of the configuration.
|
|
11
|
+
LineRule("header_comment", re.compile(r"^\s*#")),
|
|
12
|
+
]
|
|
13
|
+
|
|
14
|
+
# A stored secret reads `set password ENC <blob>` and one in clear `set password <text>`. The value goes and the
|
|
15
|
+
# ENC marker, which only says how the value is stored, stays.
|
|
16
|
+
rewrite_rules = [
|
|
17
|
+
RewriteRule(
|
|
18
|
+
"secret_setting",
|
|
19
|
+
re.compile(rf"^(\s*set\s+(?:{SECRET_SETTINGS})(?:\s+ENC)?)\s+\S+.*$"),
|
|
20
|
+
rf"\1 {MASK}",
|
|
21
|
+
),
|
|
22
|
+
]
|
|
23
|
+
|
|
24
|
+
# A private key is one quoted value that runs over many lines, so a line by line rule cannot reach it.
|
|
25
|
+
private_key = re.compile(r'^(\s*set\s+private-key\s+)"[^"]*"', re.MULTILINE)
|
|
26
|
+
|
|
27
|
+
def mask(self, raw: str) -> OpResult:
|
|
28
|
+
return super().mask(self.private_key.sub(rf'\1"{MASK}"', raw))
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import re
|
|
2
|
+
|
|
3
|
+
from acex_devkit.drivers import State
|
|
4
|
+
from acex_devkit.models.platform import OS, Vendor
|
|
5
|
+
from acex_devkit.models.state import DeviceFacts
|
|
6
|
+
|
|
7
|
+
from acex_driver_fortinet_fortios_cli.transport.transport import FortiOSTransport
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class FortiOSState(State):
|
|
11
|
+
async def get_facts(self, transport: FortiOSTransport) -> DeviceFacts:
|
|
12
|
+
output = (await transport.execute(["get system status"]))[0]
|
|
13
|
+
return DeviceFacts(
|
|
14
|
+
vendor=Vendor.fortinet,
|
|
15
|
+
os=OS.fortinet_fortios,
|
|
16
|
+
os_version=self.find(r"^Version:\s*\S+\s+v(\d+\.\d+\.\d+)", output),
|
|
17
|
+
hardware_model=self.find(r"^Version:\s*(\S+)\s+v\d", output),
|
|
18
|
+
serial_number=self.find(r"^Serial-Number:\s*(\S+)", output),
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
@staticmethod
|
|
22
|
+
def find(pattern: str, text: str) -> str | None:
|
|
23
|
+
match = re.search(pattern, text, re.MULTILINE)
|
|
24
|
+
return match.group(1) if match else None
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
from acex_devkit.drivers.mapper import Block, Line
|
|
2
|
+
from acex_devkit.models.composed_configuration import SystemConfig
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
class SystemGlobalSyntax(Block):
|
|
6
|
+
path = "system.config"
|
|
7
|
+
component = SystemConfig
|
|
8
|
+
header = Line("config system global")
|
|
9
|
+
single = True
|
|
10
|
+
body = (Line('set hostname "{hostname}"'),)
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
BLOCKS = [
|
|
14
|
+
SystemGlobalSyntax(),
|
|
15
|
+
]
|
acex_driver_fortinet_fortios_cli-0.2.0/src/acex_driver_fortinet_fortios_cli/transport/__init__.py
ADDED
|
File without changes
|
acex_driver_fortinet_fortios_cli-0.2.0/src/acex_driver_fortinet_fortios_cli/transport/transport.py
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
import re
|
|
3
|
+
|
|
4
|
+
import asyncssh
|
|
5
|
+
from acex_devkit.drivers import Transport
|
|
6
|
+
from acex_devkit.exceptions import (
|
|
7
|
+
AuthenticationFailed,
|
|
8
|
+
ConnectionTimeout,
|
|
9
|
+
DriverException,
|
|
10
|
+
HostUnreachable,
|
|
11
|
+
SshAlgorithmMismatch,
|
|
12
|
+
)
|
|
13
|
+
from acex_devkit.models.management_connection import ConnectionType
|
|
14
|
+
|
|
15
|
+
# What FortiOS prints when it refuses a line of a configuration it was given.
|
|
16
|
+
REJECTED = re.compile(r"parse error|Command fail|Unknown action|Return code -\d+|node_check_object fail", re.IGNORECASE)
|
|
17
|
+
|
|
18
|
+
# FortiOS pages long output with `--More--` and a command run on its own channel stops after the first page, so the
|
|
19
|
+
# pager, a console setting, is turned off for the session and put back before it ends.
|
|
20
|
+
PAGER_OFF = ("config system console", "set output standard", "end")
|
|
21
|
+
PAGER_ON = ("config system console", "set output more", "end")
|
|
22
|
+
|
|
23
|
+
# A session prints a prompt before each line it runs and does not echo the line: `FGT-1 # `, `FGT-1 (global) # `. The
|
|
24
|
+
# name in it follows the hostname, which a configuration can change in the middle of a session.
|
|
25
|
+
PROMPT = re.compile(r"^\S+(?: \([^)]*\))? # ?", re.MULTILINE)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class FortiOSTransport(Transport[str]):
|
|
29
|
+
"""SSH to FortiOS over asyncssh. Every command is typed into a CLI session with the pager off, and the output is
|
|
30
|
+
cut out from between the prompts the session prints. Payloads are CLI text, one command per line.
|
|
31
|
+
|
|
32
|
+
Checked on a FortiGate-VM 7.6.8 (ARM64 KVM, unlicensed, one VDOM). Not checked: a multi-VDOM unit, where
|
|
33
|
+
`config system console` may need `config global` first and `show full-configuration` from the root VDOM may leave
|
|
34
|
+
the other VDOMs out, and other FortiOS versions."""
|
|
35
|
+
|
|
36
|
+
connection_types = {ConnectionType.ssh}
|
|
37
|
+
|
|
38
|
+
PORT = 22
|
|
39
|
+
CONNECT_TIMEOUT = 30
|
|
40
|
+
COMMAND_TIMEOUT = 60
|
|
41
|
+
CONFIG_TIMEOUT = 120
|
|
42
|
+
|
|
43
|
+
async def open(self) -> None:
|
|
44
|
+
login = self.credential("userpass")
|
|
45
|
+
try:
|
|
46
|
+
self.conn = await asyncssh.connect(
|
|
47
|
+
self.address,
|
|
48
|
+
port=self.PORT,
|
|
49
|
+
username=login.fields["username"],
|
|
50
|
+
password=login.fields["password"],
|
|
51
|
+
known_hosts=None,
|
|
52
|
+
connect_timeout=self.CONNECT_TIMEOUT,
|
|
53
|
+
)
|
|
54
|
+
except asyncssh.PermissionDenied as e:
|
|
55
|
+
raise AuthenticationFailed(f"Authentication to {self.address} failed") from e
|
|
56
|
+
except asyncssh.KeyExchangeFailed as e:
|
|
57
|
+
raise SshAlgorithmMismatch(f"No SSH algorithm in common with the device: {e}") from e
|
|
58
|
+
except TimeoutError as e:
|
|
59
|
+
raise ConnectionTimeout(f"Connection to {self.address} timed out") from e
|
|
60
|
+
except (OSError, asyncssh.Error) as e:
|
|
61
|
+
raise HostUnreachable(f"Could not connect to the device: {e}") from e
|
|
62
|
+
|
|
63
|
+
async def close(self) -> None:
|
|
64
|
+
try:
|
|
65
|
+
self.conn.close()
|
|
66
|
+
await self.conn.wait_closed()
|
|
67
|
+
except Exception:
|
|
68
|
+
pass
|
|
69
|
+
|
|
70
|
+
async def get_config(self) -> str:
|
|
71
|
+
return await self.run("show full-configuration", self.CONFIG_TIMEOUT)
|
|
72
|
+
|
|
73
|
+
async def apply(self, payload: str) -> str:
|
|
74
|
+
script = "\n".join(line.rstrip() for line in payload.splitlines() if line.strip())
|
|
75
|
+
if not script:
|
|
76
|
+
return ""
|
|
77
|
+
output = await self.session(script + "\nexit\n", self.CONFIG_TIMEOUT, "The configuration")
|
|
78
|
+
if REJECTED.search(output):
|
|
79
|
+
raise DriverException(f"The device rejected the configuration:\n{output}")
|
|
80
|
+
return output
|
|
81
|
+
|
|
82
|
+
async def execute(self, request: list[str]) -> list[str]:
|
|
83
|
+
return [await self.run(command, self.COMMAND_TIMEOUT) for command in request]
|
|
84
|
+
|
|
85
|
+
async def run(self, command: str, timeout: float) -> str:
|
|
86
|
+
"""The output of one command, without the prompts around it."""
|
|
87
|
+
script = "\n".join([*PAGER_OFF, command, *PAGER_ON, "exit"]) + "\n"
|
|
88
|
+
return self.output_of(await self.session(script, timeout, command))
|
|
89
|
+
|
|
90
|
+
@staticmethod
|
|
91
|
+
def output_of(raw: str) -> str:
|
|
92
|
+
"""What the command printed in a session built by `run`: one prompt for each line typed, the command being
|
|
93
|
+
line `len(PAGER_OFF) + 1`, so its output sits after that many prompts and before the prompt that follows it,
|
|
94
|
+
which is the first of the `len(PAGER_ON) + 1` prompts at the end."""
|
|
95
|
+
prompts = list(PROMPT.finditer(raw))
|
|
96
|
+
if len(prompts) < len(PAGER_OFF) + len(PAGER_ON) + 2:
|
|
97
|
+
raise DriverException(f"Could not find the output in what the device printed:\n{raw}")
|
|
98
|
+
start = prompts[len(PAGER_OFF)].end()
|
|
99
|
+
stop = prompts[-(len(PAGER_ON) + 1)].start()
|
|
100
|
+
return raw[start:stop].rstrip("\n") + "\n"
|
|
101
|
+
|
|
102
|
+
async def session(self, script: str, timeout: float, what: str) -> str:
|
|
103
|
+
"""Everything the CLI printed while `script` was typed into a session."""
|
|
104
|
+
try:
|
|
105
|
+
result = await asyncio.wait_for(self.conn.run(None, input=script, check=False), timeout)
|
|
106
|
+
except TimeoutError as e:
|
|
107
|
+
raise ConnectionTimeout(f"{what} did not finish within {timeout:.0f} s") from e
|
|
108
|
+
return str(result.stdout or "")
|