netcmd 1.2.1__tar.gz → 1.2.2__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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: netcmd
3
- Version: 1.2.1
3
+ Version: 1.2.2
4
4
  Summary: Multivendor SSH CLI command runner with parallel and interactive workflows
5
5
  Author: jpesqueda
6
6
  Project-URL: Homepage, https://github.com/jpesqueda/NetCmd
@@ -23,7 +23,7 @@ Description-Content-Type: text/markdown
23
23
  Requires-Dist: netmiko<5,>=4.3
24
24
  Requires-Dist: rich<15,>=13.7
25
25
 
26
- # NetCmd v1.2.1
26
+ # NetCmd v1.2.2
27
27
 
28
28
  Multivendor SSH command runner for Windows and other Python 3.10+ systems. Netmiko and Rich. Executes commands on individual devices or in parallel (20 workers by default). Supports Cisco IOS-XE, NX-OS, Arista EOS, and other Netmiko drivers. Command syntax is device-specific.
29
29
 
@@ -146,3 +146,43 @@ py -m unittest discover -s tests -v
146
146
  ```
147
147
 
148
148
  Offline tests cover command transcript formatting, error categorization, empty-output suppression, interactive prompting, and test-connection mode. Live SSH integration must still be tested against representative devices before any production change.
149
+
150
+
151
+ ## V1.2.2 — Automatic CLI Mode Tracking
152
+
153
+ A command file can represent a full Cisco-style session, including
154
+ config t, TACACS configuration submodes, exit, end, and wr. NetCmd
155
+ waits for the final complete prompt after each command; for Cisco/Arista
156
+ drivers it detects failed config t/end transitions. No extra CLI flags.
157
+
158
+ Example tacacs_config.txt (documentation-only addresses/keys):
159
+
160
+ ```text
161
+ config t
162
+ tacacs server TACACS-NEW-01
163
+ address ipv4 192.0.2.10
164
+ key 0 REEMPLAZAR_CLAVE
165
+ exit
166
+ tacacs server TACACS-NEW-02
167
+ address ipv4 192.0.2.11
168
+ key 0 REEMPLAZAR_CLAVE
169
+ exit
170
+ aaa group server tacacs+ TACACS_NEW
171
+ server name TACACS-NEW-01
172
+ server name TACACS-NEW-02
173
+ exit
174
+ end
175
+ wr
176
+ ```
177
+
178
+ Run: `netcmd -hf hosts.txt -cmd tacacs_config.txt -u admin --suffix TACACS`
179
+
180
+ The default is mode exec, so the file itself should contain config t
181
+ when needed; do not also pass --mode config for this mixed file.
182
+
183
+ SAFETY: CLI result captures may expose secrets from commands.
184
+ Do not commit real TACACS keys or captured configuration outputs.
185
+ For AAA changes use a pilot switch, independent login verification,
186
+ out-of-band recovery and --on-error stop before changing a fleet.
187
+ Prompt recognition is best-effort on Cisco-like devices; device/firmware
188
+ behavior must be validated. This is not transactional rollback.
@@ -1,4 +1,4 @@
1
- # NetCmd v1.2.1
1
+ # NetCmd v1.2.2
2
2
 
3
3
  Multivendor SSH command runner for Windows and other Python 3.10+ systems. Netmiko and Rich. Executes commands on individual devices or in parallel (20 workers by default). Supports Cisco IOS-XE, NX-OS, Arista EOS, and other Netmiko drivers. Command syntax is device-specific.
4
4
 
@@ -121,3 +121,43 @@ py -m unittest discover -s tests -v
121
121
  ```
122
122
 
123
123
  Offline tests cover command transcript formatting, error categorization, empty-output suppression, interactive prompting, and test-connection mode. Live SSH integration must still be tested against representative devices before any production change.
