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.
Files changed (93) hide show
  1. network_toolkit/__about__.py +4 -0
  2. network_toolkit/__init__.py +8 -0
  3. network_toolkit/__main__.py +10 -0
  4. network_toolkit/builtin_sequences/arista_eos/common.yml +53 -0
  5. network_toolkit/builtin_sequences/mikrotik_routeros/common.yml +52 -0
  6. network_toolkit/cli.py +265 -0
  7. network_toolkit/commands/__init__.py +8 -0
  8. network_toolkit/commands/backup.py +441 -0
  9. network_toolkit/commands/complete.py +172 -0
  10. network_toolkit/commands/config.py +1068 -0
  11. network_toolkit/commands/diff.py +485 -0
  12. network_toolkit/commands/download.py +197 -0
  13. network_toolkit/commands/firmware.py +780 -0
  14. network_toolkit/commands/info.py +377 -0
  15. network_toolkit/commands/list.py +345 -0
  16. network_toolkit/commands/routerboard_upgrade.py +204 -0
  17. network_toolkit/commands/run.py +839 -0
  18. network_toolkit/commands/schema_unified.py +91 -0
  19. network_toolkit/commands/sequence.py +17 -0
  20. network_toolkit/commands/ssh.py +540 -0
  21. network_toolkit/commands/ssh_engines.py +0 -0
  22. network_toolkit/commands/ssh_fallback.py +97 -0
  23. network_toolkit/commands/ssh_platform.py +120 -0
  24. network_toolkit/commands/upload.py +237 -0
  25. network_toolkit/commands/vendor_config_backup.py +378 -0
  26. network_toolkit/common/color_magic.py +177 -0
  27. network_toolkit/common/command.py +135 -0
  28. network_toolkit/common/command_base.py +135 -0
  29. network_toolkit/common/command_helpers.py +214 -0
  30. network_toolkit/common/credentials.py +86 -0
  31. network_toolkit/common/defaults.py +17 -0
  32. network_toolkit/common/errors.py +130 -0
  33. network_toolkit/common/interactive_confirmation.py +144 -0
  34. network_toolkit/common/logging.py +47 -0
  35. network_toolkit/common/output.py +594 -0
  36. network_toolkit/common/output_clean.py +244 -0
  37. network_toolkit/common/paths.py +86 -0
  38. network_toolkit/common/resolver.py +207 -0
  39. network_toolkit/common/styles.py +199 -0
  40. network_toolkit/common/table_generator.py +169 -0
  41. network_toolkit/common/table_providers.py +716 -0
  42. network_toolkit/config.py +1506 -0
  43. network_toolkit/credentials.py +288 -0
  44. network_toolkit/device.py +1658 -0
  45. network_toolkit/device_transfers.py +170 -0
  46. network_toolkit/exceptions.py +78 -0
  47. network_toolkit/ip_device.py +241 -0
  48. network_toolkit/platforms/__init__.py +21 -0
  49. network_toolkit/platforms/base.py +267 -0
  50. network_toolkit/platforms/cisco_ios/__init__.py +6 -0
  51. network_toolkit/platforms/cisco_ios/constants.py +15 -0
  52. network_toolkit/platforms/cisco_ios/operations.py +426 -0
  53. network_toolkit/platforms/cisco_iosxe/__init__.py +6 -0
  54. network_toolkit/platforms/cisco_iosxe/constants.py +15 -0
  55. network_toolkit/platforms/cisco_iosxe/operations.py +580 -0
  56. network_toolkit/platforms/cisco_shared/__init__.py +0 -0
  57. network_toolkit/platforms/cisco_shared/operations.py +0 -0
  58. network_toolkit/platforms/factory.py +190 -0
  59. network_toolkit/platforms/mikrotik_routeros/__init__.py +8 -0
  60. network_toolkit/platforms/mikrotik_routeros/confirmation_patterns.py +24 -0
  61. network_toolkit/platforms/mikrotik_routeros/constants.py +31 -0
  62. network_toolkit/platforms/mikrotik_routeros/operations.py +686 -0
  63. network_toolkit/results_enhanced.py +364 -0
  64. network_toolkit/schemas/__init__.py +8 -0
  65. network_toolkit/sequence_manager.py +239 -0
  66. network_toolkit/shell_completion/bash_completion_nw.sh +339 -0
  67. network_toolkit/shell_completion/zsh_completion_nw.zsh +136 -0
  68. network_toolkit/transport/__init__.py +15 -0
  69. network_toolkit/transport/factory.py +113 -0
  70. network_toolkit/transport/interfaces.py +46 -0
  71. network_toolkit/transport/nornir_inventory.py +173 -0
  72. network_toolkit/transport/nornir_netmiko.py +277 -0
  73. network_toolkit/transport/scrapli_sync.py +36 -0
  74. network_toolkit/tui/__init__.py +18 -0
  75. network_toolkit/tui/app.py +1275 -0
  76. network_toolkit/tui/clipboard.py +46 -0
  77. network_toolkit/tui/compat.py +111 -0
  78. network_toolkit/tui/constants.py +111 -0
  79. network_toolkit/tui/controller.py +550 -0
  80. network_toolkit/tui/data.py +149 -0
  81. network_toolkit/tui/dialogs.py +196 -0
  82. network_toolkit/tui/helpers.py +55 -0
  83. network_toolkit/tui/keymap.py +31 -0
  84. network_toolkit/tui/layout.py +111 -0
  85. network_toolkit/tui/models.py +93 -0
  86. network_toolkit/tui/output_manager.py +372 -0
  87. network_toolkit/tui/prompt.py +172 -0
  88. network_toolkit/tui/services.py +285 -0
  89. networka-0.1.9.dist-info/METADATA +316 -0
  90. networka-0.1.9.dist-info/RECORD +93 -0
  91. networka-0.1.9.dist-info/WHEEL +4 -0
  92. networka-0.1.9.dist-info/entry_points.txt +2 -0
  93. networka-0.1.9.dist-info/licenses/LICENSE +73 -0
