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,426 @@
1
+ # SPDX-License-Identifier: MIT
2
+ """Cisco IOS platform operations implementation."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import logging
7
+ import time
8
+ from pathlib import Path
9
+ from typing import TYPE_CHECKING
10
+
11
+ from network_toolkit.exceptions import DeviceConnectionError, DeviceExecutionError
12
+ from network_toolkit.platforms.base import PlatformOperations, UnsupportedOperationError
13
+ from network_toolkit.platforms.cisco_ios.constants import (
14
+ DEVICE_TYPES,
15
+ PLATFORM_NAME,
16
+ SUPPORTED_FIRMWARE_EXTENSIONS,
17
+ )
18
+
19
+ if TYPE_CHECKING:
20
+ pass
21
+
22
+ logger = logging.getLogger(__name__)
23
+
24
+
25
+ class CiscoIOSOperations(PlatformOperations):
26
+ """Cisco IOS specific operations implementation.
27
+
28
+ Implements firmware operations for traditional Cisco IOS using
29
+ monolithic images and boot system commands.
30
+ """
31
+
32
+ def firmware_upgrade(
33
+ self,
34
+ local_firmware_path: Path,
35
+ remote_filename: str | None = None,
36
+ verify_upload: bool = True,
37
+ verify_checksum: bool = True,
38
+ pre_reboot_delay: float = 3.0,
39
+ confirmation_timeout: float = 10.0,
40
+ ) -> bool:
41
+ """Upload Cisco IOS firmware and apply it using boot system workflow.
42
+
43
+ Implements the Cisco IOS firmware upgrade workflow:
44
+ 1. Enable file verification
45
+ 2. Transfer firmware using SCP
46
+ 3. Verify integrity if requested
47
+ 4. Configure boot system with new image
48
+ 5. Save configuration and reload
49
+
50
+ Parameters
51
+ ----------
52
+ local_firmware_path : Path
53
+ Path to the local firmware file (.bin or .tar)
54
+ remote_filename : str | None
55
+ Remote filename (default: same as local file)
56
+ verify_upload : bool
57
+ Verify file was uploaded successfully
58
+ verify_checksum : bool
59
+ Verify file integrity using checksums
60
+ pre_reboot_delay : float
61
+ Delay in seconds before rebooting
62
+ confirmation_timeout : float
63
+ Timeout for confirmation prompts
64
+
65
+ Returns
66
+ -------
67
+ bool
68
+ True if upgrade was initiated successfully
69
+ """
70
+ if not self.session._connected:
71
+ msg = "Device not connected"
72
+ raise DeviceConnectionError(msg)
73
+
74
+ # Validate firmware file extension
75
+ if local_firmware_path.suffix.lower() not in SUPPORTED_FIRMWARE_EXTENSIONS:
76
+ expected_exts = ", ".join(SUPPORTED_FIRMWARE_EXTENSIONS)
77
+ msg = f"Invalid firmware file for Cisco IOS. Expected {expected_exts}, got {local_firmware_path.suffix}"
78
+ raise ValueError(msg)
79
+
80
+ # Validate local firmware file
81
+ if not local_firmware_path.exists():
82
+ msg = f"Firmware file not found: {local_firmware_path}"
83
+ raise FileNotFoundError(msg)
84
+
85
+ if not local_firmware_path.is_file():
86
+ msg = f"Path is not a file: {local_firmware_path}"
87
+ raise FileNotFoundError(msg)
88
+
89
+ # Determine remote filename
90
+ remote_name = remote_filename or local_firmware_path.name
91
+
92
+ logger.warning(
93
+ f"🚨 CISCO IOS FIRMWARE UPGRADE INITIATED on {self.session.device_name}!"
94
+ )
95
+ logger.warning(f" Firmware file: {local_firmware_path}")
96
+ logger.warning(f" Remote name: {remote_name}")
97
+ logger.warning(" This will RELOAD the device!")
98
+
99
+ try:
100
+ # Step 1: Enable file verification
101
+ logger.info("Step 1/5: Enabling file verification")
102
+ try:
103
+ self.session.execute_command("file verify auto")
104
+ logger.info("OK File verification enabled")
105
+ except DeviceExecutionError as e:
106
+ logger.warning(f"Could not enable file verification: {e}")
107
+
108
+ # Step 2: Check current state and flash space
109
+ logger.info("Step 2/5: Checking device state and flash space")
110
+ try:
111
+ version_output = self.session.execute_command("show version")
112
+ logger.debug(f"Current version: {version_output}")
113
+
114
+ boot_output = self.session.execute_command("show boot")
115
+ logger.debug(f"Current boot config: {boot_output}")
116
+
117
+ flash_output = self.session.execute_command("dir flash:")
118
+ logger.debug(f"Flash contents: {flash_output}")
119
+
120
+ except DeviceExecutionError as e:
121
+ logger.warning(f"Could not check device state: {e}")
122
+
123
+ # Step 3: Upload the firmware file
124
+ logger.info(f"Step 3/5: Uploading firmware file {local_firmware_path.name}")
125
+ upload_success = self.session.upload_file(
126
+ local_path=local_firmware_path,
127
+ remote_filename=remote_filename,
128
+ verify_upload=verify_upload,
129
+ verify_checksum=verify_checksum,
130
+ )
131
+
132
+ if not upload_success:
133
+ msg = f"Firmware file upload failed to {self.session.device_name}"
134
+ raise DeviceExecutionError(
135
+ msg,
136
+ details={"reason": "Upload verification failed"},
137
+ )
138
+
139
+ logger.info("OK Firmware file uploaded successfully")
140
+
141
+ # Step 4: Configure boot system for new firmware
142
+ logger.info("Step 4/5: Configuring boot system")
143
+ try:
144
+ # Configure boot system using monolithic image workflow
145
+ config_commands = [
146
+ "configure terminal",
147
+ "no boot system", # Clear existing boot commands
148
+ f"boot system flash:{remote_name}", # Set new primary boot image
149
+ "end",
150
+ "write memory", # Save configuration
151
+ ]
152
+
153
+ for cmd in config_commands:
154
+ logger.debug(f"Executing: {cmd}")
155
+ result = self.session.execute_command(cmd)
156
+ logger.debug(f"Result: {result}")
157
+
158
+ logger.info("OK Boot system configured")
159
+
160
+ except DeviceExecutionError as e:
161
+ msg = f"Failed to configure boot system: {e}"
162
+ raise DeviceExecutionError(msg) from e
163
+
164
+ # Step 5: Reload the device
165
+ logger.warning(f"Step 5/5: Reloading device in {pre_reboot_delay}s...")
166
+ logger.warning("🚨 DEVICE WILL LOSE CONNECTION AND RELOAD! 🚨")
167
+
168
+ time.sleep(pre_reboot_delay)
169
+
170
+ try:
171
+ logger.info("Sending reload command...")
172
+ response = self.session._transport.send_interactive( # type: ignore[union-attr]
173
+ interact_events=[
174
+ (
175
+ "reload",
176
+ "Proceed with reload? [confirm]",
177
+ True,
178
+ ),
179
+ (
180
+ "", # Just press enter to confirm
181
+ "",
182
+ False,
183
+ ),
184
+ ],
185
+ timeout_ops=confirmation_timeout,
186
+ )
187
+
188
+ logger.info(f"Reload command executed: {response}")
189
+ logger.warning("🚨 CISCO IOS DEVICE RELOADING WITH NEW FIRMWARE!")
190
+
191
+ self.session._connected = False
192
+ return True
193
+
194
+ except Exception as e:
195
+ # Device might disconnect immediately, which is expected
196
+ error_str = str(e).lower()
197
+ if any(
198
+ phrase in error_str
199
+ for phrase in [
200
+ "connection",
201
+ "disconnect",
202
+ "timeout",
203
+ "closed",
204
+ "eof",
205
+ ]
206
+ ):
207
+ logger.info(f"Device disconnected during reload (expected): {e}")
208
+ logger.warning("🚨 CISCO IOS DEVICE RELOADING WITH NEW FIRMWARE!")
209
+ self.session._connected = False
210
+ return True
211
+ else:
212
+ logger.error(f"Unexpected error during reload: {e}")
213
+ msg = f"Reload command failed: {e}"
214
+ raise DeviceConnectionError(msg) from e
215
+
216
+ except Exception as e:
217
+ logger.error(f"Cisco IOS firmware upgrade failed: {e}")
218
+ raise
219
+
220
+ def firmware_downgrade(
221
+ self,
222
+ local_firmware_path: Path,
223
+ remote_filename: str | None = None,
224
+ verify_upload: bool = True,
225
+ verify_checksum: bool = True,
226
+ confirmation_timeout: float = 10.0,
227
+ ) -> bool:
228
+ """Downgrade Cisco IOS firmware using same workflow as upgrade.
229
+
230
+ Parameters
231
+ ----------
232
+ local_firmware_path : Path
233
+ Path to the local firmware file (older version)
234
+ remote_filename : str | None
235
+ Remote filename (default: same as local file)
236
+ verify_upload : bool
237
+ Verify file was uploaded successfully
238
+ verify_checksum : bool
239
+ Verify file integrity using checksums
240
+ confirmation_timeout : float
241
+ Timeout for confirmation prompts
242
+
243
+ Returns
244
+ -------
245
+ bool
246
+ True if downgrade was initiated successfully
247
+ """
248
+ # Downgrade uses the same process as upgrade for IOS
249
+ logger.info("Initiating Cisco IOS firmware downgrade (same process as upgrade)")
250
+ return self.firmware_upgrade(
251
+ local_firmware_path=local_firmware_path,
252
+ remote_filename=remote_filename,
253
+ verify_upload=verify_upload,
254
+ verify_checksum=verify_checksum,
255
+ pre_reboot_delay=3.0,
256
+ confirmation_timeout=confirmation_timeout,
257
+ )
258
+
259
+ def bios_upgrade(
260
+ self,
261
+ pre_reboot_delay: float = 3.0,
262
+ confirmation_timeout: float = 10.0,
263
+ verify_before: bool = True,
264
+ ) -> bool:
265
+ """BIOS upgrade is not applicable for Cisco IOS devices."""
266
+ raise UnsupportedOperationError(PLATFORM_NAME, "bios_upgrade")
267
+
268
+ def create_backup(
269
+ self,
270
+ backup_sequence: list[str],
271
+ download_files: list[dict[str, str]] | None = None,
272
+ ) -> bool:
273
+ """Create Cisco IOS device backup using platform-specific commands.
274
+
275
+ Parameters
276
+ ----------
277
+ backup_sequence : list[str]
278
+ List of Cisco IOS commands to execute for backup
279
+ download_files : list[dict[str, str]] | None
280
+ Optional list of files to download after backup
281
+
282
+ Returns
283
+ -------
284
+ bool
285
+ True if backup was created successfully
286
+ """
287
+ if not self.session.is_connected:
288
+ msg = "Device not connected"
289
+ raise DeviceConnectionError(msg)
290
+
291
+ # Use provided sequence or fall back to default IOS backup sequence
292
+ if not backup_sequence:
293
+ backup_sequence = ["show running-config"]
294
+
295
+ logger.info(f"Creating Cisco IOS backup on {self.session.device_name}")
296
+
297
+ try:
298
+ # Execute backup commands
299
+ for cmd in backup_sequence:
300
+ logger.debug(f"Executing backup command: {cmd}")
301
+ self.session.execute_command(cmd)
302
+
303
+ logger.info("OK Cisco IOS backup commands executed successfully")
304
+ return True
305
+
306
+ except DeviceExecutionError as e:
307
+ logger.error(f"Cisco IOS backup failed: {e}")
308
+ raise
309
+
310
+ def config_backup(
311
+ self,
312
+ backup_sequence: list[str],
313
+ download_files: list[dict[str, str]] | None = None,
314
+ ) -> bool:
315
+ """Create Cisco IOS configuration backup using platform-specific commands.
316
+
317
+ This operation creates a text representation of the Cisco IOS configuration
318
+ using show commands.
319
+
320
+ Parameters
321
+ ----------
322
+ backup_sequence : list[str]
323
+ List of Cisco IOS commands to execute for configuration backup
324
+ download_files : list[dict[str, str]] | None
325
+ Optional list of files to download after backup
326
+
327
+ Returns
328
+ -------
329
+ bool
330
+ True if configuration backup was created successfully
331
+ """
332
+ if not self.session.is_connected:
333
+ msg = "Device not connected"
334
+ raise DeviceConnectionError(msg)
335
+
336
+ # Use provided sequence or fall back to default config backup
337
+ if not backup_sequence:
338
+ backup_sequence = ["show running-config"]
339
+
340
+ logger.info(
341
+ f"Creating Cisco IOS configuration backup on {self.session.device_name}"
342
+ )
343
+
344
+ try:
345
+ # Execute configuration backup commands
346
+ for cmd in backup_sequence:
347
+ logger.debug(f"Executing config backup command: {cmd}")
348
+ self.session.execute_command(cmd)
349
+
350
+ logger.info(
351
+ "OK Cisco IOS configuration backup commands executed successfully"
352
+ )
353
+ return True
354
+
355
+ except DeviceExecutionError as e:
356
+ logger.error(f"Cisco IOS configuration backup failed: {e}")
357
+ raise
358
+
359
+ def backup(
360
+ self,
361
+ backup_sequence: list[str],
362
+ download_files: list[dict[str, str]] | None = None,
363
+ ) -> bool:
364
+ """Create comprehensive Cisco IOS backup using platform-specific commands.
365
+
366
+ This operation creates both configuration and system information backups
367
+ of the Cisco IOS device.
368
+
369
+ Parameters
370
+ ----------
371
+ backup_sequence : list[str]
372
+ List of Cisco IOS commands to execute for comprehensive backup
373
+ download_files : list[dict[str, str]] | None
374
+ Optional list of files to download after backup
375
+
376
+ Returns
377
+ -------
378
+ bool
379
+ True if comprehensive backup was created successfully
380
+ """
381
+ if not self.session.is_connected:
382
+ msg = "Device not connected"
383
+ raise DeviceConnectionError(msg)
384
+
385
+ # Use provided sequence or fall back to comprehensive backup
386
+ if not backup_sequence:
387
+ backup_sequence = [
388
+ "show running-config",
389
+ "show startup-config",
390
+ "show version",
391
+ "show inventory",
392
+ ]
393
+
394
+ logger.info(
395
+ f"Creating comprehensive Cisco IOS backup on {self.session.device_name}"
396
+ )
397
+
398
+ try:
399
+ # Execute comprehensive backup commands
400
+ for cmd in backup_sequence:
401
+ logger.debug(f"Executing backup command: {cmd}")
402
+ self.session.execute_command(cmd)
403
+
404
+ logger.info(
405
+ "OK Cisco IOS comprehensive backup commands executed successfully"
406
+ )
407
+ return True
408
+
409
+ except DeviceExecutionError as e:
410
+ logger.error(f"Cisco IOS comprehensive backup failed: {e}")
411
+ raise
412
+
413
+ @classmethod
414
+ def get_supported_file_extensions(cls) -> list[str]:
415
+ """Get list of supported firmware file extensions for Cisco IOS."""
416
+ return SUPPORTED_FIRMWARE_EXTENSIONS.copy()
417
+
418
+ @classmethod
419
+ def get_platform_name(cls) -> str:
420
+ """Get human-readable platform name."""
421
+ return PLATFORM_NAME
422
+
423
+ @classmethod
424
+ def get_device_types(cls) -> list[str]:
425
+ """Get list of device types supported by this platform."""
426
+ return DEVICE_TYPES.copy()
@@ -0,0 +1,6 @@
1
+ # SPDX-License-Identifier: MIT
2
+ """Cisco IOS-XE platform implementation."""
3
+
4
+ from network_toolkit.platforms.cisco_iosxe.operations import CiscoIOSXEOperations
5
+
6
+ __all__ = ["CiscoIOSXEOperations"]
@@ -0,0 +1,15 @@
1
+ # SPDX-License-Identifier: MIT
2
+ """Cisco IOS-XE platform constants."""
3
+
4
+ # File extensions supported by Cisco IOS-XE
5
+ SUPPORTED_FIRMWARE_EXTENSIONS = [".bin", ".pkg"]
6
+
7
+ # Platform information
8
+ PLATFORM_NAME = "Cisco IOS-XE"
9
+ DEVICE_TYPES = ["cisco_iosxe"]
10
+
11
+ # Default backup sequence commands (example - not implemented)
12
+ DEFAULT_BACKUP_SEQUENCE = [
13
+ "show running-config",
14
+ "show startup-config",
15
+ ]