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,377 @@
1
+ # SPDX-License-Identifier: MIT
2
+ """`nw info` command implementation."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import os
7
+ from pathlib import Path
8
+ from typing import TYPE_CHECKING, Annotated
9
+
10
+ import typer
11
+
12
+ from network_toolkit.common.command_helpers import CommandContext
13
+ from network_toolkit.common.credentials import (
14
+ InteractiveCredentials,
15
+ prompt_for_credentials,
16
+ )
17
+ from network_toolkit.common.defaults import DEFAULT_CONFIG_PATH
18
+ from network_toolkit.common.logging import setup_logging
19
+ from network_toolkit.common.output import OutputMode
20
+ from network_toolkit.common.table_generator import BaseTableProvider
21
+ from network_toolkit.common.table_providers import (
22
+ DeviceInfoTableProvider,
23
+ DeviceTypesInfoTableProvider,
24
+ GlobalSequenceInfoTableProvider,
25
+ GroupInfoTableProvider,
26
+ TransportTypesTableProvider,
27
+ VendorSequenceInfoTableProvider,
28
+ )
29
+ from network_toolkit.config import load_config
30
+ from network_toolkit.credentials import EnvironmentCredentialManager
31
+ from network_toolkit.exceptions import NetworkToolkitError
32
+ from network_toolkit.sequence_manager import SequenceManager
33
+
34
+ if TYPE_CHECKING:
35
+ from network_toolkit.config import NetworkConfig
36
+
37
+
38
+ def register(app: typer.Typer) -> None:
39
+ @app.command(rich_help_panel="Info & Configuration")
40
+ def info(
41
+ targets: Annotated[
42
+ str,
43
+ typer.Argument(
44
+ help="Comma-separated device/group/sequence names from configuration"
45
+ ),
46
+ ],
47
+ config_file: Annotated[
48
+ Path,
49
+ typer.Option("--config", "-c", help="Configuration directory or file path"),
50
+ ] = DEFAULT_CONFIG_PATH,
51
+ output_mode: Annotated[
52
+ OutputMode | None,
53
+ typer.Option(
54
+ "--output-mode",
55
+ "-o",
56
+ help="Output decoration mode: default, light, dark, no-color, raw",
57
+ show_default=False,
58
+ ),
59
+ ] = None,
60
+ verbose: Annotated[
61
+ bool, typer.Option("--verbose", "-v", help="Enable verbose logging")
62
+ ] = False,
63
+ interactive_auth: Annotated[
64
+ bool,
65
+ typer.Option(
66
+ "--interactive-auth",
67
+ "-i",
68
+ help="Prompt for username and password interactively",
69
+ ),
70
+ ] = False,
71
+ ) -> None:
72
+ """
73
+ Show comprehensive information for devices, groups, or sequences.
74
+
75
+ Supports comma-separated device names, group names, and sequence names.
76
+
77
+ Examples:
78
+ - nw info sw-acc1 # Show device info
79
+ - nw info sw-acc1,sw-acc2 # Show multiple devices
80
+ - nw info access_switches # Show group info
81
+ - nw info system_info # Show sequence info
82
+ - nw info sw-acc1,access_switches,health_check # Mixed types
83
+ """
84
+ setup_logging("DEBUG" if verbose else "INFO")
85
+
86
+ # Resolve default config path: if user passed the literal default 'config'
87
+ # and it doesn't exist, fall back to the OS default config dir.
88
+ cfg_path = Path(config_file)
89
+ if str(cfg_path) == "config" and not cfg_path.exists():
90
+ from network_toolkit.common.paths import default_modular_config_dir
91
+
92
+ cfg_path = default_modular_config_dir()
93
+
94
+ # Use CommandContext for consistent output management
95
+ ctx = CommandContext(
96
+ config_file=cfg_path,
97
+ verbose=verbose,
98
+ output_mode=output_mode,
99
+ )
100
+
101
+ try:
102
+ config = load_config(cfg_path)
103
+
104
+ # Handle interactive authentication if requested
105
+ interactive_creds = None
106
+ if interactive_auth:
107
+ ctx.print_warning("Interactive authentication mode enabled")
108
+ interactive_creds = prompt_for_credentials(
109
+ "Enter username for devices",
110
+ "Enter password for devices",
111
+ "admin", # Default username suggestion
112
+ )
113
+ ctx.print_info(f"Will use username: {interactive_creds.username}")
114
+
115
+ # Parse targets and determine types
116
+ target_list = [t.strip() for t in targets.split(",") if t.strip()]
117
+ if not target_list:
118
+ ctx.print_error("Error: No targets specified")
119
+ raise typer.Exit(1) from None
120
+
121
+ # Process each target
122
+ known_count = 0
123
+ unknown_count = 0
124
+ for i, target in enumerate(target_list):
125
+ if i > 0:
126
+ ctx.print_blank_line()
127
+
128
+ target_type = _determine_target_type(target, config)
129
+
130
+ if target_type == "device":
131
+ _show_device_info(target, config, ctx, interactive_creds, verbose)
132
+ known_count += 1
133
+ elif target_type == "group":
134
+ _show_group_info(target, config, ctx)
135
+ known_count += 1
136
+ elif target_type == "sequence":
137
+ _show_sequence_info(target, config, ctx, verbose)
138
+ known_count += 1
139
+ else:
140
+ # Unknown targets should not cause a non-zero exit; warn and continue
141
+ ctx.print_warning(f"Unknown target: {target}")
142
+ unknown_count += 1
143
+ continue
144
+
145
+ # If nothing was recognized and config is not empty, treat as error
146
+ if known_count == 0 and unknown_count > 0:
147
+ has_devices = bool(getattr(config, "devices", None))
148
+ has_groups = bool(getattr(config, "device_groups", None))
149
+ has_global_seq = bool(getattr(config, "global_command_sequences", None))
150
+ # Inspect vendor sequences to determine if repository provides any
151
+ sm = SequenceManager(config)
152
+ all_vendor_sequences = sm.list_all_sequences()
153
+ has_vendor_sequences = any(
154
+ bool(v) for v in all_vendor_sequences.values()
155
+ )
156
+
157
+ has_any_definitions = (
158
+ has_devices or has_groups or has_global_seq or has_vendor_sequences
159
+ )
160
+
161
+ if has_any_definitions:
162
+ # Heuristic: treat a single unknown token that doesn't look like a
163
+ # plural/group name as an error (covers "invalid device" CLI test),
164
+ # otherwise keep it as a warning-only to avoid false positives.
165
+ if len(target_list) == 1 and not target_list[0].endswith("s"):
166
+ raise typer.Exit(1) from None
167
+
168
+ except NetworkToolkitError as e:
169
+ ctx.print_error(f"Error: {e.message}")
170
+ if verbose and e.details:
171
+ ctx.print_error(f"Details: {e.details}")
172
+ raise typer.Exit(1) from None
173
+ except typer.Exit:
174
+ # Allow clean exits (e.g., user cancellation) to pass through
175
+ raise
176
+ except Exception as e: # pragma: no cover - unexpected
177
+ ctx.print_error(f"Unexpected error: {e}")
178
+ raise typer.Exit(1) from None
179
+
180
+
181
+ def _show_supported_types_impl(ctx: CommandContext, verbose: bool) -> None:
182
+ """Implementation logic for showing supported device types."""
183
+ # Show transport types first
184
+ transport_provider = TransportTypesTableProvider()
185
+ ctx.render_table(transport_provider, False)
186
+
187
+ ctx.print_blank_line()
188
+
189
+ # Show supported device types
190
+ device_types_provider = DeviceTypesInfoTableProvider()
191
+ ctx.render_table(device_types_provider, verbose)
192
+
193
+ if verbose:
194
+ # Show usage examples
195
+ ctx.print_usage_examples_header()
196
+ examples_text = """ # Use in device configuration:
197
+ devices:
198
+ my_device:
199
+ host: 192.168.1.1
200
+ device_type: mikrotik_routeros
201
+ transport_type: scrapli # Optional, defaults to scrapli
202
+
203
+ # Use with IP addresses:
204
+ nw run 192.168.1.1 "/system/identity/print" --platform mikrotik_routeros
205
+
206
+ # Transport selection via config:
207
+ general:
208
+ default_transport_type: scrapli"""
209
+ ctx.print_code_block(examples_text)
210
+
211
+
212
+ def _determine_target_type(target: str, config: NetworkConfig) -> str:
213
+ """Determine if target is a device, group, or sequence."""
214
+ # Check if it's a device
215
+ if config.devices and target in config.devices:
216
+ return "device"
217
+
218
+ # Check if it's a group
219
+ if config.device_groups and target in config.device_groups:
220
+ return "group"
221
+
222
+ # Check if it's a global sequence
223
+ if config.global_command_sequences and target in config.global_command_sequences:
224
+ return "sequence"
225
+
226
+ # Check if it's a vendor sequence
227
+ sm = SequenceManager(config)
228
+ all_sequences = sm.list_all_sequences()
229
+ for vendor_sequences in all_sequences.values():
230
+ if target in vendor_sequences:
231
+ return "sequence"
232
+
233
+ return "unknown"
234
+
235
+
236
+ def _show_device_info(
237
+ device: str,
238
+ config: NetworkConfig,
239
+ ctx: CommandContext,
240
+ interactive_creds: InteractiveCredentials | None,
241
+ verbose: bool,
242
+ ) -> None:
243
+ """Show detailed information for a device."""
244
+ if not config.devices or device not in config.devices:
245
+ ctx.print_error(f"Error: Device '{device}' not found in configuration")
246
+ return
247
+
248
+ provider = DeviceInfoTableProvider(
249
+ config=config, device_name=device, interactive_creds=interactive_creds
250
+ )
251
+ ctx.render_table(provider, verbose)
252
+
253
+
254
+ def _show_group_info(target: str, config: NetworkConfig, ctx: CommandContext) -> None:
255
+ """Show detailed information for a group."""
256
+ if not config.device_groups or target not in config.device_groups:
257
+ ctx.print_error(f"Error: Group '{target}' not found in configuration")
258
+ return
259
+
260
+ provider = GroupInfoTableProvider(config=config, group_name=target)
261
+ ctx.render_table(provider, False)
262
+
263
+
264
+ def _show_sequence_info(
265
+ target: str, config: NetworkConfig, ctx: CommandContext, verbose: bool = False
266
+ ) -> None:
267
+ """Show detailed information for a sequence."""
268
+ provider: BaseTableProvider
269
+
270
+ # Check global sequences first
271
+ if config.global_command_sequences and target in config.global_command_sequences:
272
+ sequence = config.global_command_sequences[target]
273
+ provider = GlobalSequenceInfoTableProvider(
274
+ sequence_name=target, sequence=sequence, verbose=verbose
275
+ )
276
+ ctx.render_table(provider, verbose)
277
+ return
278
+
279
+ # Check vendor sequences
280
+ sm = SequenceManager(config)
281
+ all_sequences = sm.list_all_sequences()
282
+
283
+ # Find all vendors that implement this sequence
284
+ matching_vendors: list[str] = []
285
+ sequence_record = None
286
+
287
+ for vendor, vendor_sequences in all_sequences.items():
288
+ if target in vendor_sequences:
289
+ matching_vendors.append(vendor)
290
+ # Use the first matching sequence record as the template
291
+ # (they should be the same sequence across vendors)
292
+ if sequence_record is None:
293
+ sequence_record = vendor_sequences[target]
294
+
295
+ if sequence_record:
296
+ # Format vendor names for display
297
+ vendor_names = [vendor.replace("_", " ").title() for vendor in matching_vendors]
298
+
299
+ provider = VendorSequenceInfoTableProvider(
300
+ sequence_name=target,
301
+ sequence_record=sequence_record,
302
+ vendor_names=vendor_names,
303
+ verbose=verbose,
304
+ )
305
+ ctx.render_table(provider, verbose)
306
+ return
307
+
308
+ ctx.print_error(f"Error: Sequence '{target}' not found in configuration")
309
+
310
+
311
+ def _env_truthy(var_name: str) -> bool:
312
+ """Check if environment variable is truthy."""
313
+ val = os.getenv(var_name, "")
314
+ return val.strip().lower() in {"1", "true", "yes", "y", "on"}
315
+
316
+
317
+ def _get_credential_source(
318
+ device_name: str,
319
+ credential_type: str,
320
+ config: NetworkConfig,
321
+ interactive_auth: bool,
322
+ interactive_creds: InteractiveCredentials | None,
323
+ ) -> str:
324
+ """Get the source of a credential with exact file paths."""
325
+ # Check interactive override
326
+ if interactive_auth and interactive_creds:
327
+ if credential_type == "username" and interactive_creds.username:
328
+ return "interactive input"
329
+ if credential_type == "password" and interactive_creds.password:
330
+ return "interactive input"
331
+
332
+ # Check device config
333
+ dev = config.devices.get(device_name) if config.devices else None
334
+ if dev:
335
+ if credential_type == "username" and getattr(dev, "user", None):
336
+ return "device config file (config/devices/devices.yml)"
337
+ if credential_type == "password" and getattr(dev, "password", None):
338
+ return "device config file (config/devices/devices.yml)"
339
+
340
+ # Check device-specific environment variables
341
+ env_var_name = (
342
+ f"NW_{credential_type.upper()}_{device_name.upper().replace('-', '_')}"
343
+ )
344
+ if os.getenv(env_var_name):
345
+ return f"environment ({env_var_name})"
346
+
347
+ # Check group-level credentials
348
+ group_user, group_password = config.get_group_credentials(device_name)
349
+ target_credential = group_user if credential_type == "username" else group_password
350
+
351
+ if target_credential:
352
+ # Find which group provided the credential
353
+ device_groups = config.get_device_groups(device_name)
354
+ for group_name in device_groups:
355
+ group = (
356
+ config.device_groups.get(group_name) if config.device_groups else None
357
+ )
358
+ if group and group.credentials:
359
+ if credential_type == "username" and group.credentials.user:
360
+ return f"group config file config/groups/groups.yml ({group_name})"
361
+ elif credential_type == "password" and group.credentials.password:
362
+ return f"group config file config/groups/groups.yml ({group_name})"
363
+
364
+ # Check group environment variable
365
+ if EnvironmentCredentialManager.get_group_specific(
366
+ group_name, credential_type
367
+ ):
368
+ grp_env = f"NW_{credential_type.upper()}_{group_name.upper().replace('-', '_')}"
369
+ return f"environment ({grp_env})"
370
+
371
+ # Check default environment variables
372
+ default_env_var = f"NW_{credential_type.upper()}_DEFAULT"
373
+ if os.getenv(default_env_var):
374
+ return f"environment ({default_env_var})"
375
+
376
+ # Fallback to general config
377
+ return f"config (general.default_{credential_type})"