networka 0.1.9__py3-none-any.whl
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.
- network_toolkit/__about__.py +4 -0
- network_toolkit/__init__.py +8 -0
- network_toolkit/__main__.py +10 -0
- network_toolkit/builtin_sequences/arista_eos/common.yml +53 -0
- network_toolkit/builtin_sequences/mikrotik_routeros/common.yml +52 -0
- network_toolkit/cli.py +265 -0
- network_toolkit/commands/__init__.py +8 -0
- network_toolkit/commands/backup.py +441 -0
- network_toolkit/commands/complete.py +172 -0
- network_toolkit/commands/config.py +1068 -0
- network_toolkit/commands/diff.py +485 -0
- network_toolkit/commands/download.py +197 -0
- network_toolkit/commands/firmware.py +780 -0
- network_toolkit/commands/info.py +377 -0
- network_toolkit/commands/list.py +345 -0
- network_toolkit/commands/routerboard_upgrade.py +204 -0
- network_toolkit/commands/run.py +839 -0
- network_toolkit/commands/schema_unified.py +91 -0
- network_toolkit/commands/sequence.py +17 -0
- network_toolkit/commands/ssh.py +540 -0
- network_toolkit/commands/ssh_engines.py +0 -0
- network_toolkit/commands/ssh_fallback.py +97 -0
- network_toolkit/commands/ssh_platform.py +120 -0
- network_toolkit/commands/upload.py +237 -0
- network_toolkit/commands/vendor_config_backup.py +378 -0
- network_toolkit/common/color_magic.py +177 -0
- network_toolkit/common/command.py +135 -0
- network_toolkit/common/command_base.py +135 -0
- network_toolkit/common/command_helpers.py +214 -0
- network_toolkit/common/credentials.py +86 -0
- network_toolkit/common/defaults.py +17 -0
- network_toolkit/common/errors.py +130 -0
- network_toolkit/common/interactive_confirmation.py +144 -0
- network_toolkit/common/logging.py +47 -0
- network_toolkit/common/output.py +594 -0
- network_toolkit/common/output_clean.py +244 -0
- network_toolkit/common/paths.py +86 -0
- network_toolkit/common/resolver.py +207 -0
- network_toolkit/common/styles.py +199 -0
- network_toolkit/common/table_generator.py +169 -0
- network_toolkit/common/table_providers.py +716 -0
- network_toolkit/config.py +1506 -0
- network_toolkit/credentials.py +288 -0
- network_toolkit/device.py +1658 -0
- network_toolkit/device_transfers.py +170 -0
- network_toolkit/exceptions.py +78 -0
- network_toolkit/ip_device.py +241 -0
- network_toolkit/platforms/__init__.py +21 -0
- network_toolkit/platforms/base.py +267 -0
- network_toolkit/platforms/cisco_ios/__init__.py +6 -0
- network_toolkit/platforms/cisco_ios/constants.py +15 -0
- network_toolkit/platforms/cisco_ios/operations.py +426 -0
- network_toolkit/platforms/cisco_iosxe/__init__.py +6 -0
- network_toolkit/platforms/cisco_iosxe/constants.py +15 -0
- network_toolkit/platforms/cisco_iosxe/operations.py +580 -0
- network_toolkit/platforms/cisco_shared/__init__.py +0 -0
- network_toolkit/platforms/cisco_shared/operations.py +0 -0
- network_toolkit/platforms/factory.py +190 -0
- network_toolkit/platforms/mikrotik_routeros/__init__.py +8 -0
- network_toolkit/platforms/mikrotik_routeros/confirmation_patterns.py +24 -0
- network_toolkit/platforms/mikrotik_routeros/constants.py +31 -0
- network_toolkit/platforms/mikrotik_routeros/operations.py +686 -0
- network_toolkit/results_enhanced.py +364 -0
- network_toolkit/schemas/__init__.py +8 -0
- network_toolkit/sequence_manager.py +239 -0
- network_toolkit/shell_completion/bash_completion_nw.sh +339 -0
- network_toolkit/shell_completion/zsh_completion_nw.zsh +136 -0
- network_toolkit/transport/__init__.py +15 -0
- network_toolkit/transport/factory.py +113 -0
- network_toolkit/transport/interfaces.py +46 -0
- network_toolkit/transport/nornir_inventory.py +173 -0
- network_toolkit/transport/nornir_netmiko.py +277 -0
- network_toolkit/transport/scrapli_sync.py +36 -0
- network_toolkit/tui/__init__.py +18 -0
- network_toolkit/tui/app.py +1275 -0
- network_toolkit/tui/clipboard.py +46 -0
- network_toolkit/tui/compat.py +111 -0
- network_toolkit/tui/constants.py +111 -0
- network_toolkit/tui/controller.py +550 -0
- network_toolkit/tui/data.py +149 -0
- network_toolkit/tui/dialogs.py +196 -0
- network_toolkit/tui/helpers.py +55 -0
- network_toolkit/tui/keymap.py +31 -0
- network_toolkit/tui/layout.py +111 -0
- network_toolkit/tui/models.py +93 -0
- network_toolkit/tui/output_manager.py +372 -0
- network_toolkit/tui/prompt.py +172 -0
- network_toolkit/tui/services.py +285 -0
- networka-0.1.9.dist-info/METADATA +316 -0
- networka-0.1.9.dist-info/RECORD +93 -0
- networka-0.1.9.dist-info/WHEEL +4 -0
- networka-0.1.9.dist-info/entry_points.txt +2 -0
- networka-0.1.9.dist-info/licenses/LICENSE +73 -0
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
"""Unified schema commands for the network toolkit CLI."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Annotated
|
|
6
|
+
|
|
7
|
+
import typer
|
|
8
|
+
|
|
9
|
+
from network_toolkit.common.logging import setup_logging
|
|
10
|
+
from network_toolkit.exceptions import NetworkToolkitError
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def register(app: typer.Typer) -> None:
|
|
14
|
+
"""Register the unified schema command group with the main CLI app."""
|
|
15
|
+
schema_app = typer.Typer(
|
|
16
|
+
name="schema",
|
|
17
|
+
help="JSON schema management commands",
|
|
18
|
+
no_args_is_help=True,
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
@schema_app.command("update")
|
|
22
|
+
def update(
|
|
23
|
+
verbose: Annotated[bool, typer.Option("--verbose", "-v")] = False,
|
|
24
|
+
) -> None:
|
|
25
|
+
"""Update JSON schemas for YAML editor validation.
|
|
26
|
+
|
|
27
|
+
Regenerates the JSON schema files used by VS Code and other YAML editors
|
|
28
|
+
to provide validation and auto-completion for configuration files.
|
|
29
|
+
|
|
30
|
+
Creates/updates:
|
|
31
|
+
- schemas/network-config.schema.json (full config)
|
|
32
|
+
- schemas/device-config.schema.json (device collections)
|
|
33
|
+
- schemas/groups-config.schema.json (group collections)
|
|
34
|
+
- .vscode/settings.json (VS Code YAML validation)
|
|
35
|
+
"""
|
|
36
|
+
setup_logging("DEBUG" if verbose else "INFO")
|
|
37
|
+
|
|
38
|
+
try:
|
|
39
|
+
from network_toolkit.commands.schema import _schema_update_impl
|
|
40
|
+
|
|
41
|
+
_schema_update_impl(verbose=verbose)
|
|
42
|
+
|
|
43
|
+
except NetworkToolkitError as e:
|
|
44
|
+
from network_toolkit.common.command_helpers import CommandContext
|
|
45
|
+
|
|
46
|
+
ctx = CommandContext()
|
|
47
|
+
ctx.print_error(str(e))
|
|
48
|
+
if verbose and hasattr(e, "details") and e.details:
|
|
49
|
+
ctx.print_error(f"Details: {e.details}")
|
|
50
|
+
raise typer.Exit(1) from None
|
|
51
|
+
except typer.Exit:
|
|
52
|
+
# Allow clean exits (e.g., user cancellation) to pass through
|
|
53
|
+
raise
|
|
54
|
+
except Exception as e: # pragma: no cover - unexpected
|
|
55
|
+
from network_toolkit.common.command_helpers import CommandContext
|
|
56
|
+
|
|
57
|
+
ctx = CommandContext()
|
|
58
|
+
ctx.print_error(f"Unexpected error: {e}")
|
|
59
|
+
raise typer.Exit(1) from None
|
|
60
|
+
|
|
61
|
+
@schema_app.command("info")
|
|
62
|
+
def info(
|
|
63
|
+
verbose: Annotated[bool, typer.Option("--verbose", "-v")] = False,
|
|
64
|
+
) -> None:
|
|
65
|
+
"""Display information about JSON schema files."""
|
|
66
|
+
setup_logging("DEBUG" if verbose else "INFO")
|
|
67
|
+
|
|
68
|
+
try:
|
|
69
|
+
from network_toolkit.commands.schema import _schema_info_impl
|
|
70
|
+
|
|
71
|
+
_schema_info_impl(verbose=verbose)
|
|
72
|
+
|
|
73
|
+
except NetworkToolkitError as e:
|
|
74
|
+
from network_toolkit.common.command_helpers import CommandContext
|
|
75
|
+
|
|
76
|
+
ctx = CommandContext()
|
|
77
|
+
ctx.print_error(str(e))
|
|
78
|
+
if verbose and hasattr(e, "details") and e.details:
|
|
79
|
+
ctx.print_error(f"Details: {e.details}")
|
|
80
|
+
raise typer.Exit(1) from None
|
|
81
|
+
except typer.Exit:
|
|
82
|
+
# Allow clean exits (e.g., user cancellation) to pass through
|
|
83
|
+
raise
|
|
84
|
+
except Exception as e: # pragma: no cover - unexpected
|
|
85
|
+
from network_toolkit.common.command_helpers import CommandContext
|
|
86
|
+
|
|
87
|
+
ctx = CommandContext()
|
|
88
|
+
ctx.print_error(f"Unexpected error: {e}")
|
|
89
|
+
raise typer.Exit(1) from None
|
|
90
|
+
|
|
91
|
+
app.add_typer(schema_app, name="schema", rich_help_panel="Info & Configuration")
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
"""Deprecated: The 'sequence' command has been removed. Use 'run' instead.
|
|
2
|
+
|
|
3
|
+
This module remains only as a stub placeholder to avoid import errors in older
|
|
4
|
+
environments. It doesn't register any commands. All sequence functionality is
|
|
5
|
+
handled by `nw run <device|group> <sequence>`.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import typer
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def register(app: typer.Typer) -> None: # pragma: no cover - compatibility stub
|
|
14
|
+
_ = app
|
|
15
|
+
# Intentionally no-op: 'sequence' subcommand was removed in favor of 'run'.
|
|
16
|
+
# Keeping this stub avoids crashes if older integrations import it.
|
|
17
|
+
pass
|
|
@@ -0,0 +1,540 @@
|
|
|
1
|
+
"""tmux-powered SSH fanout command.
|
|
2
|
+
|
|
3
|
+
This command opens a tmux session/window with panes for one or more devices and
|
|
4
|
+
starts interactive SSH clients in each pane. It aims to be lean and simple,
|
|
5
|
+
relying on the user's SSH setup (keys/agent). Optionally it can enable
|
|
6
|
+
"synchronize-panes" so a single keyboard input is sent to all panes.
|
|
7
|
+
|
|
8
|
+
Design goals:
|
|
9
|
+
- No persistence beyond tmux session; no extra daemons.
|
|
10
|
+
- Avoid handling passwords; prefer SSH keys. Optionally use sshpass.
|
|
11
|
+
- Minimal, readable code using libtmux.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
# Standard library imports
|
|
17
|
+
import datetime
|
|
18
|
+
import os
|
|
19
|
+
import shlex
|
|
20
|
+
import shutil
|
|
21
|
+
import tempfile
|
|
22
|
+
import threading
|
|
23
|
+
from dataclasses import dataclass
|
|
24
|
+
from enum import Enum
|
|
25
|
+
from pathlib import Path
|
|
26
|
+
from typing import Annotated, Any
|
|
27
|
+
|
|
28
|
+
# Third-party imports
|
|
29
|
+
import typer
|
|
30
|
+
|
|
31
|
+
# Local application imports
|
|
32
|
+
from network_toolkit.commands.ssh_fallback import open_sequential_ssh_sessions
|
|
33
|
+
from network_toolkit.commands.ssh_platform import get_platform_capabilities
|
|
34
|
+
from network_toolkit.common.command_helpers import CommandContext
|
|
35
|
+
from network_toolkit.common.logging import setup_logging
|
|
36
|
+
from network_toolkit.common.output import OutputMode
|
|
37
|
+
from network_toolkit.common.resolver import DeviceResolver
|
|
38
|
+
from network_toolkit.config import NetworkConfig, load_config
|
|
39
|
+
from network_toolkit.exceptions import NetworkToolkitError
|
|
40
|
+
from network_toolkit.ip_device import (
|
|
41
|
+
create_ip_based_config,
|
|
42
|
+
extract_ips_from_target,
|
|
43
|
+
get_supported_platforms,
|
|
44
|
+
is_ip_list,
|
|
45
|
+
)
|
|
46
|
+
|
|
47
|
+
app_help = (
|
|
48
|
+
"Open tmux with SSH panes for a device or group.\n\n"
|
|
49
|
+
"Synchronized typing is ENABLED by default - keystrokes go to all panes.\n"
|
|
50
|
+
"Use --no-sync to disable at startup.\n\n"
|
|
51
|
+
"Quick controls:\n"
|
|
52
|
+
"- Ctrl+b, z: Zoom/unzoom focused pane (exits/enters sync mode)\n"
|
|
53
|
+
"- Ctrl+b + Arrow keys: Navigate panes\n"
|
|
54
|
+
"- Click any pane to focus it\n"
|
|
55
|
+
"- Ctrl+b, d: Detach session\n\n"
|
|
56
|
+
"When sync is on, all panes show red borders."
|
|
57
|
+
)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
LAYOUT_CHOICES = (
|
|
61
|
+
"tiled",
|
|
62
|
+
"even-horizontal",
|
|
63
|
+
"even-vertical",
|
|
64
|
+
"main-horizontal",
|
|
65
|
+
"main-vertical",
|
|
66
|
+
)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
@dataclass
|
|
70
|
+
class Target:
|
|
71
|
+
name: str
|
|
72
|
+
devices: list[str]
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _ensure_libtmux() -> Any:
|
|
76
|
+
"""Ensure libtmux is available and can connect to tmux server."""
|
|
77
|
+
try:
|
|
78
|
+
import libtmux
|
|
79
|
+
except Exception as e: # pragma: no cover - simple import guard
|
|
80
|
+
msg = (
|
|
81
|
+
"libtmux is required for this command. Install with 'uv add libtmux' or "
|
|
82
|
+
"'pip install libtmux'."
|
|
83
|
+
)
|
|
84
|
+
raise RuntimeError(msg) from e
|
|
85
|
+
|
|
86
|
+
# Test if we can connect to tmux server (will start one if needed)
|
|
87
|
+
try:
|
|
88
|
+
server = libtmux.Server()
|
|
89
|
+
# This will fail if tmux is not installed or cannot start
|
|
90
|
+
_ = server.sessions
|
|
91
|
+
except Exception as e:
|
|
92
|
+
msg = (
|
|
93
|
+
"Cannot connect to tmux server. Please ensure tmux is installed.\n"
|
|
94
|
+
"Install with: apt install tmux (Linux), brew install tmux (macOS), "
|
|
95
|
+
"or use WSL on Windows."
|
|
96
|
+
)
|
|
97
|
+
raise RuntimeError(msg) from e
|
|
98
|
+
|
|
99
|
+
return libtmux
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def _resolve_targets(
|
|
103
|
+
config: NetworkConfig, targets: str, ctx: CommandContext
|
|
104
|
+
) -> Target:
|
|
105
|
+
"""Resolve comma-separated targets to a list of devices."""
|
|
106
|
+
resolver = DeviceResolver(config)
|
|
107
|
+
devices, unknowns = resolver.resolve_targets(targets)
|
|
108
|
+
|
|
109
|
+
if unknowns:
|
|
110
|
+
# Be tolerant and warn about unknowns but continue
|
|
111
|
+
unknowns_str = ", ".join(unknowns)
|
|
112
|
+
ctx.print_warning(f"Unknown targets: {unknowns_str}")
|
|
113
|
+
|
|
114
|
+
if not devices:
|
|
115
|
+
msg = f"No valid devices found in targets: {targets}"
|
|
116
|
+
raise NetworkToolkitError(
|
|
117
|
+
msg,
|
|
118
|
+
details={"targets": targets, "unknowns": unknowns},
|
|
119
|
+
)
|
|
120
|
+
|
|
121
|
+
return Target(name=targets, devices=devices)
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
class AuthMode(str, Enum):
|
|
125
|
+
KEY_FIRST = "key-first" # try keys first, fallback to password
|
|
126
|
+
KEY = "key" # prefer keys/agent only
|
|
127
|
+
PASSWORD = "password" # use sshpass only
|
|
128
|
+
INTERACTIVE = "interactive" # let ssh prompt per-pane
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def _secure_tmpdir() -> Path:
|
|
132
|
+
"""Return a secure, user-only temp directory for transient secrets.
|
|
133
|
+
|
|
134
|
+
Prefers XDG_RUNTIME_DIR (0700 tmpfs) else ~/.cache/networka/sshpass (0700),
|
|
135
|
+
else a namespaced dir under system temp (0700).
|
|
136
|
+
"""
|
|
137
|
+
xdg = os.environ.get("XDG_RUNTIME_DIR")
|
|
138
|
+
if xdg:
|
|
139
|
+
p = Path(xdg) / "networka"
|
|
140
|
+
else:
|
|
141
|
+
p = Path.home() / ".cache" / "networka" / "sshpass"
|
|
142
|
+
try:
|
|
143
|
+
p.mkdir(parents=True, exist_ok=True)
|
|
144
|
+
p.chmod(0o700)
|
|
145
|
+
except Exception:
|
|
146
|
+
p = Path(tempfile.gettempdir()) / "networka_sshpass"
|
|
147
|
+
p.mkdir(parents=True, exist_ok=True)
|
|
148
|
+
try:
|
|
149
|
+
p.chmod(0o700)
|
|
150
|
+
except Exception:
|
|
151
|
+
pass
|
|
152
|
+
return p
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def _prepare_sshpass_fifo(password: str) -> str:
|
|
156
|
+
"""Create a secure FIFO and start a writer thread to feed sshpass.
|
|
157
|
+
|
|
158
|
+
No plaintext is stored at rest; the FIFO node is removed after writing.
|
|
159
|
+
Returns the FIFO path.
|
|
160
|
+
"""
|
|
161
|
+
dirpath = _secure_tmpdir()
|
|
162
|
+
ts_ms = int(datetime.datetime.now(tz=datetime.UTC).timestamp() * 1000)
|
|
163
|
+
fifo_path = dirpath / f"pw_{os.getpid()}_{ts_ms}.fifo"
|
|
164
|
+
try:
|
|
165
|
+
os.mkfifo(fifo_path, 0o600)
|
|
166
|
+
except FileExistsError:
|
|
167
|
+
ts_ms += 1
|
|
168
|
+
fifo_path = dirpath / f"pw_{os.getpid()}_{ts_ms}.fifo"
|
|
169
|
+
os.mkfifo(fifo_path, 0o600)
|
|
170
|
+
|
|
171
|
+
def _writer() -> None:
|
|
172
|
+
try:
|
|
173
|
+
with open(fifo_path, "w", encoding="utf-8", buffering=1) as f:
|
|
174
|
+
f.write(password)
|
|
175
|
+
except Exception:
|
|
176
|
+
pass
|
|
177
|
+
finally:
|
|
178
|
+
try:
|
|
179
|
+
os.remove(fifo_path)
|
|
180
|
+
except Exception:
|
|
181
|
+
pass
|
|
182
|
+
|
|
183
|
+
threading.Thread(target=_writer, daemon=True).start()
|
|
184
|
+
return str(fifo_path)
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def _build_ssh_cmd(
|
|
188
|
+
*,
|
|
189
|
+
host: str,
|
|
190
|
+
user: str,
|
|
191
|
+
port: int = 22,
|
|
192
|
+
auth: AuthMode = AuthMode.KEY_FIRST,
|
|
193
|
+
password: str | None = None,
|
|
194
|
+
ctx: CommandContext,
|
|
195
|
+
) -> str:
|
|
196
|
+
base = [
|
|
197
|
+
"ssh",
|
|
198
|
+
"-p",
|
|
199
|
+
str(port),
|
|
200
|
+
"-o",
|
|
201
|
+
"StrictHostKeyChecking=accept-new",
|
|
202
|
+
# Add options to try key auth first, then password
|
|
203
|
+
"-o",
|
|
204
|
+
"PreferredAuthentications=publickey,password",
|
|
205
|
+
"-o",
|
|
206
|
+
"PasswordAuthentication=yes",
|
|
207
|
+
f"{user}@{host}",
|
|
208
|
+
]
|
|
209
|
+
|
|
210
|
+
if auth == AuthMode.PASSWORD:
|
|
211
|
+
if not password:
|
|
212
|
+
msg = (
|
|
213
|
+
"No password available for password auth. Set --password or "
|
|
214
|
+
"use env/config credentials."
|
|
215
|
+
)
|
|
216
|
+
raise NetworkToolkitError(msg)
|
|
217
|
+
# Use sshpass reading from a secure FIFO to avoid env/cmdline/plain files
|
|
218
|
+
if not shutil.which("sshpass"):
|
|
219
|
+
msg = (
|
|
220
|
+
"sshpass is required for password authentication but was not found.\n"
|
|
221
|
+
"Install it with: sudo apt install sshpass (Ubuntu/Debian) or "
|
|
222
|
+
"brew install hudochenkov/sshpass/sshpass (macOS)"
|
|
223
|
+
)
|
|
224
|
+
raise NetworkToolkitError(msg)
|
|
225
|
+
fifo = _prepare_sshpass_fifo(password)
|
|
226
|
+
sshpass_cmd = f"sshpass -f {shlex.quote(fifo)} "
|
|
227
|
+
return sshpass_cmd + " ".join(shlex.quote(p) for p in base)
|
|
228
|
+
|
|
229
|
+
if auth == AuthMode.KEY_FIRST and password:
|
|
230
|
+
# For key-first mode with password available, use sshpass if available
|
|
231
|
+
if shutil.which("sshpass"):
|
|
232
|
+
fifo = _prepare_sshpass_fifo(password)
|
|
233
|
+
sshpass_cmd = f"sshpass -f {shlex.quote(fifo)} "
|
|
234
|
+
return sshpass_cmd + " ".join(shlex.quote(p) for p in base)
|
|
235
|
+
else:
|
|
236
|
+
# If sshpass not available, provide helpful message
|
|
237
|
+
ctx.print_warning(
|
|
238
|
+
"sshpass not found. SSH will prompt for password interactively."
|
|
239
|
+
)
|
|
240
|
+
ctx.print_info(
|
|
241
|
+
"To automate password entry, install sshpass: "
|
|
242
|
+
"sudo apt install sshpass (Ubuntu/Debian) or "
|
|
243
|
+
"brew install hudochenkov/sshpass/sshpass (macOS)"
|
|
244
|
+
)
|
|
245
|
+
|
|
246
|
+
return " ".join(shlex.quote(p) for p in base)
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
def _session_name(default_base: str) -> str:
|
|
250
|
+
ts = datetime.datetime.now(tz=datetime.UTC).strftime("%Y%m%d_%H%M%S")
|
|
251
|
+
base = "".join(c if c.isalnum() or c in ("-", "_") else "_" for c in default_base)
|
|
252
|
+
return f"nw_{base}_{ts}"
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
def _sanitize_session_name(name: str) -> str:
|
|
256
|
+
"""Allow only safe characters in session name used for tmux attach."""
|
|
257
|
+
return "".join(c if (c.isalnum() or c in ("-", "_", ".")) else "_" for c in name)
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def register(app: typer.Typer) -> None:
|
|
261
|
+
@app.command("ssh", help=app_help, rich_help_panel="Remote Operations")
|
|
262
|
+
def ssh_fanout(
|
|
263
|
+
target: Annotated[
|
|
264
|
+
str,
|
|
265
|
+
typer.Argument(help="Comma-separated device/group names or IP addresses"),
|
|
266
|
+
],
|
|
267
|
+
*,
|
|
268
|
+
config_file: Annotated[
|
|
269
|
+
Path, typer.Option("--config", "-c", help="Path to config dir or YAML")
|
|
270
|
+
] = Path("config"),
|
|
271
|
+
auth: Annotated[
|
|
272
|
+
AuthMode,
|
|
273
|
+
typer.Option(
|
|
274
|
+
"--auth",
|
|
275
|
+
help=(
|
|
276
|
+
"Authentication mode: key-first (default), key, "
|
|
277
|
+
"password, interactive"
|
|
278
|
+
),
|
|
279
|
+
case_sensitive=False,
|
|
280
|
+
),
|
|
281
|
+
] = AuthMode.KEY_FIRST,
|
|
282
|
+
user_override: Annotated[
|
|
283
|
+
str | None, typer.Option("--user", help="Override username for SSH")
|
|
284
|
+
] = None,
|
|
285
|
+
password_override: Annotated[
|
|
286
|
+
str | None, typer.Option("--password", help="Override password for SSH")
|
|
287
|
+
] = None,
|
|
288
|
+
layout: Annotated[
|
|
289
|
+
str,
|
|
290
|
+
typer.Option(
|
|
291
|
+
"--layout",
|
|
292
|
+
case_sensitive=False,
|
|
293
|
+
help=f"tmux layout to use: {', '.join(LAYOUT_CHOICES)}",
|
|
294
|
+
),
|
|
295
|
+
] = "tiled",
|
|
296
|
+
session_name: Annotated[
|
|
297
|
+
str | None, typer.Option("--session-name", help="Custom session name")
|
|
298
|
+
] = None,
|
|
299
|
+
window_name: Annotated[
|
|
300
|
+
str | None, typer.Option("--window-name", help="Custom window name")
|
|
301
|
+
] = None,
|
|
302
|
+
sync: Annotated[
|
|
303
|
+
bool,
|
|
304
|
+
typer.Option(
|
|
305
|
+
"--sync/--no-sync", help="Enable synchronized typing (default: on)"
|
|
306
|
+
),
|
|
307
|
+
] = True,
|
|
308
|
+
use_sshpass: Annotated[
|
|
309
|
+
bool,
|
|
310
|
+
typer.Option(
|
|
311
|
+
"--use-sshpass",
|
|
312
|
+
help="Use sshpass (same as --auth password)",
|
|
313
|
+
),
|
|
314
|
+
] = False,
|
|
315
|
+
attach: Annotated[
|
|
316
|
+
bool, typer.Option("--attach/--no-attach", help="Attach after creating")
|
|
317
|
+
] = True,
|
|
318
|
+
verbose: Annotated[
|
|
319
|
+
bool, typer.Option("--verbose", "-v", help="Enable debug logging")
|
|
320
|
+
] = False,
|
|
321
|
+
device_type: Annotated[
|
|
322
|
+
str | None,
|
|
323
|
+
typer.Option(
|
|
324
|
+
"--platform",
|
|
325
|
+
"-p",
|
|
326
|
+
help="Device type when using IP addresses (e.g., mikrotik_routeros). Note: This specifies the network driver type, not hardware platform.",
|
|
327
|
+
),
|
|
328
|
+
] = None,
|
|
329
|
+
port: Annotated[
|
|
330
|
+
int | None,
|
|
331
|
+
typer.Option(
|
|
332
|
+
"--port",
|
|
333
|
+
help="SSH port when using IP addresses (default: 22)",
|
|
334
|
+
),
|
|
335
|
+
] = None,
|
|
336
|
+
transport_type: Annotated[
|
|
337
|
+
str | None,
|
|
338
|
+
typer.Option(
|
|
339
|
+
"--transport",
|
|
340
|
+
"-t",
|
|
341
|
+
help="Transport type for connections (currently only scrapli is supported). Defaults to configuration or scrapli.",
|
|
342
|
+
),
|
|
343
|
+
] = None,
|
|
344
|
+
) -> None:
|
|
345
|
+
"""
|
|
346
|
+
Open a tmux window with SSH panes for devices in targets.
|
|
347
|
+
|
|
348
|
+
Supports comma-separated device and group names.
|
|
349
|
+
|
|
350
|
+
Examples:
|
|
351
|
+
- nw ssh sw-acc1
|
|
352
|
+
- nw ssh sw-acc1,sw-acc2
|
|
353
|
+
- nw ssh access_switches
|
|
354
|
+
- nw ssh sw-acc1,access_switches
|
|
355
|
+
"""
|
|
356
|
+
|
|
357
|
+
setup_logging("DEBUG" if verbose else "INFO")
|
|
358
|
+
|
|
359
|
+
# Create command context for centralized output management
|
|
360
|
+
ctx = CommandContext(
|
|
361
|
+
output_mode=OutputMode.DEFAULT, verbose=verbose, config_file=config_file
|
|
362
|
+
)
|
|
363
|
+
|
|
364
|
+
# Validate transport type if provided
|
|
365
|
+
if transport_type is not None:
|
|
366
|
+
from network_toolkit.transport.factory import get_transport_factory
|
|
367
|
+
|
|
368
|
+
try:
|
|
369
|
+
# This will raise ValueError if transport_type is invalid
|
|
370
|
+
get_transport_factory(transport_type)
|
|
371
|
+
except ValueError as e:
|
|
372
|
+
ctx.print_error(str(e))
|
|
373
|
+
raise typer.Exit(1) from e
|
|
374
|
+
|
|
375
|
+
try:
|
|
376
|
+
libtmux = _ensure_libtmux()
|
|
377
|
+
except Exception as e: # pragma: no cover - trivial failures
|
|
378
|
+
ctx.print_error(str(e))
|
|
379
|
+
raise typer.Exit(1) from None
|
|
380
|
+
|
|
381
|
+
try:
|
|
382
|
+
config = load_config(config_file)
|
|
383
|
+
|
|
384
|
+
# Handle IP addresses if platform is provided
|
|
385
|
+
if is_ip_list(target):
|
|
386
|
+
if device_type is None:
|
|
387
|
+
supported_platforms = get_supported_platforms()
|
|
388
|
+
platform_list = "\n".join(
|
|
389
|
+
[f" {k}: {v}" for k, v in supported_platforms.items()]
|
|
390
|
+
)
|
|
391
|
+
ctx.print_error("When using IP addresses, --platform is required")
|
|
392
|
+
ctx.print_warning(f"Supported platforms:\n{platform_list}")
|
|
393
|
+
raise typer.Exit(1)
|
|
394
|
+
|
|
395
|
+
ips = extract_ips_from_target(target)
|
|
396
|
+
config = create_ip_based_config(
|
|
397
|
+
ips, device_type, config, port=port, transport_type=transport_type
|
|
398
|
+
)
|
|
399
|
+
ctx.print_info(
|
|
400
|
+
f"Using IP addresses with platform '{device_type}': {', '.join(ips)}"
|
|
401
|
+
)
|
|
402
|
+
|
|
403
|
+
resolver = DeviceResolver(config, device_type, port, transport_type)
|
|
404
|
+
tgt = Target(name=target, devices=resolver.resolve_targets(target)[0])
|
|
405
|
+
|
|
406
|
+
# Check platform capabilities after we have config and targets
|
|
407
|
+
platform_caps = get_platform_capabilities()
|
|
408
|
+
capabilities = platform_caps.get_fallback_options()
|
|
409
|
+
|
|
410
|
+
if not capabilities["can_do_tmux_fanout"]:
|
|
411
|
+
ctx.print_warning(
|
|
412
|
+
"tmux-based SSH fanout not available on this platform."
|
|
413
|
+
)
|
|
414
|
+
|
|
415
|
+
if not capabilities["tmux_available"]:
|
|
416
|
+
ctx.print_warning("Reason: tmux not available")
|
|
417
|
+
platform_caps.suggest_alternatives()
|
|
418
|
+
|
|
419
|
+
if capabilities["can_do_sequential_ssh"]:
|
|
420
|
+
ctx.print_info("Falling back to sequential SSH connections...")
|
|
421
|
+
# Use fallback implementation
|
|
422
|
+
open_sequential_ssh_sessions(tgt.devices, config)
|
|
423
|
+
return
|
|
424
|
+
else:
|
|
425
|
+
ctx.print_error("No SSH client available")
|
|
426
|
+
platform_caps.suggest_alternatives()
|
|
427
|
+
raise typer.Exit(1)
|
|
428
|
+
except Exception as e:
|
|
429
|
+
ctx.print_error(f"Failed to load config or resolve target: {e}")
|
|
430
|
+
raise typer.Exit(1) from None
|
|
431
|
+
|
|
432
|
+
# Resolve effective auth mode with legacy flag support
|
|
433
|
+
effective_auth = auth
|
|
434
|
+
|
|
435
|
+
# Prepare connection params and SSH commands per device
|
|
436
|
+
device_cmds: list[tuple[str, str]] = [] # (device_name, ssh_cmd)
|
|
437
|
+
for dev in tgt.devices:
|
|
438
|
+
params = config.get_device_connection_params(
|
|
439
|
+
dev, user_override, password_override
|
|
440
|
+
)
|
|
441
|
+
try:
|
|
442
|
+
# Determine credentials
|
|
443
|
+
user = str(params.get("auth_username"))
|
|
444
|
+
host = str(params.get("host"))
|
|
445
|
+
port = int(params.get("port", 22))
|
|
446
|
+
pw = params.get("auth_password")
|
|
447
|
+
|
|
448
|
+
# Decide auth mode if KEY_FIRST or legacy flag set
|
|
449
|
+
mode = effective_auth
|
|
450
|
+
if mode == AuthMode.KEY_FIRST:
|
|
451
|
+
# For KEY_FIRST, we use SSH native fallback behavior
|
|
452
|
+
# SSH will try keys first, then prompt for password if available
|
|
453
|
+
mode = AuthMode.KEY_FIRST
|
|
454
|
+
if use_sshpass:
|
|
455
|
+
mode = AuthMode.PASSWORD
|
|
456
|
+
|
|
457
|
+
# Note: We no longer strictly require sshpass since we have pexpect fallback
|
|
458
|
+
|
|
459
|
+
ssh_cmd = _build_ssh_cmd(
|
|
460
|
+
host=host,
|
|
461
|
+
user=user,
|
|
462
|
+
port=port,
|
|
463
|
+
auth=mode,
|
|
464
|
+
password=str(pw) if pw is not None else None,
|
|
465
|
+
ctx=ctx,
|
|
466
|
+
)
|
|
467
|
+
except Exception as e:
|
|
468
|
+
ctx.print_error(f"Skipping {dev}: {e}")
|
|
469
|
+
continue
|
|
470
|
+
device_cmds.append((dev, ssh_cmd))
|
|
471
|
+
|
|
472
|
+
if not device_cmds:
|
|
473
|
+
ctx.print_error("No valid devices to connect to.")
|
|
474
|
+
raise typer.Exit(1)
|
|
475
|
+
|
|
476
|
+
# Always create a new tmux session for clean behavior
|
|
477
|
+
server = libtmux.Server()
|
|
478
|
+
sname = session_name or _session_name(tgt.name)
|
|
479
|
+
sname = _sanitize_session_name(sname)
|
|
480
|
+
|
|
481
|
+
# Always create a new unique session name to avoid conflicts
|
|
482
|
+
sname = _sanitize_session_name(_session_name(tgt.name))
|
|
483
|
+
session = server.new_session(session_name=sname, attach=False)
|
|
484
|
+
|
|
485
|
+
wname = window_name or tgt.name
|
|
486
|
+
window = session.active_window
|
|
487
|
+
if wname != window.name:
|
|
488
|
+
try:
|
|
489
|
+
window.rename_window(wname)
|
|
490
|
+
except Exception as exc: # pragma: no cover - rename failure is non-fatal
|
|
491
|
+
ctx.console.log(f"Could not rename tmux window: {exc}")
|
|
492
|
+
|
|
493
|
+
# Ensure we start with a single pane
|
|
494
|
+
# Create panes for each device
|
|
495
|
+
panes: list[Any] = []
|
|
496
|
+
if not window.panes:
|
|
497
|
+
pane0 = window.split_window(attach=False)
|
|
498
|
+
panes.append(pane0)
|
|
499
|
+
else:
|
|
500
|
+
panes.append(window.active_pane)
|
|
501
|
+
|
|
502
|
+
for idx in range(1, len(device_cmds)):
|
|
503
|
+
vertical = idx % 2 == 1
|
|
504
|
+
panes.append(window.split_window(attach=False, vertical=vertical))
|
|
505
|
+
|
|
506
|
+
# Apply layout
|
|
507
|
+
if layout in LAYOUT_CHOICES:
|
|
508
|
+
window.select_layout(layout)
|
|
509
|
+
|
|
510
|
+
# Send ssh commands to all panes first
|
|
511
|
+
for (dev_name, cmd), pane in zip(device_cmds, window.panes, strict=True):
|
|
512
|
+
_ = dev_name # name not used but kept for future labels
|
|
513
|
+
pane.send_keys(cmd, enter=True)
|
|
514
|
+
|
|
515
|
+
# Simple sync setup using direct tmux commands
|
|
516
|
+
if sync:
|
|
517
|
+
try:
|
|
518
|
+
window.cmd("set-window-option", "synchronize-panes", "on")
|
|
519
|
+
except Exception as exc:
|
|
520
|
+
ctx.console.log(f"Could not enable sync: {exc}")
|
|
521
|
+
|
|
522
|
+
# Enable mouse support using direct command
|
|
523
|
+
try:
|
|
524
|
+
session.cmd("set-option", "mouse", "on")
|
|
525
|
+
except Exception as exc:
|
|
526
|
+
ctx.console.log(f"Could not enable mouse: {exc}")
|
|
527
|
+
|
|
528
|
+
ctx.print_success("Created tmux session")
|
|
529
|
+
ctx.print_info(f"Session: {sname} with {len(device_cmds)} pane(s).")
|
|
530
|
+
ctx.print_info("Use tmux to navigate. Press Ctrl-b d to detach.")
|
|
531
|
+
|
|
532
|
+
if attach:
|
|
533
|
+
# Use libtmux to attach directly instead of subprocess
|
|
534
|
+
try:
|
|
535
|
+
# Attach using libtmux server
|
|
536
|
+
session.attach_session()
|
|
537
|
+
except Exception:
|
|
538
|
+
ctx.print_warning(
|
|
539
|
+
f"Failed to attach automatically. Run: tmux attach -t {sname}"
|
|
540
|
+
)
|
|
File without changes
|