124
+
125
+
126
+ ## V1.2.2 — Automatic CLI Mode Tracking
127
+
128
+ A command file can represent a full Cisco-style session, including
129
+ config t, TACACS configuration submodes, exit, end, and wr. NetCmd
130
+ waits for the final complete prompt after each command; for Cisco/Arista
131
+ drivers it detects failed config t/end transitions. No extra CLI flags.
132
+
133
+ Example tacacs_config.txt (documentation-only addresses/keys):
134
+
135
+ ```text
136
+ config t
137
+ tacacs server TACACS-NEW-01
138
+ address ipv4 192.0.2.10
139
+ key 0 REEMPLAZAR_CLAVE
140
+ exit
141
+ tacacs server TACACS-NEW-02
142
+ address ipv4 192.0.2.11
143
+ key 0 REEMPLAZAR_CLAVE
144
+ exit
145
+ aaa group server tacacs+ TACACS_NEW
146
+ server name TACACS-NEW-01
147
+ server name TACACS-NEW-02
148
+ exit
149
+ end
150
+ wr
151
+ ```
152
+
153
+ Run: `netcmd -hf hosts.txt -cmd tacacs_config.txt -u admin --suffix TACACS`
154
+
155
+ The default is mode exec, so the file itself should contain config t
156
+ when needed; do not also pass --mode config for this mixed file.
157
+
158
+ SAFETY: CLI result captures may expose secrets from commands.
159
+ Do not commit real TACACS keys or captured configuration outputs.
160
+ For AAA changes use a pilot switch, independent login verification,
161
+ out-of-band recovery and --on-error stop before changing a fleet.
162
+ Prompt recognition is best-effort on Cisco-like devices; device/firmware
163
+ behavior must be validated. This is not transactional rollback.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: netcmd
3
- Version: 1.2.1
3
+ Version: 1.2.2
4
4
  Summary: Multivendor SSH CLI command runner with parallel and interactive workflows
5
5
  Author: jpesqueda
6
6
  Project-URL: Homepage, https://github.com/jpesqueda/NetCmd
@@ -23,7 +23,7 @@ Description-Content-Type: text/markdown
23
23
  Requires-Dist: netmiko<5,>=4.3
24
24
  Requires-Dist: rich<15,>=13.7
25
25
 
26
- # NetCmd v1.2.1
26
+ # NetCmd v1.2.2
27
27
 
28
28
  Multivendor SSH command runner for Windows and other Python 3.10+ systems. Netmiko and Rich. Executes commands on individual devices or in parallel (20 workers by default). Supports Cisco IOS-XE, NX-OS, Arista EOS, and other Netmiko drivers. Command syntax is device-specific.
29
29
 
