netcmd 1.2.0__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.
netcmd-1.2.0/PKG-INFO ADDED
@@ -0,0 +1,149 @@
1
+ Metadata-Version: 2.4
2
+ Name: netcmd
3
+ Version: 1.2.0
4
+ Summary: Multivendor SSH CLI command runner with parallel and interactive workflows
5
+ Author: jpesqueda
6
+ Project-URL: Homepage, https://github.com/jpesqueda/NetCmd
7
+ Project-URL: Repository, https://github.com/jpesqueda/NetCmd
8
+ Project-URL: Issues, https://github.com/jpesqueda/NetCmd/issues
9
+ Keywords: network automation,ssh,netmiko,cisco,arista,cli
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Environment :: Console
12
+ Classifier: Intended Audience :: System Administrators
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Topic :: System :: Networking
20
+ Classifier: Topic :: System :: Systems Administration
21
+ Requires-Python: >=3.10
22
+ Description-Content-Type: text/markdown
23
+ Requires-Dist: netmiko<5,>=4.3
24
+ Requires-Dist: rich<15,>=13.7
25
+
26
+ # NetCmd — Multivendor Network Command Runner
27
+
28
+ **Version 1.2.0** · Python 3.10+ · SSH / Netmiko
29
+
30
+ NetCmd executes CLI commands over SSH on a single network device or on multiple devices concurrently. It supports Cisco IOS/IOS-XE, NX-OS, Arista EOS, and other drivers supported by Netmiko. Interactive workflows can wait for CLI prompts, send responses, and reconnect after a planned reboot.
31
+
32
+ > **Safety:** Run disruptive workflows in a lab first. NetCmd sends commands that you provide; it does not independently prove that an upgrade is safe or successful.
33
+
34
+ ## Installation (Windows PowerShell)
35
+
36
+ ```powershell
37
+ py -m pip install -r requirements.txt
38
+ py netcmd.py --help
39
+ py netcmd.py --version
40
+ ```
41
+
42
+ ## Run commands
43
+
44
+ **Single device**
45
+
46
+ ```powershell
47
+ py netcmd.py -ho 192.0.2.11 -cmd examples/commands.txt -u admin -dt cisco_ios
48
+ ```
49
+
50
+ **Same commands on multiple devices**
51
+
52
+ ```powershell
53
+ py netcmd.py -hf examples/hosts.txt -cmd examples/commands.txt -u admin -dt cisco_ios -w 20
54
+ ```
55
+
56
+ **Different commands per device (Multifile)**
57
+
58
+ ```powershell
59
+ py netcmd.py -mf examples/multifile.txt -u admin -w 20
60
+ ```
61
+
62
+ **Preview without connecting**
63
+
64
+ ```powershell
65
+ py netcmd.py -mf examples/multifile.txt --dry-run
66
+ ```
67
+
68
+ **Customize result names**
69
+
70
+ ```powershell
71
+ py netcmd.py -mf examples/multifile.txt --prefix pre --suffix checks --timestamp -o Network_Audit
72
+ ```
73
+
74
+ ## Multifile input
75
+
76
+ ```text
77
+ HostName:192.0.2.11
78
+ DeviceType:cisco_ios
79
+ show version
80
+ show inventory
81
+ !
82
+
83
+ HostName:192.0.2.12
84
+ DeviceType:arista_eos
85
+ show version
86
+ show interfaces status
87
+ !
88
+ ```
89
+
90
+ Each device has its own command sequence. Repeated hostname blocks are combined in their original order. The `DeviceType:` directive overrides the CLI default driver. The host file and command file are used together in standard mode; `-mf` replaces both.
91
+
92
+ ## Interactive commands
93
+
94
+ The same directives work in `-cmd` and `-mf`.
95
+
96
+ ```text
97
+ @timeout 60
98
+ copy running-config startup-config
99
+ @expect Destination filename
100
+ @send [Enter]
101
+
102
+ @timeout 60
103
+ copy running-config bootflash:Config_2026_11_11
104
+ @expect Destination filename
105
+ @send [Enter]
106
+ ```
107
+
108
+ Available workflow directives: `@timeout`, `@expect`, `@send`, `@wait`, `@wait-disconnect`, `@reconnect`. An `@expect` must match before its corresponding `@send` is transmitted. `@send y` sends `y` plus Enter; `@send [Enter]` sends only Enter.
109
+
110
+ For a planned reboot, a sequence could include:
111
+
112
+ ```text
113
+ @wait-disconnect 300
114
+ @reconnect 900
115
+ ```
116
+
117
+ Verify CLI prompt wording and timeout values on your actual device platform before use. A reconnect alone does not validate upgrade success.
118
+
119
+ ## Output
120
+
121
+ ```text
122
+ Outputs/
123
+ ├── Results/
124
+ │ ├── pre_SW01_checks_YYYYMMDD_HHMMSS.txt
125
+ │ └── pre_SW02_checks_YYYYMMDD_HHMMSS.txt
126
+ └── Logs/
127
+ ├── NetCmd_YYYYMMDD_HHMMSS.log
128
+ └── Summary_YYYYMMDD_HHMMSS.log
129
+ ```
130
+
131
+ Result `.txt` files contain commands and original CLI responses only. Complete diagnostics and an execution summary go into separate `.log` files. No CSV or JSON reports are generated.
132
+
133
+ The terminal normally shows NET COMMAND RUNNER, mode, device count, start/end time and a Rich progress bar. Use `--verbose` to show each completed device.
134
+
135
+ ## Test
136
+
137
+ ```powershell
138
+ py -m unittest discover -s tests -v
139
+ ```
140
+
141
+ These tests are offline and do **not** establish connections to real network devices. Always validate interactive CLI behaviors against your specific firmware and model.
142
+
143
+ ## Security
144
+
145
+ Use password prompts instead of passing credentials in the command line where practical. Never commit real hostnames, IP inventories, credentials, private configuration backups or production output logs. Example IP addresses use the documentation-only `192.0.2.0/24` range.
146
+
147
+ ## Repository
148
+
149
+ Maintained as `jpesqueda/NetCmd`. This source tree contains release 1.2.0; see `PROJECT_CONTEXT.md` for implementation context.
netcmd-1.2.0/README.md ADDED
@@ -0,0 +1,124 @@
1
+ # NetCmd — Multivendor Network Command Runner
2
+
3
+ **Version 1.2.0** · Python 3.10+ · SSH / Netmiko
4
+
5
+ NetCmd executes CLI commands over SSH on a single network device or on multiple devices concurrently. It supports Cisco IOS/IOS-XE, NX-OS, Arista EOS, and other drivers supported by Netmiko. Interactive workflows can wait for CLI prompts, send responses, and reconnect after a planned reboot.
6
+
7
+ > **Safety:** Run disruptive workflows in a lab first. NetCmd sends commands that you provide; it does not independently prove that an upgrade is safe or successful.
8
+
9
+ ## Installation (Windows PowerShell)
10
+
11
+ ```powershell
12
+ py -m pip install -r requirements.txt
13
+ py netcmd.py --help
14
+ py netcmd.py --version
15
+ ```
16
+
17
+ ## Run commands
18
+
19
+ **Single device**
20
+
21
+ ```powershell
22
+ py netcmd.py -ho 192.0.2.11 -cmd examples/commands.txt -u admin -dt cisco_ios
23
+ ```
24
+
25
+ **Same commands on multiple devices**
26
+
27
+ ```powershell
28
+ py netcmd.py -hf examples/hosts.txt -cmd examples/commands.txt -u admin -dt cisco_ios -w 20
29
+ ```
30
+
31
+ **Different commands per device (Multifile)**
32
+
33
+ ```powershell
34
+ py netcmd.py -mf examples/multifile.txt -u admin -w 20
35
+ ```
36
+
37
+ **Preview without connecting**
38
+
39
+ ```powershell
40
+ py netcmd.py -mf examples/multifile.txt --dry-run
41
+ ```
42
+
43
+ **Customize result names**
44
+
45
+ ```powershell
46
+ py netcmd.py -mf examples/multifile.txt --prefix pre --suffix checks --timestamp -o Network_Audit
47
+ ```
48
+
49
+ ## Multifile input
50
+
51
+ ```text
52
+ HostName:192.0.2.11
53
+ DeviceType:cisco_ios
54
+ show version
55
+ show inventory
56
+ !
57
+
58
+ HostName:192.0.2.12
59
+ DeviceType:arista_eos
60
+ show version
61
+ show interfaces status
62
+ !
63
+ ```
64
+
65
+ Each device has its own command sequence. Repeated hostname blocks are combined in their original order. The `DeviceType:` directive overrides the CLI default driver. The host file and command file are used together in standard mode; `-mf` replaces both.
66
+
67
+ ## Interactive commands
68
+
69
+ The same directives work in `-cmd` and `-mf`.
70
+
71
+ ```text
72
+ @timeout 60
73
+ copy running-config startup-config
74
+ @expect Destination filename
75
+ @send [Enter]
76
+
77
+ @timeout 60
78
+ copy running-config bootflash:Config_2026_11_11
79
+ @expect Destination filename
80
+ @send [Enter]
81
+ ```
82
+
83
+ Available workflow directives: `@timeout`, `@expect`, `@send`, `@wait`, `@wait-disconnect`, `@reconnect`. An `@expect` must match before its corresponding `@send` is transmitted. `@send y` sends `y` plus Enter; `@send [Enter]` sends only Enter.
84
+
85
+ For a planned reboot, a sequence could include:
86
+
87
+ ```text
88
+ @wait-disconnect 300
89
+ @reconnect 900
90
+ ```
91
+
92
+ Verify CLI prompt wording and timeout values on your actual device platform before use. A reconnect alone does not validate upgrade success.
93
+
94
+ ## Output
95
+
96
+ ```text
97
+ Outputs/
98
+ ├── Results/
99
+ │ ├── pre_SW01_checks_YYYYMMDD_HHMMSS.txt
100
+ │ └── pre_SW02_checks_YYYYMMDD_HHMMSS.txt
101
+ └── Logs/
102
+ ├── NetCmd_YYYYMMDD_HHMMSS.log
103
+ └── Summary_YYYYMMDD_HHMMSS.log
104
+ ```
105
+
106
+ Result `.txt` files contain commands and original CLI responses only. Complete diagnostics and an execution summary go into separate `.log` files. No CSV or JSON reports are generated.
107
+
108
+ The terminal normally shows NET COMMAND RUNNER, mode, device count, start/end time and a Rich progress bar. Use `--verbose` to show each completed device.
109
+
110
+ ## Test
111
+
112
+ ```powershell
113
+ py -m unittest discover -s tests -v
114
+ ```
115
+
116
+ These tests are offline and do **not** establish connections to real network devices. Always validate interactive CLI behaviors against your specific firmware and model.
117
+
118
+ ## Security
119
+
120
+ Use password prompts instead of passing credentials in the command line where practical. Never commit real hostnames, IP inventories, credentials, private configuration backups or production output logs. Example IP addresses use the documentation-only `192.0.2.0/24` range.
121
+
122
+ ## Repository
123
+
124
+ Maintained as `jpesqueda/NetCmd`. This source tree contains release 1.2.0; see `PROJECT_CONTEXT.md` for implementation context.
@@ -0,0 +1,149 @@
1
+ Metadata-Version: 2.4
2
+ Name: netcmd
3
+ Version: 1.2.0
4
+ Summary: Multivendor SSH CLI command runner with parallel and interactive workflows
5
+ Author: jpesqueda
6
+ Project-URL: Homepage, https://github.com/jpesqueda/NetCmd
7
+ Project-URL: Repository, https://github.com/jpesqueda/NetCmd
8
+ Project-URL: Issues, https://github.com/jpesqueda/NetCmd/issues
9
+ Keywords: network automation,ssh,netmiko,cisco,arista,cli
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Environment :: Console
12
+ Classifier: Intended Audience :: System Administrators
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Topic :: System :: Networking
20
+ Classifier: Topic :: System :: Systems Administration
21
+ Requires-Python: >=3.10
22
+ Description-Content-Type: text/markdown
23
+ Requires-Dist: netmiko<5,>=4.3
24
+ Requires-Dist: rich<15,>=13.7
25
+
26
+ # NetCmd — Multivendor Network Command Runner
27
+
28
+ **Version 1.2.0** · Python 3.10+ · SSH / Netmiko
29
+
30
+ NetCmd executes CLI commands over SSH on a single network device or on multiple devices concurrently. It supports Cisco IOS/IOS-XE, NX-OS, Arista EOS, and other drivers supported by Netmiko. Interactive workflows can wait for CLI prompts, send responses, and reconnect after a planned reboot.
31
+
32
+ > **Safety:** Run disruptive workflows in a lab first. NetCmd sends commands that you provide; it does not independently prove that an upgrade is safe or successful.
33
+
34
+ ## Installation (Windows PowerShell)
35
+
36
+ ```powershell
37
+ py -m pip install -r requirements.txt
38
+ py netcmd.py --help
39
+ py netcmd.py --version
40
+ ```
41
+
42
+ ## Run commands
43
+
44
+ **Single device**
45
+
46
+ ```powershell
47
+ py netcmd.py -ho 192.0.2.11 -cmd examples/commands.txt -u admin -dt cisco_ios
48
+ ```
49
+
50
+ **Same commands on multiple devices**
51
+
52
+ ```powershell
53
+ py netcmd.py -hf examples/hosts.txt -cmd examples/commands.txt -u admin -dt cisco_ios -w 20
54
+ ```
55
+
56
+ **Different commands per device (Multifile)**
57
+
58
+ ```powershell
59
+ py netcmd.py -mf examples/multifile.txt -u admin -w 20
60
+ ```
61
+
62
+ **Preview without connecting**
63
+
64
+ ```powershell
65
+ py netcmd.py -mf examples/multifile.txt --dry-run
66
+ ```
67
+
68
+ **Customize result names**
69
+
70
+ ```powershell
71
+ py netcmd.py -mf examples/multifile.txt --prefix pre --suffix checks --timestamp -o Network_Audit
72
+ ```
73
+
74
+ ## Multifile input
75
+
76
+ ```text
77
+ HostName:192.0.2.11
78
+ DeviceType:cisco_ios
79
+ show version
80
+ show inventory
81
+ !
82
+
83
+ HostName:192.0.2.12
84
+ DeviceType:arista_eos
85
+ show version
86
+ show interfaces status
87
+ !
88
+ ```
89
+
90
+ Each device has its own command sequence. Repeated hostname blocks are combined in their original order. The `DeviceType:` directive overrides the CLI default driver. The host file and command file are used together in standard mode; `-mf` replaces both.
91
+
92
+ ## Interactive commands
93
+
94
+ The same directives work in `-cmd` and `-mf`.
95
+
96
+ ```text
97
+ @timeout 60
98
+ copy running-config startup-config
99
+ @expect Destination filename
100
+ @send [Enter]
101
+
102
+ @timeout 60
103
+ copy running-config bootflash:Config_2026_11_11
104
+ @expect Destination filename
105
+ @send [Enter]
106
+ ```
107
+
108
+ Available workflow directives: `@timeout`, `@expect`, `@send`, `@wait`, `@wait-disconnect`, `@reconnect`. An `@expect` must match before its corresponding `@send` is transmitted. `@send y` sends `y` plus Enter; `@send [Enter]` sends only Enter.
109
+
110
+ For a planned reboot, a sequence could include:
111
+
112
+ ```text
113
+ @wait-disconnect 300
114
+ @reconnect 900
115
+ ```
116
+
117
+ Verify CLI prompt wording and timeout values on your actual device platform before use. A reconnect alone does not validate upgrade success.
118
+
119
+ ## Output
120
+
121
+ ```text
122
+ Outputs/
123
+ ├── Results/
124
+ │ ├── pre_SW01_checks_YYYYMMDD_HHMMSS.txt
125
+ │ └── pre_SW02_checks_YYYYMMDD_HHMMSS.txt
126
+ └── Logs/
127
+ ├── NetCmd_YYYYMMDD_HHMMSS.log
128
+ └── Summary_YYYYMMDD_HHMMSS.log
129
+ ```
130
+
131
+ Result `.txt` files contain commands and original CLI responses only. Complete diagnostics and an execution summary go into separate `.log` files. No CSV or JSON reports are generated.
132
+
133
+ The terminal normally shows NET COMMAND RUNNER, mode, device count, start/end time and a Rich progress bar. Use `--verbose` to show each completed device.
134
+
135
+ ## Test
136
+
137
+ ```powershell
138
+ py -m unittest discover -s tests -v
139
+ ```
140
+
141
+ These tests are offline and do **not** establish connections to real network devices. Always validate interactive CLI behaviors against your specific firmware and model.
142
+
143
+ ## Security
144
+
145
+ Use password prompts instead of passing credentials in the command line where practical. Never commit real hostnames, IP inventories, credentials, private configuration backups or production output logs. Example IP addresses use the documentation-only `192.0.2.0/24` range.
146
+
147
+ ## Repository
148
+
149
+ Maintained as `jpesqueda/NetCmd`. This source tree contains release 1.2.0; see `PROJECT_CONTEXT.md` for implementation context.
@@ -0,0 +1,10 @@
1
+ README.md
2
+ netcmd.py
3
+ pyproject.toml
4
+ netcmd.egg-info/PKG-INFO
5
+ netcmd.egg-info/SOURCES.txt
6
+ netcmd.egg-info/dependency_links.txt
7
+ netcmd.egg-info/entry_points.txt
8
+ netcmd.egg-info/requires.txt
9
+ netcmd.egg-info/top_level.txt
10
+ tests/test_netcmd.py
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ netcmd = netcmd:main
@@ -0,0 +1,2 @@
1
+ netmiko<5,>=4.3
2
+ rich<15,>=13.7
@@ -0,0 +1 @@
1
+ netcmd
netcmd-1.2.0/netcmd.py ADDED
@@ -0,0 +1,637 @@
1
+ #!/usr/bin/env python3
2
+ """NetCmd v1.2.0: multivendor SSH command runner with interactive workflows.
3
+
4
+ Designed for Windows / Python 3.10+. No third-party package is imported when
5
+ showing --help, --version or validating an input file with --dry-run.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import argparse
10
+ import concurrent.futures
11
+ from dataclasses import dataclass, field
12
+ from datetime import datetime
13
+ import getpass
14
+ import logging
15
+ from pathlib import Path
16
+ import re
17
+ import sys
18
+ import threading
19
+ import time
20
+ from typing import Any
21
+
22
+ VERSION = "1.2.0"
23
+ DEFAULT_TIMEOUT = 60.0
24
+ PROMPT_PATTERN = re.compile(r"(?m)^\s*[^\r\n]{1,160}[#>$]\s*$")
25
+ ERROR_PATTERN = re.compile(
26
+ r"(?im)^\s*(?:%\s*(?:invalid|error|incomplete|ambiguous|unknown|unrecognized|failed)|"
27
+ r"error:\s|syntax error|invalid command|unknown command|command not found|"
28
+ r"permission denied|not enough space|copy failed)"
29
+ )
30
+ WR_COMMANDS = {"wr", "write memory", "copy running-config startup-config"}
31
+ SENSITIVE = re.compile(r"(?i)\b(password|secret|token|community|private-key|passphrase)\b")
32
+ DISRUPTIVE = re.compile(r"(?i)^\s*(?:install\s+all\b|reload\b|request\s+system\s+reboot\b|reboot\b)")
33
+ HOST_RE = re.compile(r"^hostname\s*:\s*(\S+)\s*$", re.I)
34
+ TYPE_RE = re.compile(r"^devicetype\s*:\s*(\S+)\s*$", re.I)
35
+ VALID_DIRECTIVES = {"timeout", "expect", "send", "wait", "wait-disconnect", "reconnect"}
36
+ LOG_LOCK = threading.Lock()
37
+
38
+
39
+ class InputError(ValueError):
40
+ """Bad command-file syntax, reported before any connections are made."""
41
+
42
+
43
+ class CommandFailure(RuntimeError):
44
+ """Failure during a command; do not blindly replay the command."""
45
+
46
+
47
+ @dataclass
48
+ class CommandStep:
49
+ command: str
50
+ line: int
51
+ timeout: float | None = None
52
+ interactions: list[tuple[str, str]] = field(default_factory=list)
53
+ wait_disconnect: float | None = None
54
+ reconnect: float | None = None
55
+
56
+
57
+ @dataclass
58
+ class WaitStep:
59
+ seconds: float
60
+ line: int
61
+
62
+
63
+ @dataclass
64
+ class DeviceJob:
65
+ host: str
66
+ device_type: str | None
67
+ steps: list[CommandStep | WaitStep] = field(default_factory=list)
68
+
69
+
70
+ @dataclass
71
+ class DeviceResult:
72
+ host: str
73
+ total: int
74
+ passed: int = 0
75
+ failed: int = 0
76
+ skipped: int = 0
77
+ status: str = "FAILED"
78
+ reason: str = ""
79
+ output_path: str = ""
80
+
81
+
82
+ def positive_float(value: str) -> float:
83
+ try:
84
+ number = float(value)
85
+ if 0 < number <= 86400:
86
+ return number
87
+ except ValueError:
88
+ pass
89
+ raise argparse.ArgumentTypeError("must be > 0 and <= 86400 seconds")
90
+
91
+
92
+ def positive_int(value: str) -> int:
93
+ try:
94
+ n = int(value)
95
+ if n > 0:
96
+ return n
97
+ except ValueError:
98
+ pass
99
+ raise argparse.ArgumentTypeError("must be a positive integer")
100
+
101
+
102
+ def parse_steps(lines: list[tuple[int, str]], source: str) -> list[CommandStep | WaitStep]:
103
+ steps: list[CommandStep | WaitStep] = []
104
+ pending_timeout: float | None = None
105
+ last: CommandStep | None = None
106
+ waiting_for_send = False
107
+ for lineno, line in lines:
108
+ stripped = line.strip()
109
+ if not stripped or stripped.startswith("#"):
110
+ continue
111
+ if stripped.startswith("@"):
112
+ key, _, value = stripped[1:].partition(" ")
113
+ key, value = key.lower(), value.strip()
114
+ if key not in VALID_DIRECTIVES:
115
+ raise InputError(f"{source}:{lineno}: unknown directive @{key}")
116
+ if not value:
117
+ raise InputError(f"{source}:{lineno}: @{key} requires a value")
118
+ if key in {"timeout", "wait", "wait-disconnect", "reconnect"}:
119
+ try:
120
+ seconds = float(value)
121
+ if not (0 < seconds <= 86400):
122
+ raise ValueError()
123
+ except ValueError:
124
+ raise InputError(f"{source}:{lineno}: @{key} requires seconds > 0 and <= 86400") from None
125
+ if key == "timeout":
126
+ if waiting_for_send:
127
+ raise InputError(f"{source}:{lineno}: missing @send after @expect")
128
+ pending_timeout = seconds
129
+ last = None
130
+ elif key == "wait":
131
+ if waiting_for_send:
132
+ raise InputError(f"{source}:{lineno}: missing @send after @expect")
133
+ steps.append(WaitStep(seconds, lineno))
134
+ last = None
135
+ else:
136
+ if not last or waiting_for_send:
137
+ raise InputError(f"{source}:{lineno}: @{key} must follow a command and complete @expect/@send")
138
+ if key == "wait-disconnect":
139
+ if last.wait_disconnect is not None:
140
+ raise InputError(f"{source}:{lineno}: duplicate @wait-disconnect")
141
+ last.wait_disconnect = seconds
142
+ else:
143
+ if last.reconnect is not None:
144
+ raise InputError(f"{source}:{lineno}: duplicate @reconnect")
145
+ last.reconnect = seconds
146
+ elif key == "expect":
147
+ if not last or waiting_for_send or last.wait_disconnect is not None or last.reconnect is not None:
148
+ raise InputError(f"{source}:{lineno}: @expect must follow a command or completed @send")
149
+ try:
150
+ re.compile(value)
151
+ except re.error as exc:
152
+ raise InputError(f"{source}:{lineno}: invalid @expect regex: {exc}") from exc
153
+ last.interactions.append((value, ""))
154
+ waiting_for_send = True
155
+ elif key == "send":
156
+ if not last or not waiting_for_send:
157
+ raise InputError(f"{source}:{lineno}: @send requires a preceding @expect")
158
+ pattern, _ = last.interactions[-1]
159
+ last.interactions[-1] = (pattern, value)
160
+ waiting_for_send = False
161
+ continue
162
+ if waiting_for_send:
163
+ raise InputError(f"{source}:{lineno}: missing @send after @expect")
164
+ if stripped == "!":
165
+ raise InputError(f"{source}:{lineno}: '!' is only a separator in Multifile")
166
+ last = CommandStep(stripped, lineno, timeout=pending_timeout)
167
+ steps.append(last)
168
+ pending_timeout = None
169
+ if waiting_for_send:
170
+ raise InputError(f"{source}: missing @send after final @expect")
171
+ if pending_timeout is not None:
172
+ raise InputError(f"{source}: @timeout without a subsequent command")
173
+ for step in steps:
174
+ if isinstance(step, CommandStep):
175
+ if (step.wait_disconnect is None) != (step.reconnect is None):
176
+ raise InputError(f"{source}:{step.line}: @wait-disconnect and @reconnect must be paired")
177
+ return steps
178
+
179
+
180
+ def read_input(path: str) -> list[tuple[int, str]]:
181
+ p = Path(path)
182
+ try:
183
+ return list(enumerate(p.read_text(encoding="utf-8-sig").splitlines(), 1))
184
+ except OSError as exc:
185
+ raise InputError(f"Cannot read {p}: {exc}") from exc
186
+
187
+
188
+ def load_multifile(path: str) -> list[DeviceJob]:
189
+ raw = read_input(path)
190
+ grouped: dict[str, DeviceJob] = {}
191
+ buffers: list[tuple[int, str]] = []
192
+ current: DeviceJob | None = None
193
+ def flush() -> None:
194
+ nonlocal buffers
195
+ if current and buffers:
196
+ current.steps.extend(parse_steps(buffers, path))
197
+ buffers = []
198
+ for lineno, line in raw:
199
+ stripped = line.strip()
200
+ if not stripped or stripped.startswith("#"):
201
+ continue
202
+ host_match = HOST_RE.fullmatch(stripped)
203
+ if host_match:
204
+ flush()
205
+ hostname = host_match.group(1)
206
+ key = hostname.casefold()
207
+ if key not in grouped:
208
+ grouped[key] = DeviceJob(hostname, None)
209
+ current = grouped[key]
210
+ continue
211
+ type_match = TYPE_RE.fullmatch(stripped)
212
+ if type_match:
213
+ if current is None or buffers:
214
+ raise InputError(f"{path}:{lineno}: DeviceType must follow HostName before commands")
215
+ dtype = type_match.group(1)
216
+ if current.device_type and current.device_type != dtype:
217
+ raise InputError(f"{path}:{lineno}: conflicting DeviceType for {current.host}")
218
+ current.device_type = dtype
219
+ continue
220
+ if stripped == "!":
221
+ flush()
222
+ current = None
223
+ continue
224
+ if current is None:
225
+ raise InputError(f"{path}:{lineno}: command outside HostName: block")
226
+ buffers.append((lineno, line))
227
+ flush()
228
+ if not grouped:
229
+ raise InputError(f"{path}: no devices found")
230
+ for device in grouped.values():
231
+ if not any(isinstance(s, CommandStep) for s in device.steps):
232
+ raise InputError(f"{path}: {device.host} has no commands")
233
+ return list(grouped.values())
234
+
235
+
236
+ def load_standard(host: str | None, host_file: str | None, commands_file: str) -> list[DeviceJob]:
237
+ steps = parse_steps(read_input(commands_file), commands_file)
238
+ if not any(isinstance(s, CommandStep) for s in steps):
239
+ raise InputError(f"{commands_file}: no commands")
240
+ hosts = [host] if host else [line.strip() for _, line in read_input(host_file or "") if line.strip() and not line.lstrip().startswith("#")]
241
+ unique = list(dict.fromkeys(h.casefold() for h in hosts))
242
+ canonical = {h.casefold(): h for h in hosts}
243
+ if not unique:
244
+ raise InputError("No hosts found")
245
+ return [DeviceJob(canonical[key], None, steps) for key in unique]
246
+
247
+
248
+ def build_parser() -> argparse.ArgumentParser:
249
+ description = "NetCmd — multivendor SSH command runner (normal and Multifile modes)."
250
+ examples = """Examples:
251
+ python netcmd.py -ho SW01 -cmd examples/commands.txt -u admin
252
+ python netcmd.py -hf examples/hosts.txt -cf examples/commands.txt -w 20
253
+ python netcmd.py -mf examples/multifile.txt -u admin --dry-run
254
+ python netcmd.py -mf examples/multifile.txt -u admin --verbose --timestamp
255
+ python netcmd.py -hf examples/hosts.txt -cmd examples/interactive.txt -dt cisco_nxos -w 2 --yes
256
+
257
+ Interactive syntax: @timeout SEC (before command), @expect REGEX, @send TEXT,
258
+ @send [Enter], @wait SEC, @wait-disconnect SEC,
259
+ @reconnect SEC (both disconnect/reconnect must be paired).
260
+ @send TEXT automatically appends Enter. Do not add another @send [Enter].
261
+ """
262
+ p = argparse.ArgumentParser(description=description, epilog=examples, formatter_class=argparse.RawDescriptionHelpFormatter)
263
+ devices = p.add_argument_group("device selection")
264
+ sel = devices.add_mutually_exclusive_group(required=True)
265
+ sel.add_argument("-ho", "--host", help="single hostname or IP")
266
+ sel.add_argument("-hf", "--host-file", help="file listing hosts")
267
+ sel.add_argument("-mf", "--multifile", help="HostName: / DeviceType: blocks with per-device commands")
268
+ cmds = p.add_argument_group("command options")
269
+ cmds.add_argument("-cf", "-cmd", "--command-file", dest="command_file", help="common command file (required with -ho/-hf)")
270
+ cmds.add_argument("--mode", choices=["exec", "config"], default="exec", help="CLI mode (default: exec)")
271
+ cmds.add_argument("--on-error", choices=["continue", "stop"], default="continue", help="on command error (default: continue)")
272
+ auth = p.add_argument_group("authentication")
273
+ auth.add_argument("-u", "--user", help="SSH username; prompt if omitted")
274
+ auth.add_argument("-p", "--password", help="SSH password; prompt securely if omitted")
275
+ auth.add_argument("--secret", help="enable secret (prompt when needed if omitted)")
276
+ execution = p.add_argument_group("execution")
277
+ execution.add_argument("-dt", "--device-type", help="Netmiko type, e.g. cisco_ios, cisco_nxos, arista_eos; default autodetect")
278
+ execution.add_argument("-w", "--workers", type=positive_int, default=20, help="parallel devices (default: 20)")
279
+ execution.add_argument("--timeout", type=positive_float, default=DEFAULT_TIMEOUT, help="per-command timeout seconds (default: 60)")
280
+ execution.add_argument("--conn-timeout", type=positive_float, default=15, help="SSH connection timeout seconds (default: 15)")
281
+ execution.add_argument("--retries", type=int, default=1, help="extra connection retries (default: 1; never retries commands)")
282
+ execution.add_argument("--dry-run", action="store_true", help="validate and preview without SSH")
283
+ execution.add_argument("-y", "--yes", action="store_true", help="confirm potentially disruptive commands")
284
+ execution.add_argument("--verbose", action="store_true", help="print per-device status beside progress bar")
285
+ out = p.add_argument_group("output")
286
+ out.add_argument("-o", "--output", default="Outputs", help="root output directory")
287
+ out.add_argument("--prefix", default="", help="prepend text to result filename")
288
+ out.add_argument("--suffix", default="", help="append text to result filename")
289
+ out.add_argument("--timestamp", action="store_true", help="append timestamp to result filename")
290
+ out.add_argument("--overwrite", action="store_true", help="replace existing result files")
291
+ p.add_argument("-v", "--version", action="version", version=f"NetCmd {VERSION}")
292
+ return p
293
+
294
+
295
+ def result_filename(host: str, args: Any, stamp: str) -> str:
296
+ parts = [x for x in (args.prefix, host, args.suffix, stamp if args.timestamp else "") if x]
297
+ name = "_".join(parts)
298
+ if any(x in name for x in ("/", "\\", "..")) or not name or re.search(r'[<>:"|?*\x00-\x1f]', name):
299
+ raise InputError("Invalid hostname/prefix/suffix for output filename")
300
+ return name + ".txt"
301
+
302
+
303
+ def redact_command(command: str) -> str:
304
+ return "[REDACTED COMMAND]" if SENSITIVE.search(command) else command
305
+
306
+
307
+ def setup_logger(path: Path) -> logging.Logger:
308
+ logger = logging.getLogger("netcmd")
309
+ logger.handlers.clear()
310
+ logger.setLevel(logging.INFO)
311
+ logger.propagate = False
312
+ handler = logging.FileHandler(path, encoding="utf-8")
313
+ handler.setFormatter(logging.Formatter("%(asctime)s | %(levelname)-5s | %(message)s", "%Y-%m-%d %H:%M:%S"))
314
+ logger.addHandler(handler)
315
+ return logger
316
+
317
+
318
+ def detect_and_connect(host: str, dtype: str | None, username: str, password: str, args: Any):
319
+ from netmiko import ConnectHandler, SSHDetect
320
+ base = dict(host=host, username=username, password=password, conn_timeout=args.conn_timeout,
321
+ auth_timeout=args.conn_timeout, banner_timeout=args.conn_timeout, fast_cli=False)
322
+ if args.secret:
323
+ base["secret"] = args.secret
324
+ resolved = dtype or args.device_type
325
+ last_exc: Exception | None = None
326
+ for attempt in range(args.retries + 1):
327
+ try:
328
+ if not resolved:
329
+ guess = SSHDetect(device_type="autodetect", **base).autodetect()
330
+ if not guess:
331
+ raise CommandFailure("Netmiko SSH autodetection failed; supply -dt or DeviceType")
332
+ resolved = guess
333
+ connection = ConnectHandler(device_type=resolved, **base)
334
+ try:
335
+ if connection.check_enable_mode() is False:
336
+ connection.enable()
337
+ except (AttributeError, ValueError):
338
+ pass # Not every platform implements enable mode.
339
+ return connection, resolved
340
+ except Exception as exc:
341
+ last_exc = exc
342
+ # Never retry authentication failures or unknown drivers.
343
+ message = type(exc).__name__.lower() + " " + str(exc).lower()
344
+ if any(x in message for x in ("authentication", "auth_exception", "password", "unsupported device", "ssh autodetection")):
345
+ break
346
+ if attempt < args.retries:
347
+ time.sleep(min(2 ** attempt, 5))
348
+ raise CommandFailure(f"SSH connection failed: {type(last_exc).__name__}: {last_exc}")
349
+
350
+
351
+ def channel_read_until(connection: Any, pattern: str, timeout: float, *, quiet_prompt: bool = False) -> str:
352
+ """Read raw SSH channel to a regex match; never send an unrequested answer."""
353
+ compiled = re.compile(pattern, re.I | re.M)
354
+ collected = ""
355
+ until = time.monotonic() + timeout
356
+ while time.monotonic() < until:
357
+ chunk = connection.read_channel()
358
+ if chunk:
359
+ collected += chunk
360
+ if compiled.search(collected):
361
+ return collected
362
+ else:
363
+ time.sleep(0.15)
364
+ kind = "device prompt" if quiet_prompt else f"expected pattern {pattern!r}"
365
+ raise CommandFailure(f"Timeout after {timeout:g}s waiting for {kind}; last output: {collected[-250:]!r}")
366
+
367
+
368
+ def wait_disconnect(connection: Any, timeout: float) -> str:
369
+ """Require observable SSH closure, never assume it merely from missing output."""
370
+ end = time.monotonic() + timeout
371
+ transcript = ""
372
+ while time.monotonic() < end:
373
+ try:
374
+ if hasattr(connection, "is_alive") and not connection.is_alive():
375
+ return transcript
376
+ transcript += connection.read_channel()
377
+ time.sleep(1)
378
+ except (OSError, EOFError, ConnectionError):
379
+ return transcript
380
+ except Exception as exc:
381
+ # Netmiko often raises a transport-specific exception on reboot.
382
+ if any(x in str(exc).lower() for x in ("closed", "disconnect", "socket", "eof", "reset", "not active")):
383
+ return transcript
384
+ raise
385
+ raise CommandFailure(f"No SSH disconnect observed within {timeout:g}s")
386
+
387
+
388
+ def reconnect_until(host: str, dtype: str, username: str, password: str, args: Any, timeout: float):
389
+ deadline = time.monotonic() + timeout
390
+ last_error = ""
391
+ while time.monotonic() < deadline:
392
+ try:
393
+ connection, _ = detect_and_connect(host, dtype, username, password, args)
394
+ return connection
395
+ except Exception as exc:
396
+ last_error = str(exc)
397
+ time.sleep(min(5, max(0, deadline - time.monotonic())))
398
+ raise CommandFailure(f"Reconnect timeout after {timeout:g}s: {last_error}")
399
+
400
+
401
+ def run_command(connection: Any, step: CommandStep, timeout: float, host: str, dtype: str,
402
+ username: str, password: str, args: Any) -> tuple[str, Any]:
403
+ """Send exactly once. Expect/send pairs are ordered; reconnect never replays."""
404
+ transcript = ""
405
+ # Read initial stable prompt for non-interactive commands; prompt may differ
406
+ # after entering config mode, so use end-of-line CLI prompt matching.
407
+ connection.write_channel(step.command + "\n")
408
+ if step.interactions:
409
+ for expected, answer in step.interactions:
410
+ transcript += channel_read_until(connection, expected, timeout)
411
+ payload = "\n" if answer.lower() == "[enter]" else answer + "\n"
412
+ connection.write_channel(payload)
413
+ if step.wait_disconnect is not None:
414
+ transcript += wait_disconnect(connection, step.wait_disconnect)
415
+ try:
416
+ connection.disconnect()
417
+ except Exception:
418
+ pass
419
+ connection = reconnect_until(host, dtype, username, password, args, step.reconnect or 0)
420
+ return transcript, connection
421
+ # Complete response, even after final @send; do not run next command early.
422
+ transcript += channel_read_until(connection, PROMPT_PATTERN.pattern, timeout, quiet_prompt=True)
423
+ return transcript, connection
424
+
425
+
426
+ def classify_command(command: str, output: str) -> str | None:
427
+ if ERROR_PATTERN.search(output):
428
+ return "CLI error reported"
429
+ if command.strip().lower() in {"wr", "write memory"} and not re.search(r"(?im)^\s*\[OK\]\s*$", output):
430
+ return "write memory did not return [OK]"
431
+ return None
432
+
433
+
434
+ def device_worker(job: DeviceJob, args: Any, logger: logging.Logger, outpath: Path,
435
+ username: str, password: str) -> DeviceResult:
436
+ total = sum(isinstance(s, CommandStep) for s in job.steps)
437
+ result = DeviceResult(host=job.host, total=total, output_path=str(outpath))
438
+ output_chunks: list[str] = []
439
+ connection = None
440
+ try:
441
+ connection, dtype = detect_and_connect(job.host, job.device_type, username, password, args)
442
+ logger.info("%s | Connected | device_type=%s", job.host, dtype)
443
+ if args.mode == "config":
444
+ connection.config_mode()
445
+ for step in job.steps:
446
+ if isinstance(step, WaitStep):
447
+ logger.info("%s | Wait %.1fs", job.host, step.seconds)
448
+ time.sleep(step.seconds)
449
+ continue
450
+ timeout = step.timeout or args.timeout
451
+ logger.info("%s | Executing line=%d | %s", job.host, step.line, redact_command(step.command))
452
+ start = time.perf_counter()
453
+ try:
454
+ response, connection = run_command(connection, step, timeout, job.host, dtype, username, password, args)
455
+ # A command transcript contains the command echo and the raw CLI response.
456
+ # Avoid duplicate echo; add it if the remote terminal did not echo it.
457
+ if not re.search(re.escape(step.command), response, re.I):
458
+ response = f"{job.host}# {step.command}\n" + response
459
+ output_chunks.append(response.rstrip("\n") + "\n\n")
460
+ reason = classify_command(step.command, response)
461
+ if reason:
462
+ raise CommandFailure(reason)
463
+ result.passed += 1
464
+ logger.info("%s | PASS | %s | %.2fs", job.host, redact_command(step.command), time.perf_counter()-start)
465
+ except Exception as exc:
466
+ result.failed += 1
467
+ result.reason = f"{redact_command(step.command)}: {exc}"
468
+ logger.error("%s | FAILED | %s | %s", job.host, redact_command(step.command), exc)
469
+ # After SSH transport timeout the command's outcome is unknown;
470
+ # continuing risks issuing commands into a desynchronized channel.
471
+ unsafe = "timeout" in str(exc).lower() or "disconnect" in str(exc).lower() or "ssh" in str(exc).lower()
472
+ if args.on_error == "stop" or unsafe:
473
+ break
474
+ result.skipped = total - result.passed - result.failed
475
+ result.status = "PASS" if result.failed == 0 and result.skipped == 0 else ("PARTIAL" if result.passed else "FAILED")
476
+ except Exception as exc:
477
+ result.reason = str(exc)
478
+ result.skipped = total - result.passed - result.failed
479
+ result.status = "PARTIAL" if result.passed else "FAILED"
480
+ logger.error("%s | DEVICE FAILED | %s", job.host, exc)
481
+ finally:
482
+ if connection is not None:
483
+ try:
484
+ if args.mode == "config" and connection.is_alive():
485
+ connection.exit_config_mode()
486
+ connection.disconnect()
487
+ except Exception:
488
+ pass
489
+ # Keep raw results, even if a command failed. No banner or status text.
490
+ # Collision protection is checked before workers start.
491
+ try:
492
+ outpath.write_text("".join(output_chunks), encoding="utf-8")
493
+ except OSError as exc:
494
+ result.status = "FAILED"
495
+ result.reason = f"Cannot write output: {exc}"
496
+ logger.error("%s | OUTPUT FAILED | %s", job.host, exc)
497
+ logger.info("%s | RESULT | %s | pass=%d failed=%d skipped=%d | %s", job.host, result.status,
498
+ result.passed, result.failed, result.skipped, result.reason)
499
+ return result
500
+
501
+
502
+ def duration_string(seconds: float) -> str:
503
+ n = round(seconds)
504
+ h, rem = divmod(n, 3600)
505
+ m, s = divmod(rem, 60)
506
+ return (f"{h} hours " if h else "") + (f"{m} minutes " if m else "") + f"{s} seconds"
507
+
508
+
509
+ def main(argv: list[str] | None = None) -> int:
510
+ parser = build_parser()
511
+ args = parser.parse_args(argv)
512
+ if args.multifile and args.command_file:
513
+ parser.error("-mf/--multifile cannot be combined with -cf/-cmd")
514
+ if not args.multifile and not args.command_file:
515
+ parser.error("-ho/-hf requires -cf/-cmd")
516
+ if args.retries < 0:
517
+ parser.error("--retries must be >= 0")
518
+ try:
519
+ jobs = load_multifile(args.multifile) if args.multifile else load_standard(args.host, args.host_file, args.command_file)
520
+ stamp = datetime.now().strftime("%Y%m%d_%H%M%S")
521
+ names = [result_filename(j.host, args, stamp) for j in jobs]
522
+ if len({n.lower() for n in names}) != len(names):
523
+ raise InputError("Output filename collision (case-insensitive)")
524
+ except InputError as exc:
525
+ parser.error(str(exc))
526
+ mode = "MULTIFILE" if args.multifile else "STANDARD"
527
+ commands_count = sum(isinstance(s, CommandStep) for j in jobs for s in j.steps)
528
+ print("NET COMMAND RUNNER\n")
529
+ print(f"Mode : {mode}\nDevices : {len(jobs)}\nWorkers : {args.workers}")
530
+ disruptive = any(isinstance(step, CommandStep) and DISRUPTIVE.search(step.command)
531
+ for job in jobs for step in job.steps)
532
+ if args.dry_run:
533
+ print("\nDRY RUN — no SSH connections; no output files will be generated.\n")
534
+ for job, name in zip(jobs, names):
535
+ print(f"HostName:{job.host} | DeviceType:{job.device_type or args.device_type or 'autodetect'} | {name}")
536
+ for step in job.steps:
537
+ if isinstance(step, WaitStep):
538
+ print(f" @wait {step.seconds:g}")
539
+ else:
540
+ print(f" {redact_command(step.command)}")
541
+ if step.timeout: print(f" timeout={step.timeout:g}s")
542
+ for expect, answer in step.interactions:
543
+ print(f" expect={expect!r} send={'[REDACTED]' if SENSITIVE.search(answer) else answer!r}")
544
+ if step.wait_disconnect: print(f" wait-disconnect={step.wait_disconnect:g}s reconnect={step.reconnect:g}s")
545
+ return 0
546
+ if disruptive and not args.yes:
547
+ if not sys.stdin.isatty():
548
+ parser.error("Disruptive commands detected; rerun with --yes after reviewing --dry-run")
549
+ response = input("\nPotentially disruptive commands detected. Proceed? [y/N]: ").strip().lower()
550
+ if response not in ("y", "yes"):
551
+ print("Cancelled.")
552
+ return 2
553
+ if args.user is None:
554
+ args.user = input("SSH username: ").strip()
555
+ if not args.user:
556
+ parser.error("SSH username cannot be empty")
557
+ if args.password is None:
558
+ args.password = getpass.getpass("SSH password: ")
559
+ try:
560
+ from rich.console import Console
561
+ from rich.progress import Progress, SpinnerColumn, BarColumn, TaskProgressColumn, TextColumn, TimeElapsedColumn
562
+ import netmiko # noqa: F401
563
+ except ImportError as exc:
564
+ parser.error(f"Missing dependency: {exc}. Run: py -m pip install -r requirements.txt")
565
+ root = Path(args.output)
566
+ result_dir, log_dir = root / "Results", root / "Logs"
567
+ try:
568
+ existing = [result_dir / n for n in names if (result_dir / n).exists()]
569
+ if existing and not args.overwrite:
570
+ raise InputError(f"Output already exists: {existing[0]}; use --overwrite, --timestamp or another -o")
571
+ result_dir.mkdir(parents=True, exist_ok=True)
572
+ log_dir.mkdir(parents=True, exist_ok=True)
573
+ except (InputError, OSError) as exc:
574
+ parser.error(str(exc))
575
+ # Avoid accidental overwrite of logs from two runs launched in one second.
576
+ logsuffix = stamp
577
+ suffix_no = 1
578
+ while (log_dir / f"NetCmd_{logsuffix}.log").exists() or (log_dir / f"Summary_{logsuffix}.log").exists():
579
+ logsuffix = f"{stamp}_{suffix_no}"
580
+ suffix_no += 1
581
+ logger = setup_logger(log_dir / f"NetCmd_{logsuffix}.log")
582
+ started_wall = datetime.now()
583
+ started_perf = time.perf_counter()
584
+ print(f"Start Time : {started_wall:%Y-%m-%d %H:%M:%S}\n")
585
+ logger.info("Started | mode=%s devices=%d commands=%d workers=%d", mode, len(jobs), commands_count, args.workers)
586
+ results: list[DeviceResult] = []
587
+ console = Console()
588
+ progress = Progress(SpinnerColumn(), TextColumn("Executing commands"), BarColumn(), TaskProgressColumn(),
589
+ TextColumn("{task.completed}/{task.total}"), TimeElapsedColumn(), console=console)
590
+ with progress:
591
+ task = progress.add_task("Executing commands", total=len(jobs))
592
+ with concurrent.futures.ThreadPoolExecutor(max_workers=args.workers) as executor:
593
+ submitted = {executor.submit(device_worker, job, args, logger, result_dir / name, args.user, args.password): job
594
+ for job, name in zip(jobs, names)}
595
+ for future in concurrent.futures.as_completed(submitted):
596
+ job = submitted[future]
597
+ try:
598
+ result = future.result()
599
+ except Exception as exc:
600
+ result = DeviceResult(job.host, sum(isinstance(s, CommandStep) for s in job.steps),
601
+ status="FAILED", reason=f"Unhandled worker failure: {exc}")
602
+ logger.exception("%s | Unhandled worker error", job.host)
603
+ results.append(result)
604
+ if args.verbose:
605
+ progress.console.print(f"{result.host:<24} {result.status:<8} {result.passed}/{result.total}"
606
+ + (f" | {result.reason[:120]}" if result.reason else ""))
607
+ progress.advance(task)
608
+ ended_wall = datetime.now()
609
+ elapsed = time.perf_counter() - started_perf
610
+ results_by_host = {r.host.casefold(): r for r in results}
611
+ ordered = [results_by_host[j.host.casefold()] for j in jobs]
612
+ summary_path = log_dir / f"Summary_{logsuffix}.log"
613
+ with summary_path.open("w", encoding="utf-8") as file:
614
+ file.write("NET COMMAND RUNNER — EXECUTION SUMMARY\n")
615
+ file.write(f"Mode: {mode}\nStart: {started_wall:%Y-%m-%d %H:%M:%S}\n")
616
+ file.write(f"End: {ended_wall:%Y-%m-%d %H:%M:%S}\nDuration: {duration_string(elapsed)}\n")
617
+ file.write(f"Devices: {len(jobs)} | Workers: {args.workers}\n\n")
618
+ file.write(f"{'DEVICE':<28} {'PASS':>5} {'FAIL':>5} {'SKIP':>5} STATUS\n")
619
+ for r in ordered:
620
+ file.write(f"{r.host:<28} {r.passed:>5} {r.failed:>5} {r.skipped:>5} {r.status}\n")
621
+ file.write("\nFAILED / PARTIAL DEVICES\n")
622
+ for r in ordered:
623
+ if r.status != "PASS":
624
+ file.write(f"{r.host} | {r.status} | {r.reason}\n")
625
+ file.write("\nCOUNTS\n")
626
+ for status in ("PASS", "PARTIAL", "FAILED"):
627
+ file.write(f"{status}: {sum(r.status == status for r in ordered)}\n")
628
+ logger.info("Finished | devices=%d pass=%d partial=%d failed=%d elapsed=%.2fs",
629
+ len(jobs), *(sum(r.status == s for r in ordered) for s in ("PASS", "PARTIAL", "FAILED")), elapsed)
630
+ print(f"\nCompleted : {len(jobs)} devices\nDone in : {duration_string(elapsed)}")
631
+ print(f"End Time : {ended_wall:%Y-%m-%d %H:%M:%S}\n")
632
+ print(f"Results : {result_dir}/\nLogs : {log_dir}/")
633
+ return 1 if any(r.status != "PASS" for r in ordered) else 0
634
+
635
+
636
+ if __name__ == "__main__":
637
+ sys.exit(main())
@@ -0,0 +1,37 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "netcmd"
7
+ version = "1.2.0"
8
+ description = "Multivendor SSH CLI command runner with parallel and interactive workflows"
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ authors = [{ name = "jpesqueda" }]
12
+ keywords = ["network automation", "ssh", "netmiko", "cisco", "arista", "cli"]
13
+ classifiers = [
14
+ "Development Status :: 4 - Beta",
15
+ "Environment :: Console",
16
+ "Intended Audience :: System Administrators",
17
+ "Operating System :: OS Independent",
18
+ "Programming Language :: Python :: 3",
19
+ "Programming Language :: Python :: 3.10",
20
+ "Programming Language :: Python :: 3.11",
21
+ "Programming Language :: Python :: 3.12",
22
+ "Programming Language :: Python :: 3.13",
23
+ "Topic :: System :: Networking",
24
+ "Topic :: System :: Systems Administration",
25
+ ]
26
+ dependencies = ["netmiko>=4.3,<5", "rich>=13.7,<15"]
27
+
28
+ [project.urls]
29
+ Homepage = "https://github.com/jpesqueda/NetCmd"
30
+ Repository = "https://github.com/jpesqueda/NetCmd"
31
+ Issues = "https://github.com/jpesqueda/NetCmd/issues"
32
+
33
+ [project.scripts]
34
+ netcmd = "netcmd:main"
35
+
36
+ [tool.setuptools]
37
+ py-modules = ["netcmd"]
netcmd-1.2.0/setup.cfg ADDED
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,83 @@
1
+ """Offline unit tests; no network access or Netmiko required."""
2
+ import sys
3
+ import unittest
4
+ from pathlib import Path
5
+ from tempfile import TemporaryDirectory
6
+
7
+ sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
8
+ import netcmd
9
+
10
+
11
+ class ParserTests(unittest.TestCase):
12
+ def test_interactive_chain(self):
13
+ steps = netcmd.parse_steps(list(enumerate("""@timeout 60
14
+ copy running-config startup-config
15
+ @expect Destination filename
16
+ @send [Enter]
17
+ @timeout 240
18
+ install all nxos bootflash:image.bin
19
+ @expect continue.*installation
20
+ @send y
21
+ @wait-disconnect 300
22
+ @reconnect 900
23
+ """.splitlines(), 1)), "test")
24
+ self.assertEqual(len(steps), 2)
25
+ self.assertEqual(steps[0].timeout, 60)
26
+ self.assertEqual(steps[0].interactions, [("Destination filename", "[Enter]")])
27
+ self.assertEqual(steps[1].wait_disconnect, 300)
28
+ self.assertEqual(steps[1].reconnect, 900)
29
+
30
+ def test_missing_response(self):
31
+ with self.assertRaises(netcmd.InputError):
32
+ netcmd.parse_steps([(1, "show version"), (2, "@expect question")], "bad")
33
+
34
+ def test_multifile_duplicates(self):
35
+ with TemporaryDirectory() as temp:
36
+ f = Path(temp)/"multi.txt"
37
+ f.write_text("HostName:SW1\nDeviceType:cisco_ios\nshow ver\n!\nHostName:SW2\nshow clock\n!\nHostName:sw1\nshow mod\n", encoding="utf-8")
38
+ jobs = netcmd.load_multifile(str(f))
39
+ self.assertEqual(len(jobs), 2)
40
+ self.assertEqual([s.command for s in jobs[0].steps], ["show ver", "show mod"])
41
+ self.assertEqual(jobs[0].device_type, "cisco_ios")
42
+
43
+ def test_outside_host_rejected(self):
44
+ with TemporaryDirectory() as temp:
45
+ f = Path(temp)/"multi.txt"
46
+ f.write_text("show version\nHostName:sw1\nshow version\n", encoding="utf-8")
47
+ with self.assertRaises(netcmd.InputError):
48
+ netcmd.load_multifile(str(f))
49
+
50
+ def test_filename(self):
51
+ class Args:
52
+ prefix="pre"; suffix="checks"; timestamp=True
53
+ self.assertEqual(netcmd.result_filename("SW01", Args(), "20261112_090000"), "pre_SW01_checks_20261112_090000.txt")
54
+
55
+ def test_wr(self):
56
+ self.assertIsNone(netcmd.classify_command("wr", "Building configuration...\n[OK]\n"))
57
+ self.assertIsNotNone(netcmd.classify_command("wr", "% Error: Not Enough space"))
58
+ self.assertIsNotNone(netcmd.classify_command("wr", "Building configuration..."))
59
+
60
+
61
+ class FakeSSH:
62
+ def __init__(self, chunks):
63
+ self.chunks = list(chunks)
64
+ self.sent = []
65
+ def write_channel(self, value):
66
+ self.sent.append(value)
67
+ def read_channel(self):
68
+ return self.chunks.pop(0) if self.chunks else ""
69
+
70
+
71
+ class SSHFlowTests(unittest.TestCase):
72
+ def test_two_prompts_one_command(self):
73
+ conn = FakeSSH(["copy file\nDestination filename [x]?", "Overwrite file? [y/n]", "Done\nSW01#"])
74
+ step = netcmd.CommandStep("copy run bootflash:x", 1, interactions=[("Destination filename", "[Enter]"), ("Overwrite file", "y")])
75
+ class Args: pass
76
+ output, conn2 = netcmd.run_command(conn, step, 5, "SW01", "cisco_nxos", "admin", "fake", Args())
77
+ self.assertIs(conn, conn2)
78
+ self.assertEqual(conn.sent, ["copy run bootflash:x\n", "\n", "y\n"])
79
+ self.assertIn("Overwrite file", output)
80
+
81
+
82
+ if __name__ == "__main__":
83
+ unittest.main()