@@ -0,0 +1,4 @@
1
+ # SPDX-FileCopyrightText: 2025-present Network Team <network@company.com>
2
+ #
3
+ # SPDX-License-Identifier: MIT
4
+ __version__ = "0.1.9"
@@ -0,0 +1,8 @@
1
+ # SPDX-FileCopyrightText: 2025-present Network Team <network@company.com>
2
+ #
3
+ # SPDX-License-Identifier: MIT
4
+ """Network Toolkit - Network automation made simple for MikroTik (and beyond)."""
5
+
6
+ from network_toolkit.__about__ import __version__
7
+
8
+ __all__ = ["__version__"]
@@ -0,0 +1,10 @@
1
+ #!/usr/bin/env python3
2
+ # SPDX-FileCopyrightText: 2025-present Network Team <network@company.com>
3
+ #
4
+ # SPDX-License-Identifier: MIT
5
+ """Main entry point for the network toolkit CLI when run as a module."""
6
+
7
+ from network_toolkit.cli import app
8
+
9
+ if __name__ == "__main__":
10
+ app()
@@ -0,0 +1,53 @@
1
+ # Built-in Arista EOS Command Sequences
2
+ sequences:
3
+ system_info:
4
+ description: "Complete system information gathering"
5
+ category: "information"
6
+ timeout: 60
7
+ commands:
8
+ - "show version"
9
+ - "show inventory"
10
+ - "show clock"
11
+ - "show environment"
12
+ - "show processes top once"
13
+
14
+ health_check:
15
+ description: "Basic health check for device monitoring"
16
+ category: "monitoring"
17
+ timeout: 45
18
+ commands:
19
+ - "show processes top once"
20
+ - "show memory"
21
+ - "show clock"
22
+ - "show interfaces status"
23
+ - "show logging last 10"
24
+
25
+ interface_status:
26
+ description: "Detailed interface status and statistics"
27
+ category: "network"
28
+ timeout: 60
29
+ commands:
30
+ - "show interfaces status"
31
+ - "show interfaces counters"
32
+ - "show interfaces description"
33
+ - "show interfaces transceiver details"
34
+
35
+ routing_info:
36
+ description: "Routing table and protocol information"
37
+ category: "network"
38
+ timeout: 60
39
+ commands:
40
+ - "show ip route"
41
+ - "show ip ospf neighbor"
42
+ - "show ip bgp summary"
43
+ - "show bfd neighbors"
44
+
45
+ security_audit:
46
+ description: "Security configuration audit"
47
+ category: "security"
48
+ timeout: 120
49
+ commands:
50
+ - "show running-config section username"
51
+ - "show aaa"
52
+ - "show ip access-lists"
53
+ - "show logging"
@@ -0,0 +1,52 @@
1
+ # Built-in MikroTik RouterOS Command Sequences
2
+ sequences:
3
+ system_info:
4
+ description: "Complete system information gathering"
5
+ category: "information"
6
+ timeout: 60
7
+ commands:
8
+ - "/system/identity/print"
9
+ - "/system/resource/print"
10
+ - "/system/routerboard/print"
11
+ - "/system/clock/print"
12
+ - "/system/package/print"
13
+
14
+ health_check:
15
+ description: "Basic health check for device monitoring"
16
+ category: "monitoring"
17
+ timeout: 45
18
+ commands:
19
+ - "/system/resource/print"
20
+ - "/system/clock/print"
21
+ - "/interface/print detail"
22
+ - '/log/print where topics~"error|critical|warning"'
23
+
24
+ interface_status:
25
+ description: "Detailed interface status and statistics"
26
+ category: "network"
27
+ timeout: 60
28
+ commands:
29
+ - "/interface/print detail"
30
+ - "/interface/ethernet/print detail"
31
+ - "/interface/ethernet/monitor [find] once"
32
+
33
+ routing_info:
34
+ description: "Routing table and protocol information"
35
+ category: "network"
36
+ timeout: 60
37
+ commands:
38
+ - "/ip/route/print detail"
39
+ - "/routing/ospf/neighbor/print"
40
+ - "/routing/bgp/peer/print terse"
41
+
42
+ security_audit:
43
+ description: "Security configuration audit"
44
+ category: "security"
45
+ timeout: 120
46
+ commands:
47
+ - "/user/print"
48
+ - "/user/group/print"
49
+ - "/ip/service/print"
50
+ - "/ip/firewall/filter/print"
51
+ - "/ip/firewall/nat/print"
52
+ - '/log/print where topics~"account|critical|error|warning"'
network_toolkit/cli.py ADDED
@@ -0,0 +1,265 @@
1
+ # SPDX-FileCopyrightText: 2025-present Network Team <network@company.com>
2
+ #
3
+ # SPDX-License-Identifier: MIT
4
+ """Command-line interface for the network toolkit (modularized)."""
5
+
6
+ from __future__ import annotations
7
+
8
+ import datetime
9
+ from pathlib import Path
10
+ from typing import Annotated, Any
11
+
12
+ import typer
13
+ from typer.core import TyperGroup
14
+ from typer.main import get_command as _get_click_command
15
+
16
+ from network_toolkit import __version__
17
+
18
+ # Command registration: import command factories that attach to `app`
19
+ # Each module defines a `register(app)` function that adds its commands.
20
+ from network_toolkit.commands.backup import register as register_backup
21
+ from network_toolkit.commands.complete import register as register_complete
22
+ from network_toolkit.commands.config import register as register_config
23
+ from network_toolkit.commands.diff import register as register_diff
24
+ from network_toolkit.commands.download import register as register_download
25
+ from network_toolkit.commands.firmware import register as register_firmware
26
+ from network_toolkit.commands.info import register as register_info
27
+ from network_toolkit.commands.list import register as register_list
28
+ from network_toolkit.commands.run import register as register_run
29
+ from network_toolkit.commands.schema_unified import register as register_schema
30
+ from network_toolkit.commands.ssh import register as register_ssh
31
+ from network_toolkit.commands.upload import register as register_upload
32
+ from network_toolkit.common.logging import setup_logging
33
+ from network_toolkit.common.output import get_output_manager
34
+ from network_toolkit.config import NetworkConfig
35
+
36
+
37
+ class _DynamicConsoleProxy:
38
+ """Proxy that forwards attribute access to the current OutputManager console.
39
+
40
+ This avoids capturing a stale Console at import time so that changes to the
41
+ output mode (e.g., via --output-mode or config) are reflected everywhere.
42
+ """
43
+
44
+ def __getattr__(self, name: str) -> Any:
45
+ return getattr(get_output_manager().console, name)
46
+
47
+
48
+ # Dynamic console that always reflects the active OutputManager
49
+ console = _DynamicConsoleProxy()
50
+
51
+ # Keep this import here to preserve tests that patch `network_toolkit.cli.DeviceSession`
52
+ from network_toolkit.device import DeviceSession as _DeviceSession # noqa: E402
53
+
54
+
55
+ # Preserve insertion order and group commands under a single Commands section
56
+ class CategorizedHelpGroup(TyperGroup):
57
+ def list_commands(self, ctx: Any) -> list[str]:
58
+ _ = ctx # unused
59
+ return list(self.commands)
60
+
61
+ def format_commands(self, ctx: Any, formatter: Any) -> None:
62
+ # Desired categories
63
+ exec_names = [
64
+ "run",
65
+ "ssh",
66
+ "diff",
67
+ "upload",
68
+ "download",
69
+ ]
70
+ vendor_names: list[str] = [
71
+ "backup",
72
+ "firmware",
73
+ ]
74
+ info_names = [
75
+ "info",
76
+ "list",
77
+ "config",
78
+ "schema",
79
+ ]
80
+
81
+ def rows(names: list[str]) -> list[tuple[str, str]]:
82
+ items: list[tuple[str, str]] = []
83
+ for name in names:
84
+ cmd = self.get_command(ctx, name)
85
+ if not cmd:
86
+ continue
87
+ # Prefer short help if available
88
+ short_getter = getattr(cmd, "get_short_help_str", None)
89
+ short_text = (
90
+ short_getter() if callable(short_getter) else (cmd.help or "")
91
+ )
92
+ items.append((name, str(short_text)))
93
+ return items
94
+
95
+ exec_rows = rows(exec_names)
96
+ vendor_rows = rows(vendor_names)
97
+ info_rows = rows(info_names)
98
+
99
+ if exec_rows:
100
+ formatter.write_text("\nRemote Operations")
101
+ formatter.write_dl(exec_rows)
102
+ if vendor_rows:
103
+ formatter.write_text("\nVendor-Specific Remote Operations")
104
+ formatter.write_dl(vendor_rows)
105
+ if info_rows:
106
+ formatter.write_text("\nInfo & Configuration")
107
+ formatter.write_dl(info_rows)
108
+
109
+
110
+ # Typer application instance
111
+ help_text = (
112
+ "\n Networka (nw)\n\n"
113
+ " A powerful multi-vendor CLI tool for automating network devices based "
114
+ "on ssh protocol.\n"
115
+ " Built with async/await support and type safety in mind.\n\n"
116
+ " QUICK START:\n"
117
+ " nw run sw-acc1 '/system/clock/print' # Execute command\n"
118
+ " nw run office_switches system_info # Run sequence on group\n\n"
119
+ " For detailed help on any command: nw <command> --help\n"
120
+ " Default config directory: system app config (use --config to override)\n "
121
+ )
122
+ app = typer.Typer(
123
+ name="nw",
124
+ help=help_text,
125
+ no_args_is_help=True,
126
+ rich_markup_mode="rich",
127
+ add_completion=False,
128
+ cls=CategorizedHelpGroup,
129
+ context_settings={"help_option_names": ["-h", "--help"]},
130
+ invoke_without_command=True,
131
+ )
132
+
133
+ # Click-compatible command is created after all subcommands are registered below
134
+
135
+
136
+ @app.callback()
137
+ def main(
138
+ ctx: typer.Context,
139
+ version: Annotated[
140
+ bool, typer.Option("--version", help="Show version information")
141
+ ] = False,
142
+ ) -> None:
143
+ """Configure global settings for the network toolkit."""
144
+ if version:
145
+ from network_toolkit.common.command_helpers import CommandContext
146
+
147
+ cmd_ctx = CommandContext()
148
+ cmd_ctx.print_info(f"Networka (nw) version {__version__}")
149
+ raise typer.Exit()
150
+
151
+ # If no command is invoked and no version flag, show help
152
+ if ctx.invoked_subcommand is None:
153
+ from network_toolkit.common.command_helpers import CommandContext
154
+
155
+ cmd_ctx = CommandContext()
156
+ cmd_ctx.output_manager.print_text(ctx.get_help())
157
+ raise typer.Exit()
158
+
159
+
160
+ # Expose DeviceSession symbol for tests to patch (`network_toolkit.cli.DeviceSession`)
161
+ DeviceSession = _DeviceSession
162
+
163
+
164
+ def _handle_file_downloads(
165
+ session: _DeviceSession,
166
+ config: NetworkConfig,
167
+ device_name: str,
168
+ download_files: list[dict[str, Any]],
169
+ ) -> dict[str, str]:
170
+ """Handle file downloads from a device session using centralized output.
171
+
172
+ Returns:
173
+ Dict mapping remote_file names to download status messages.
174
+ """
175
+ from network_toolkit.common.command_helpers import CommandContext
176
+
177
+ # Create a context for centralized output
178
+ ctx = CommandContext()
179
+
180
+ results: dict[str, str] = {}
181
+
182
+ def replace_placeholders(text: str) -> str:
183
+ now = datetime.datetime.now(datetime.UTC)
184
+ return (
185
+ text.replace("{date}", now.strftime("%Y%m%d"))
186
+ .replace("{time}", now.strftime("%H%M%S"))
187
+ .replace("{datetime}", now.strftime("%Y%m%d_%H%M%S"))
188
+ .replace("{device}", device_name)
189
+ )
190
+
191
+ def to_bool(val: Any) -> bool:
192
+ if isinstance(val, bool):
193
+ return val
194
+ if isinstance(val, str):
195
+ return val.lower() in ("true", "yes", "1", "on")
196
+ return bool(val)
197
+
198
+ default_dir = getattr(getattr(config, "general", object()), "backup_dir", ".")
199
+
200
+ for item in download_files:
201
+ remote_raw = item.get("remote_file", "") # could be empty per tests
202
+ remote_file = str(remote_raw)
203
+
204
+ local_path_val = item.get("local_path", default_dir)
205
+ local_path_str = str(local_path_val)
206
+ local_filename_val = item.get("local_filename", remote_file)
207
+ local_filename_str = str(local_filename_val)
208
+ delete_remote = to_bool(item.get("delete_remote", False))
209
+
210
+ # Placeholder replacement
211
+ local_dir = Path(replace_placeholders(local_path_str))
212
+ filename = replace_placeholders(local_filename_str)
213
+ destination = local_dir / filename
214
+
215
+ # Use centralized output system
216
+ ctx.output_manager.print_downloading(device_name, remote_file)
217
+
218
+ try:
219
+ success = session.download_file( # type: ignore[attr-defined]
220
+ remote_filename=remote_file,
221
+ local_path=destination,
222
+ delete_remote=delete_remote,
223
+ )
224
+ if success:
225
+ ctx.output_manager.print_success(
226
+ f"Downloaded {remote_file} to {destination}"
227
+ )
228
+ results[remote_file] = f"Downloaded to {destination}"
229
+ else:
230
+ ctx.output_manager.print_error(f"Failed to download {remote_file}")
231
+ results[remote_file] = "Download failed"
232
+ except Exception as e: # DeviceExecutionError or unexpected
233
+ ctx.output_manager.print_error(f"Error downloading {remote_file}: {e}")
234
+ results[remote_file] = f"Download error: {e}"
235
+
236
+ return results
237
+
238
+
239
+ # Register all commands with the Typer app
240
+ register_info(app)
241
+ register_list(app)
242
+ register_run(app)
243
+ register_config(app)
244
+ register_backup(app)
245
+ register_upload(app)
246
+ register_download(app)
247
+ register_firmware(app)
248
+ register_complete(app)
249
+ register_diff(app)
250
+ register_schema(app)
251
+ register_ssh(app)
252
+
253
+ # Expose a Click-compatible command for documentation tools (e.g., mkdocs-click)
254
+ # Create this after all subcommands have been registered
255
+ cli = _get_click_command(app)
256
+
257
+
258
+ __all__ = [
259
+ "DeviceSession",
260
+ "_handle_file_downloads",
261
+ "app",
262
+ "cli",
263
+ "console",
264
+ "setup_logging",
265
+ ]
@@ -0,0 +1,8 @@
1
+ # SPDX-FileCopyrightText: 2025-present Network Team <network@company.com>
2
+ #
3
+ # SPDX-License-Identifier: MIT
4
+ """Command modules for the Network Toolkit CLI.
5
+
6
+ Each module exposes a `register(app: typer.Typer) -> None` function
7
+ that attaches its command(s) to the shared Typer application.
8
+ """