@@ -146,3 +146,43 @@ py -m unittest discover -s tests -v
146
146
  ```
147
147
 
148
148
  Offline tests cover command transcript formatting, error categorization, empty-output suppression, interactive prompting, and test-connection mode. Live SSH integration must still be tested against representative devices before any production change.
149
+
150
+
151
+ ## V1.2.2 — Automatic CLI Mode Tracking
152
+
153
+ A command file can represent a full Cisco-style session, including
154
+ config t, TACACS configuration submodes, exit, end, and wr. NetCmd
155
+ waits for the final complete prompt after each command; for Cisco/Arista
156
+ drivers it detects failed config t/end transitions. No extra CLI flags.
157
+
158
+ Example tacacs_config.txt (documentation-only addresses/keys):
159
+
160
+ ```text
161
+ config t
162
+ tacacs server TACACS-NEW-01
163
+ address ipv4 192.0.2.10
164
+ key 0 REEMPLAZAR_CLAVE
165
+ exit
166
+ tacacs server TACACS-NEW-02
167
+ address ipv4 192.0.2.11
168
+ key 0 REEMPLAZAR_CLAVE
169
+ exit
170
+ aaa group server tacacs+ TACACS_NEW
171
+ server name TACACS-NEW-01
172
+ server name TACACS-NEW-02
173
+ exit
174
+ end
175
+ wr
176
+ ```
177
+
178
+ Run: `netcmd -hf hosts.txt -cmd tacacs_config.txt -u admin --suffix TACACS`
179
+
180
+ The default is mode exec, so the file itself should contain config t
181
+ when needed; do not also pass --mode config for this mixed file.
182
+
183
+ SAFETY: CLI result captures may expose secrets from commands.
184
+ Do not commit real TACACS keys or captured configuration outputs.
185
+ For AAA changes use a pilot switch, independent login verification,
186
+ out-of-band recovery and --on-error stop before changing a fleet.
187
+ Prompt recognition is best-effort on Cisco-like devices; device/firmware
188
+ behavior must be validated. This is not transactional rollback.
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env python3
2
- """NetCmd v1.2.1: multivendor SSH command runner with interactive workflows.
2
+ """NetCmd v1.2.2: multivendor SSH command runner with interactive workflows.
3
3
 
4
4
  Designed for Windows / Python 3.10+. No third-party package is imported when
5
5
  showing --help, --version or validating an input file with --dry-run.
@@ -20,9 +20,14 @@ import threading
20
20
  import time
21
21
  from typing import Any
22
22
 
23
- VERSION = "1.2.1"
23
+ VERSION = "1.2.2"
24
24
  DEFAULT_TIMEOUT = 60.0
25
- PROMPT_PATTERN = re.compile(r"(?m)^\s*[^\r\n]{1,160}[#>$]\s*$")
25
+ # Cisco IOS-XE, NX-OS and EOS prompts, including all CLI submodes.
26
+ # Anchoring to a single final line avoids treating earlier output as the next prompt.
27
+ PROMPT_PATTERN = re.compile(r"[A-Za-z0-9_.:/@~-]+(?:\([^\r\n()]{1,80}\))*[>#%$]", re.ASCII)
28
+ CONFIG_MODES = re.compile(r"\((?:config|conf)(?:[-/][^()]*)?\)", re.I)
29
+ CONFIG_ENTER = re.compile(r"^(?:conf(?:igure)?(?:\s+(?:terminal|t))?|config\s+t)$", re.I)
30
+ CONFIG_LEAVE = re.compile(r"^(?:end|disable)$", re.I)
26
31
  ERROR_PATTERN = re.compile(
27
32
  r"(?im)^\s*(?:%\s*(?:invalid|error|incomplete|ambiguous|unknown|unrecognized|failed)|"
28
33
  r"error:\s|syntax error|invalid command|unknown command|command not found|"
@@ -387,11 +392,52 @@ def classify_connection_error(exc: BaseException) -> tuple[str, str]:
387
392
  return "SSH CONNECTION FAILED", detail
388
393
 
389
394
 
395
+ def extract_cli_prompt(text: str) -> str | None:
396
+ """Return the *final* standalone prompt, never an intermediate output line."""
397
+ lines = text.replace("\r\n", "\n").replace("\r", "\n").rstrip("\n").split("\n")
398
+ if not lines:
399
+ return None
400
+ candidate = lines[-1].strip()
401
+ return candidate if PROMPT_PATTERN.fullmatch(candidate) else None
402
+
403
+
404
+ def cli_mode(prompt: str) -> str:
405
+ """A Cisco-like mode hint. No vendor configuration commands are injected."""
406
+ return "config" if CONFIG_MODES.search(prompt) else "exec"
407
+
408
+
409
+ @dataclass
410
+ class CliModeTracker:
411
+ """Observe real prompts after every command and validate common transitions.
412
+
413
+ The device is authoritative: NetCmd never guesses or sends an extra end command.
414
+ Unknown vendor prompts are permitted as long as a complete prompt is read.
415
+ """
416
+ current_prompt: str
417
+ device_type: str
418
+
419
+ def observe(self, command: str, response: str) -> str:
420
+ next_prompt = extract_cli_prompt(response)
421
+ if not next_prompt:
422
+ raise CommandFailure("No complete CLI prompt after command; command outcome unknown")
423
+ previous_mode = cli_mode(self.current_prompt)
424
+ next_mode = cli_mode(next_prompt)
425
+ cmd = command.strip().lower()
426
+ # Validate mode transitions for the Cisco/Arista CLI family only.
427
+ # Other vendors keep prompt synchronization without Cisco semantics.
428
+ supported = self.device_type.startswith(("cisco_", "arista_"))
429
+ if supported and CONFIG_ENTER.fullmatch(cmd) and next_mode != "config":
430
+ raise CommandFailure(f"Configuration mode not entered (prompt: {next_prompt})")
431
+ if supported and CONFIG_LEAVE.fullmatch(cmd) and previous_mode == "config" and next_mode == "config":
432
+ raise CommandFailure(f"Configuration mode not exited (prompt: {next_prompt})")
433
+ self.current_prompt = next_prompt
434
+ return next_prompt
435
+
436
+
390
437
  def session_transcript(prompt: str, command: str, response: str) -> str:
391
- """One CLI-looking block: real prompt+command followed by captured output.
438
+ """Use the prompt captured before the command; omit the resulting prompt.
392
439
 
393
- Strip only an exact leading echoed command and final naked prompt. Do not
394
- throw away arbitrary CLI error text, or duplicate a command echo.
440
+ Never add an extra prompt line when the device switches to a new submode.
395
441
  """
396
442
  cleaned = response.replace("\r\n", "\n").replace("\r", "\n")
397
443
  lines = cleaned.split("\n")
@@ -400,11 +446,12 @@ def session_transcript(prompt: str, command: str, response: str) -> str:
400
446
  command_text = command.strip()
401
447
  if lines:
402
448
  first = lines[0].strip()
403
- if first == command_text or (prompt and first == prompt.strip() + command_text) or (prompt and first == prompt.strip() + " " + command_text):
449
+ if first == command_text or (prompt and first in (prompt.strip() + command_text, prompt.strip() + " " + command_text)):
404
450
  lines.pop(0)
405
451
  while lines and not lines[-1].strip():
406
452
  lines.pop()
407
- if lines and prompt and lines[-1].strip() == prompt.strip():
453
+ # The final prompt may differ from the prompt before the command!
454
+ if lines and extract_cli_prompt(lines[-1]):
408
455
  lines.pop()
409
456
  remainder = "\n".join(lines).strip("\n")
410
457
  title = f"{prompt.strip() if prompt else ''}{command_text}"
@@ -412,19 +459,22 @@ def session_transcript(prompt: str, command: str, response: str) -> str:
412
459
 
413
460
 
414
461
  def channel_read_until(connection: Any, pattern: str, timeout: float, *, quiet_prompt: bool = False) -> str:
415
- """Read raw SSH channel to a regex match; never send an unrequested answer."""
416
- compiled = re.compile(pattern, re.I | re.M)
462
+ """Wait until the last line is a CLI prompt (or a specific interactive regex)."""
463
+ compiled = None if quiet_prompt else re.compile(pattern, re.I | re.M)
417
464
  collected = ""
418
465
  until = time.monotonic() + timeout
419
466
  while time.monotonic() < until:
420
467
  chunk = connection.read_channel()
421
468
  if chunk:
422
469
  collected += chunk
423
- if compiled.search(collected):
470
+ if quiet_prompt:
471
+ if extract_cli_prompt(collected):
472
+ return collected
473
+ elif compiled and compiled.search(collected):
424
474
  return collected
425
475
  else:
426
476
  time.sleep(0.15)
427
- kind = "device prompt" if quiet_prompt else f"expected pattern {pattern!r}"
477
+ kind = "complete CLI prompt" if quiet_prompt else f"expected pattern {pattern!r}"
428
478
  raise CommandFailure(f"Timeout after {timeout:g}s waiting for {kind}; last output: {collected[-250:]!r}")
429
479
 
430
480
 
@@ -514,6 +564,7 @@ def device_worker(job: DeviceJob, args: Any, logger: logging.Logger, outpath: Pa
514
564
  return result
515
565
  if args.mode == "config":
516
566
  connection.config_mode()
567
+ tracker = CliModeTracker(connection.find_prompt().strip(), dtype)
517
568
  for step in job.steps:
518
569
  if isinstance(step, WaitStep):
519
570
  logger.info("%s | Wait %.1fs", job.host, step.seconds)
@@ -523,12 +574,18 @@ def device_worker(job: DeviceJob, args: Any, logger: logging.Logger, outpath: Pa
523
574
  logger.info("%s | Executing line=%d | %s", job.host, step.line, redact_command(step.command))
524
575
  start = time.perf_counter()
525
576
  try:
577
+ # Refresh from the live device; keeps state consistent with the channel.
526
578
  prompt = connection.find_prompt().strip()
579
+ tracker.current_prompt = prompt
527
580
  response, connection = run_command(connection, step, timeout, job.host, dtype, username, password, args)
528
581
  output_chunks.append(session_transcript(prompt, step.command, response).rstrip("\n") + "\n\n")
529
582
  reason = classify_command(step.command, response)
530
583
  if reason:
531
584
  raise CommandFailure(reason)
585
+ if step.wait_disconnect is not None:
586
+ tracker.current_prompt = connection.find_prompt().strip()
587
+ else:
588
+ tracker.observe(step.command, response)
532
589
  result.passed += 1
533
590
  logger.info("%s | PASS | %s | %.2fs", job.host, redact_command(step.command), time.perf_counter()-start)
534
591
  except Exception as exc:
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "netcmd"
7
- version = "1.2.1"
7
+ version = "1.2.2"
8
8
  description = "Multivendor SSH CLI command runner with parallel and interactive workflows"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.10"
@@ -1,4 +1,4 @@
1
- """Unit tests for NetCmd 1.2.1 without live network devices."""
1
+ """Unit tests for NetCmd 1.2.2 without live network devices."""
2
2
  from __future__ import annotations
3
3
  import contextlib
4
4
  import io
@@ -145,3 +145,44 @@ class NetCmdTests(TestCase):
145
145
 
146
146
 
147
147
  if __name__ == '__main__': main()
148
+
149
+
150
+ class CliTrackingTests(TestCase):
151
+ def test_submode_transitions(self):
152
+ tracker = netcmd.CliModeTracker('SW01#', 'cisco_ios')
153
+ fixtures = [
154
+ ('config t', 'SW01(config)#'),
155
+ ('tacacs server TACACS-NEW-01', 'SW01(config-server-tacacs)#'),
156
+ ('address ipv4 192.0.2.10', 'SW01(config-server-tacacs)#'),
157
+ ('exit', 'SW01(config)#'),
158
+ ('end', 'SW01#'),
159
+ ('wr', 'SW01#'),
160
+ ]
161
+ for cmd, after in fixtures:
162
+ before = tracker.current_prompt
163
+ payload = f'{cmd}\r\n{after}'
164
+ self.assertEqual(tracker.observe(cmd,payload),after)
165
+ self.assertEqual(netcmd.session_transcript(before,cmd,payload), f'{before}{cmd}\n')
166
+ self.assertEqual(tracker.current_prompt, 'SW01#')
167
+
168
+ def test_reject_failed_config_transition(self):
169
+ tracker = netcmd.CliModeTracker('SW01#','cisco_ios')
170
+ with self.assertRaisesRegex(netcmd.CommandFailure,'not entered'):
171
+ tracker.observe('config t','SW01#config t\r\nSW01#')
172
+
173
+ def test_reject_failed_end_transition(self):
174
+ tracker = netcmd.CliModeTracker('SW01(config)#','cisco_ios')
175
+ with self.assertRaisesRegex(netcmd.CommandFailure,'not exited'):
176
+ tracker.observe('end','SW01(config)#')
177
+
178
+ def test_no_premature_prompt_from_middle_of_output(self):
179
+ self.assertIsNone(netcmd.extract_cli_prompt('SW01#\nProcessing...'))
180
+ self.assertEqual(netcmd.extract_cli_prompt('SW01#\nProcessing...\nSW01(config)#'), 'SW01(config)#')
181
+
182
+ def test_multivendor_prompt_tracking_does_not_force_cisco_mode(self):
183
+ tracker=netcmd.CliModeTracker('device>', 'juniper_junos')
184
+ self.assertEqual(tracker.observe('configure', 'device#'),'device#')
185
+
186
+ def test_transcript_removes_new_submode_prompt(self):
187
+ raw='SW01#config t\r\nEnter configuration commands\r\nSW01(config)#'
188
+ self.assertEqual(netcmd.session_transcript('SW01#','config t',raw), 'SW01#config t\nEnter configuration commands\n')
File without changes