jackedin 1.2.0__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.
jackedin/__init__.py ADDED
@@ -0,0 +1,52 @@
1
+ """Python client for the JackedIN command line.
2
+
3
+ Passwords are read from `JACKEDIN_PASSWORD` or written to `--password-stdin`.
4
+ They are not command-line arguments and they are not logged.
5
+ """
6
+
7
+ from jackedin.adapter import JackedinDevice
8
+ from jackedin.client import Jackedin
9
+ from jackedin.errors import (
10
+ DeviceError,
11
+ ExpectMismatch,
12
+ Interrupted,
13
+ JackedinError,
14
+ JackedinTimeout,
15
+ SecretOnArgv,
16
+ UsageError,
17
+ )
18
+ from jackedin.expect import dump_expect, load_expect
19
+ from jackedin.models import ChangePlan, CommandResult, DryRunPlan, ExecReport, ExpectRule
20
+ from jackedin.runner import SubprocessRunner
21
+
22
+ __version__ = "1.2.0"
23
+
24
+ def __getattr__(name: str):
25
+ """Load pytest helpers only when asked, so `import jackedin` does not need pytest."""
26
+ if name in {"assert_matches", "assert_report"}:
27
+ from jackedin import testing
28
+
29
+ return getattr(testing, name)
30
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
31
+
32
+ __all__ = [
33
+ "ChangePlan",
34
+ "CommandResult",
35
+ "DeviceError",
36
+ "DryRunPlan",
37
+ "ExecReport",
38
+ "ExpectMismatch",
39
+ "ExpectRule",
40
+ "Interrupted",
41
+ "Jackedin",
42
+ "JackedinDevice",
43
+ "JackedinError",
44
+ "JackedinTimeout",
45
+ "SecretOnArgv",
46
+ "SubprocessRunner",
47
+ "UsageError",
48
+ "assert_matches",
49
+ "assert_report",
50
+ "dump_expect",
51
+ "load_expect",
52
+ ]
jackedin/adapter.py ADDED
@@ -0,0 +1,101 @@
1
+ """A Netmiko-shaped adapter over `jackedin exec`.
2
+
3
+ `send_command` and `send_config_set` match the calls most automation scripts
4
+ already make. `commit_confirmed` only prints the plan. It does not connect.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from typing import Iterable, List, Optional, Sequence, Union
10
+
11
+ from jackedin.client import Jackedin
12
+ from jackedin.errors import UsageError
13
+ from jackedin.models import ChangePlan, ExpectRule
14
+
15
+ ConfigCommands = Union[str, Sequence[str]]
16
+
17
+
18
+ class JackedinDevice:
19
+ """One device. Each call connects, runs, and disconnects."""
20
+
21
+ def __init__(self, client: Jackedin, password: Optional[str] = None) -> None:
22
+ self.client = client
23
+ self._password = password
24
+
25
+ def __repr__(self) -> str:
26
+ return f"JackedinDevice(host={self.client.host!r}, username={self.client.username!r}, session={self.client.session!r})"
27
+
28
+ def send_command(self, command: str, *, expect_string: Optional[str] = None, read_timeout: int = 8) -> str:
29
+ expect = None
30
+ if expect_string:
31
+ expect = [ExpectRule(command=command, expect_match=expect_string)]
32
+ report = self.client.run([command], expect=expect, timeout=read_timeout, password=self._password)
33
+ return report.output_for(command)
34
+
35
+ def send_config_set(
36
+ self,
37
+ config_commands: ConfigCommands,
38
+ *,
39
+ exit_config_mode: bool = True,
40
+ read_timeout: int = 8,
41
+ commit: bool = False,
42
+ commit_minutes: int = 5,
43
+ ) -> str:
44
+ """Stage lines without committing them.
45
+
46
+ Junos uses `configure private` unless `commit=True`. The private edits
47
+ are discarded with `rollback 0` before `exit`, so the shared candidate
48
+ stays untouched.
49
+
50
+ `commit=True` uses `configure exclusive` and `commit confirmed`.
51
+ Junos rejects commit confirmed inside a private session. The exclusive
52
+ list always ends with `rollback 0` and `exit`, and the run does not
53
+ stop on the first error, so a failed line or a failed commit still
54
+ clears the candidate and releases the lock. `rollback 0` after a
55
+ successful commit confirmed reloads that commit. It does not cancel
56
+ the confirm timer.
57
+ """
58
+ lines = _lines(config_commands)
59
+ vendor = (self.client.vendor or "cisco").lower()
60
+ stop_on_error = True
61
+ if vendor in {"junos", "juniper", "juniper_junos"}:
62
+ if commit:
63
+ commands = [
64
+ "configure exclusive",
65
+ *lines,
66
+ f"commit confirmed {commit_minutes}",
67
+ "rollback 0",
68
+ "exit",
69
+ ]
70
+ stop_on_error = False
71
+ else:
72
+ commands = ["configure private", *lines]
73
+ if exit_config_mode:
74
+ commands.extend(["rollback 0", "exit"])
75
+ else:
76
+ if commit:
77
+ raise UsageError("Cisco has no commit confirmed. Leave commit unset, or print the change plan.")
78
+ commands = ["configure terminal", *lines]
79
+ if exit_config_mode:
80
+ commands.append("end")
81
+ report = self.client.run(
82
+ commands,
83
+ timeout=read_timeout,
84
+ password=self._password,
85
+ stop_on_error=stop_on_error,
86
+ )
87
+ return "\n".join(item.output for item in report.commands if item.output)
88
+
89
+ def commit_confirmed(self, minutes: int = 5) -> ChangePlan:
90
+ """Print the commit-confirmed plan. The password is not sent."""
91
+ return self.client.commit_confirmed(minutes=minutes)
92
+
93
+ def disconnect(self) -> None:
94
+ """Drop the in-memory password. There is no long-lived session to close."""
95
+ self._password = None
96
+
97
+
98
+ def _lines(config_commands: ConfigCommands) -> List[str]:
99
+ if isinstance(config_commands, str):
100
+ return [line.strip() for line in config_commands.splitlines() if line.strip()]
101
+ return [str(line) for line in config_commands if str(line).strip()]
jackedin/client.py ADDED
@@ -0,0 +1,377 @@
1
+ """Connect, run commands, dry-run, and print a commit-confirmed plan.
2
+
3
+ Passwords are sent only with `--password-stdin` or by leaving `JACKEDIN_PASSWORD`
4
+ in the environment the command inherits. They are never placed on argv and never logged.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import logging
11
+ import tempfile
12
+ from pathlib import Path
13
+ from typing import List, Optional, Sequence, Union
14
+
15
+ from jackedin.errors import DeviceError, Interrupted, JackedinTimeout, SecretOnArgv, UsageError
16
+ from jackedin.expect import ExpectInput, coerce_expect
17
+ from jackedin.models import ChangePlan, CheckResult, CommandResult, DryRunPlan, ExecReport, ExpectRule
18
+ from jackedin.runner import ProcessResult, Runner, SubprocessRunner, log_args, redact
19
+
20
+ LOG = logging.getLogger("jackedin")
21
+
22
+ _SECRET_FLAGS = {"--password", "-p"}
23
+ _ENABLE_ENV = "JACKEDIN_ENABLE_PASSWORD"
24
+ _LOGOUT = {"exit", "logout", "quit"}
25
+ _CISCO = {"cisco", "ios", "ios-xe", "iosxe", "cisco_ios", "cisco_xe"}
26
+ _JUNOS = {"junos", "juniper", "juniper_junos"}
27
+
28
+
29
+ class Jackedin:
30
+ """One device, or one saved session, driven by the `jackedin` command."""
31
+
32
+ def __init__(
33
+ self,
34
+ host: str = "",
35
+ username: Optional[str] = None,
36
+ port: int = 22,
37
+ protocol: str = "ssh",
38
+ session: Optional[str] = None,
39
+ credential: Optional[str] = None,
40
+ vendor: Optional[str] = None,
41
+ trust_host_key: bool = True,
42
+ runner: Optional[Runner] = None,
43
+ enable: Optional[str] = None,
44
+ secret: Optional[str] = None,
45
+ ) -> None:
46
+ if not host and not session:
47
+ raise UsageError("Pass a host or a saved session name.")
48
+ # SSH and Telnet still default to netops. A serial console often shows
49
+ # only Password:, and CLI 1.2.0 will not send that password when --user
50
+ # is set. Leave the username unset unless the caller passed one.
51
+ if username is not None and not str(username).strip():
52
+ username = None
53
+ if username is None and protocol != "serial":
54
+ username = "netops"
55
+ self.host = host
56
+ self.username = username
57
+ self.port = port
58
+ self.protocol = protocol
59
+ self.session = session
60
+ self.credential = credential
61
+ self.vendor = vendor
62
+ self.trust_host_key = trust_host_key
63
+ self.runner = runner if runner is not None else SubprocessRunner()
64
+ # Enable secret. Kept off argv and out of logs. `secret` is the same value.
65
+ self._enable = enable if enable is not None else secret
66
+
67
+ @classmethod
68
+ def from_session(cls, name: str, **kwargs: object) -> "Jackedin":
69
+ """Use a session saved in JackedIN. `name` is the session label, not a password."""
70
+ kwargs["session"] = name
71
+ kwargs.setdefault("host", "")
72
+ return cls(**kwargs) # type: ignore[arg-type]
73
+
74
+ def connect(self, commands: Sequence[str], **kwargs: object) -> ExecReport:
75
+ """Connect, run `commands`, and disconnect. This calls `jackedin exec`."""
76
+ return self.run(commands, **kwargs) # type: ignore[arg-type]
77
+
78
+ def run(
79
+ self,
80
+ commands: Sequence[str],
81
+ *,
82
+ expect: Optional[ExpectInput] = None,
83
+ timeout: int = 8,
84
+ password: Optional[str] = None,
85
+ check: bool = True,
86
+ enable: Optional[str] = None,
87
+ secret: Optional[str] = None,
88
+ stop_on_error: bool = True,
89
+ ) -> ExecReport:
90
+ """Run commands on the device and return the JSON report."""
91
+ if not commands and expect is None:
92
+ raise UsageError("Pass at least one command.")
93
+ if expect is not None and _ends_with_logout(commands):
94
+ raise UsageError(
95
+ "Refusing to run a logout with expect rules. "
96
+ "The last command returns the console to login:, and an expect check must not be typed there. "
97
+ "Drop the logout or the expect rules."
98
+ )
99
+ enable_secret = enable if enable is not None else secret
100
+ if enable_secret is None:
101
+ enable_secret = self._enable
102
+ commands = self._with_enable(list(commands), enable_secret)
103
+ args = [*self._target_args(), "--output", "json", "--timeout", str(timeout)]
104
+ if not stop_on_error:
105
+ args.append("--no-stop-on-error")
106
+ for command in commands:
107
+ args.extend(["--cmd", command])
108
+ report = self._exec(args, expect=expect, password=password, enable_secret=enable_secret)
109
+ if check and not report.ok:
110
+ message = report.error or _first_error(report) or "The command failed."
111
+ raise DeviceError(message, report=report)
112
+ return report
113
+
114
+ def dry_run(self, commands: Sequence[str], *, expect: Optional[ExpectInput] = None) -> DryRunPlan:
115
+ """Print the command plan. Nothing is connected and no password is sent."""
116
+ args = [*self._target_args(), "--dry-run"]
117
+ for command in commands:
118
+ args.extend(["--cmd", command])
119
+ result = self._invoke(args, expect=expect, password=None)
120
+ _raise_for_status(result, secrets=())
121
+ return _parse_dry_run(self.host or (self.session or ""), result.stdout)
122
+
123
+ def commit_confirmed(self, minutes: int = 5, vendor: Optional[str] = None) -> ChangePlan:
124
+ """Print Junos `commit confirmed` or the Cisco replace guidance. Nothing is sent."""
125
+ return self._change("plan", minutes=minutes, vendor=vendor)
126
+
127
+ def confirm(self, vendor: Optional[str] = None) -> ChangePlan:
128
+ """Print the Junos confirm commands. Nothing is sent."""
129
+ return self._change("confirm", vendor=vendor)
130
+
131
+ def rollback(self, vendor: Optional[str] = None) -> ChangePlan:
132
+ """Print the Junos rollback commands. Nothing is sent."""
133
+ return self._change("rollback", vendor=vendor)
134
+
135
+ def _change(self, action: str, minutes: int = 5, vendor: Optional[str] = None) -> ChangePlan:
136
+ chosen = vendor or self.vendor or "junos"
137
+ args = ["change", chosen]
138
+ if action != "plan":
139
+ args.append(action)
140
+ if chosen in {"junos", "juniper"}:
141
+ args.extend(["--minutes", str(minutes)])
142
+ result = self._invoke(args, expect=None, password=None)
143
+ _raise_for_status(result, secrets=())
144
+ text = result.stdout.strip()
145
+ return ChangePlan(
146
+ vendor=chosen,
147
+ action=action,
148
+ minutes=minutes,
149
+ text=text,
150
+ sent="not sent" not in text.lower(),
151
+ )
152
+
153
+ def _target_args(self) -> List[str]:
154
+ args = ["exec"]
155
+ if self.session:
156
+ args.extend(["--session", self.session])
157
+ else:
158
+ args.extend(["--host", self.host, "--port", str(self.port)])
159
+ if self.username:
160
+ args.extend(["--user", self.username])
161
+ if self.protocol and self.protocol != "ssh":
162
+ args.extend(["--protocol", self.protocol])
163
+ if self.trust_host_key and self.protocol == "ssh":
164
+ args.append("--trust-host-key")
165
+ if self.credential:
166
+ args.extend(["--credential", self.credential])
167
+ if self.vendor:
168
+ args.extend(["--vendor", self.vendor])
169
+ return args
170
+
171
+ def _with_enable(self, commands: List[str], enable_secret: Optional[str]) -> List[str]:
172
+ """Enter enable once when a Cisco enable secret was supplied.
173
+
174
+ Consoles that accept an enable secret land in user mode. Sending
175
+ `enable` before the rest of the list covers show startup-config,
176
+ write, copy, debug, and the other privileged commands, not only
177
+ show running-config.
178
+ """
179
+ if not enable_secret or not commands:
180
+ return commands
181
+ if commands[0].strip().lower() == "enable":
182
+ return commands
183
+ vendor = (self.vendor or "").lower()
184
+ if vendor in _JUNOS:
185
+ return commands
186
+ cisco = vendor in _CISCO or (self.protocol == "serial" and not vendor)
187
+ if not cisco:
188
+ return commands
189
+ return ["enable", *commands]
190
+
191
+ def _exec(
192
+ self,
193
+ args: List[str],
194
+ *,
195
+ expect: Optional[ExpectInput],
196
+ password: Optional[str],
197
+ enable_secret: Optional[str] = None,
198
+ ) -> ExecReport:
199
+ result = self._invoke(args, expect=expect, password=password, enable_secret=enable_secret)
200
+ secrets = tuple(item for item in (password, enable_secret) if item)
201
+ _raise_for_status(result, secrets=secrets)
202
+ report = _parse_report(redact(result.stdout, secrets))
203
+ if report.error and not report.commands:
204
+ raise DeviceError(redact(report.error, secrets), report=report)
205
+ return report
206
+
207
+ def _invoke(
208
+ self,
209
+ args: List[str],
210
+ *,
211
+ expect: Optional[ExpectInput],
212
+ password: Optional[str],
213
+ enable_secret: Optional[str] = None,
214
+ ) -> ProcessResult:
215
+ _reject_secret_args(args)
216
+ stdin: Optional[str] = None
217
+ expect_path: Optional[Path] = None
218
+ full = list(args)
219
+ try:
220
+ if expect is not None:
221
+ expect_path = _write_expect(coerce_expect(expect))
222
+ full.extend(["--expect-file", str(expect_path)])
223
+ if password is not None:
224
+ if password == "":
225
+ raise UsageError("An empty password is not sent.")
226
+ full.append("--password-stdin")
227
+ stdin = password if password.endswith("\n") else password + "\n"
228
+ _reject_secret_args(full)
229
+ child_env: Optional[dict] = None
230
+ if enable_secret is not None:
231
+ if enable_secret == "":
232
+ raise UsageError("An empty enable secret is not sent.")
233
+ if enable_secret in full:
234
+ raise SecretOnArgv("The enable secret is not passed on the command line.")
235
+ full.extend(["--enable-password-env", _ENABLE_ENV])
236
+ child_env = {_ENABLE_ENV: enable_secret}
237
+ if password and password in full:
238
+ raise SecretOnArgv("Passwords are not passed on the command line.")
239
+ log_args(full)
240
+ return self.runner.run(full, stdin=stdin, inherit_env=password is None, env=child_env)
241
+ finally:
242
+ if expect_path is not None:
243
+ expect_path.unlink(missing_ok=True)
244
+
245
+
246
+ def _ends_with_logout(commands: Sequence[str]) -> bool:
247
+ if not commands:
248
+ return False
249
+ return commands[-1].strip().lower() in _LOGOUT
250
+
251
+
252
+ def _reject_secret_args(args: Sequence[str]) -> None:
253
+ for arg in args:
254
+ name = arg.split("=", 1)[0]
255
+ if name in _SECRET_FLAGS:
256
+ raise SecretOnArgv("Use JACKEDIN_PASSWORD or --password-stdin. Do not pass --password.")
257
+
258
+
259
+ def _write_expect(text: str) -> Path:
260
+ handle = tempfile.NamedTemporaryFile("w", prefix="jackedin-expect-", suffix=".yml", delete=False, encoding="utf-8")
261
+ try:
262
+ handle.write(text)
263
+ finally:
264
+ handle.close()
265
+ return Path(handle.name)
266
+
267
+
268
+ def _raise_for_status(result: ProcessResult, secrets: Sequence[str]) -> None:
269
+ if result.returncode == 0:
270
+ return
271
+ message = redact((result.stderr or result.stdout).strip(), secrets) or f"jackedin exited {result.returncode}"
272
+ if result.returncode == 2:
273
+ raise UsageError(message)
274
+ if result.returncode == 124:
275
+ raise JackedinTimeout(message)
276
+ if result.returncode in {130, 143}:
277
+ raise Interrupted(message, result.returncode)
278
+ if result.returncode != 1:
279
+ raise DeviceError(message)
280
+
281
+
282
+ def _parse_report(text: str) -> ExecReport:
283
+ try:
284
+ payload = json.loads(text)
285
+ except json.JSONDecodeError as err:
286
+ raise DeviceError("JackedIN did not return JSON.") from err
287
+ if not isinstance(payload, dict):
288
+ raise DeviceError("JackedIN did not return a JSON object.")
289
+ if "report" in payload and isinstance(payload["report"], dict):
290
+ report = _report_from_mapping(payload["report"])
291
+ records = payload.get("records")
292
+ if isinstance(records, list):
293
+ report.records = [item for item in records if isinstance(item, dict)]
294
+ return report
295
+ return _report_from_mapping(payload)
296
+
297
+
298
+ def _report_from_mapping(payload: dict) -> ExecReport:
299
+ commands = [_command(item) for item in payload.get("commands") or [] if isinstance(item, dict)]
300
+ checks = [_check(item) for item in payload.get("checks") or [] if isinstance(item, dict)]
301
+ error = payload.get("error")
302
+ return ExecReport(
303
+ ok=bool(payload.get("ok")),
304
+ prompt=str(payload.get("prompt") or ""),
305
+ commands=commands,
306
+ checks=checks,
307
+ error=str(error) if error else None,
308
+ )
309
+
310
+
311
+ def _command(item: dict) -> CommandResult:
312
+ return CommandResult(
313
+ command=str(item.get("command") or ""),
314
+ ok=bool(item.get("ok")),
315
+ output=str(item.get("output") or ""),
316
+ prompt=str(item.get("prompt") or ""),
317
+ matched_error=_optional_str(item.get("matched_error")),
318
+ timed_out=bool(item.get("timed_out")),
319
+ duration_ms=int(item.get("duration_ms") or 0),
320
+ )
321
+
322
+
323
+ def _check(item: dict) -> CheckResult:
324
+ return CheckResult(
325
+ command=str(item.get("command") or ""),
326
+ ok=bool(item.get("ok")),
327
+ output=str(item.get("output") or ""),
328
+ expect_match=_optional_str(item.get("expect_match")),
329
+ expect_no_match=_optional_str(item.get("expect_no_match")),
330
+ matched=bool(item.get("matched")),
331
+ matched_error=_optional_str(item.get("matched_error")),
332
+ timed_out=bool(item.get("timed_out")),
333
+ )
334
+
335
+
336
+ def _optional_str(value: object) -> Optional[str]:
337
+ if value is None:
338
+ return None
339
+ return str(value)
340
+
341
+
342
+ def _first_error(report: ExecReport) -> str:
343
+ for item in report.commands:
344
+ if item.matched_error:
345
+ return item.matched_error
346
+ if not item.ok:
347
+ return f"{item.command} failed"
348
+ for item in report.checks:
349
+ if not item.ok:
350
+ return f"{item.command} did not match"
351
+ return ""
352
+
353
+
354
+ def _parse_dry_run(host: str, text: str) -> DryRunPlan:
355
+ commands: List[str] = []
356
+ checks: List[ExpectRule] = []
357
+ seen_host = host
358
+ current: Optional[ExpectRule] = None
359
+ for raw in text.splitlines():
360
+ line = raw.rstrip()
361
+ if line.startswith("host: "):
362
+ seen_host = line.split(": ", 1)[1].strip()
363
+ elif line.startswith("command: "):
364
+ command = line.split(": ", 1)[1].strip()
365
+ if command and command != "(none)":
366
+ commands.append(command)
367
+ elif line.startswith("check: "):
368
+ if current is not None:
369
+ checks.append(current)
370
+ current = ExpectRule(command=line.split(": ", 1)[1].strip())
371
+ elif line.startswith(" expect_match: ") and current is not None:
372
+ current.expect_match = line.split(": ", 1)[1].strip()
373
+ elif line.startswith(" expect_no_match: ") and current is not None:
374
+ current.expect_no_match = line.split(": ", 1)[1].strip()
375
+ if current is not None:
376
+ checks.append(current)
377
+ return DryRunPlan(host=seen_host, commands=commands, checks=checks, text=text.strip(), sent=False)
jackedin/errors.py ADDED
@@ -0,0 +1,47 @@
1
+ """Failures from the JackedIN command line. Messages never include a password."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Optional
6
+
7
+ from jackedin.models import ExecReport
8
+
9
+
10
+ class JackedinError(Exception):
11
+ """Base error. Subclasses name the kind of failure."""
12
+
13
+
14
+ class SecretOnArgv(JackedinError):
15
+ """A password was about to be placed on the command line."""
16
+
17
+
18
+ class ExpectMismatch(JackedinError):
19
+ """Captured output did not satisfy an expect rule."""
20
+
21
+ def __init__(self, message: str, failures: list) -> None:
22
+ super().__init__(message)
23
+ self.failures = failures
24
+
25
+
26
+ class UsageError(JackedinError):
27
+ """The command line was rejected. Exit code 2."""
28
+
29
+
30
+ class DeviceError(JackedinError):
31
+ """The device or the command failed. Exit code 1, or a report with ok false."""
32
+
33
+ def __init__(self, message: str, report: Optional[ExecReport] = None) -> None:
34
+ super().__init__(message)
35
+ self.report = report
36
+
37
+
38
+ class JackedinTimeout(JackedinError):
39
+ """No session output arrived before the stall watchdog. Exit code 124."""
40
+
41
+
42
+ class Interrupted(JackedinError):
43
+ """The process was interrupted. Exit code 130 or 143."""
44
+
45
+ def __init__(self, message: str, code: int) -> None:
46
+ super().__init__(message)
47
+ self.code = code
jackedin/expect.py ADDED
@@ -0,0 +1,112 @@
1
+ """The same expect-file shape the JackedIN command line reads.
2
+
3
+ Each rule starts with `- command:`. `password` and `secret` are rejected.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ from typing import List, Mapping, Union
9
+
10
+ from jackedin.errors import UsageError
11
+ from jackedin.models import ExpectRule
12
+
13
+ ExpectInput = Union[str, List[ExpectRule], List[Mapping[str, object]]]
14
+
15
+
16
+ def load_expect(text: str) -> List[ExpectRule]:
17
+ trimmed = text.strip()
18
+ if not trimmed:
19
+ raise UsageError("The expect file is empty.")
20
+ for line in trimmed.splitlines():
21
+ key = line.split(":", 1)[0].strip().lstrip("-").strip().lower()
22
+ if key in {"password", "secret"}:
23
+ raise UsageError("An expect file must not contain a password.")
24
+ rules: List[ExpectRule] = []
25
+ current: ExpectRule | None = None
26
+ for raw in trimmed.splitlines():
27
+ line = raw.strip()
28
+ if not line or line.startswith("#"):
29
+ continue
30
+ if line.startswith("- "):
31
+ if current is not None:
32
+ rules.append(_finish(current))
33
+ current = ExpectRule(command="")
34
+ field = _split_field(line[2:])
35
+ if field is not None:
36
+ _set_field(current, field[0], field[1])
37
+ continue
38
+ field = _split_field(line)
39
+ if field is None:
40
+ raise UsageError(f'Could not read expect line "{line}".')
41
+ if current is None:
42
+ raise UsageError("An expect rule must start with '- command:'.")
43
+ _set_field(current, field[0], field[1])
44
+ if current is not None:
45
+ rules.append(_finish(current))
46
+ if not rules:
47
+ raise UsageError("The expect file has no rules.")
48
+ return rules
49
+
50
+
51
+ def dump_expect(rules: List[ExpectRule]) -> str:
52
+ lines: List[str] = []
53
+ for rule in rules:
54
+ _finish(rule)
55
+ lines.append(f"- command: {rule.command}")
56
+ if rule.expect_match is not None:
57
+ lines.append(f" expect_match: {rule.expect_match}")
58
+ if rule.expect_no_match is not None:
59
+ lines.append(f" expect_no_match: {rule.expect_no_match}")
60
+ return "\n".join(lines) + "\n"
61
+
62
+
63
+ def coerce_expect(expect: ExpectInput) -> str:
64
+ if isinstance(expect, str):
65
+ load_expect(expect)
66
+ return expect if expect.endswith("\n") else expect + "\n"
67
+ if not isinstance(expect, list):
68
+ raise UsageError("Expect rules must be a YAML string, a list of rules, or a list of dicts.")
69
+ return dump_expect([_rule_from(item) for item in expect])
70
+
71
+
72
+ def _rule_from(item: object) -> ExpectRule:
73
+ if isinstance(item, ExpectRule):
74
+ return item
75
+ if isinstance(item, Mapping):
76
+ command = item.get("command")
77
+ if not isinstance(command, str):
78
+ raise UsageError("An expect dict needs a command string.")
79
+ match = item.get("expect_match")
80
+ forbidden = item.get("expect_no_match")
81
+ if match is not None and not isinstance(match, str):
82
+ raise UsageError("expect_match must be a string.")
83
+ if forbidden is not None and not isinstance(forbidden, str):
84
+ raise UsageError("expect_no_match must be a string.")
85
+ return ExpectRule(command=command, expect_match=match, expect_no_match=forbidden)
86
+ raise UsageError("An expect rule must be a string, a dict, or an ExpectRule.")
87
+
88
+
89
+ def _finish(rule: ExpectRule) -> ExpectRule:
90
+ if not rule.command:
91
+ raise UsageError("An expect rule needs a command.")
92
+ if rule.expect_match is None and rule.expect_no_match is None:
93
+ raise UsageError(f'"{rule.command}" needs expect_match or expect_no_match.')
94
+ return rule
95
+
96
+
97
+ def _split_field(text: str) -> tuple[str, str] | None:
98
+ if ":" not in text:
99
+ return None
100
+ key, value = text.split(":", 1)
101
+ return key.strip().lower(), value.strip().strip('"')
102
+
103
+
104
+ def _set_field(rule: ExpectRule, key: str, value: str) -> None:
105
+ if key == "command":
106
+ rule.command = value
107
+ elif key == "expect_match":
108
+ rule.expect_match = value
109
+ elif key == "expect_no_match":
110
+ rule.expect_no_match = value
111
+ else:
112
+ raise UsageError(f'Unknown expect field "{key}".')
jackedin/models.py ADDED
@@ -0,0 +1,74 @@
1
+ """Typed results from `jackedin exec`, dry-run, and change."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+ from typing import List, Optional
7
+
8
+
9
+ @dataclass
10
+ class CommandResult:
11
+ command: str
12
+ ok: bool
13
+ output: str
14
+ prompt: str = ""
15
+ matched_error: Optional[str] = None
16
+ timed_out: bool = False
17
+ duration_ms: int = 0
18
+
19
+
20
+ @dataclass
21
+ class CheckResult:
22
+ command: str
23
+ ok: bool
24
+ output: str = ""
25
+ expect_match: Optional[str] = None
26
+ expect_no_match: Optional[str] = None
27
+ matched: bool = False
28
+ matched_error: Optional[str] = None
29
+ timed_out: bool = False
30
+
31
+
32
+ @dataclass
33
+ class ExecReport:
34
+ ok: bool
35
+ prompt: str = ""
36
+ commands: List[CommandResult] = field(default_factory=list)
37
+ checks: List[CheckResult] = field(default_factory=list)
38
+ error: Optional[str] = None
39
+ records: List[dict] = field(default_factory=list)
40
+
41
+ def output_for(self, command: str) -> str:
42
+ for item in self.commands:
43
+ if item.command == command:
44
+ return item.output
45
+ return ""
46
+
47
+
48
+ @dataclass
49
+ class ExpectRule:
50
+ command: str
51
+ expect_match: Optional[str] = None
52
+ expect_no_match: Optional[str] = None
53
+
54
+
55
+ @dataclass
56
+ class DryRunPlan:
57
+ """A plan that was printed and not sent."""
58
+
59
+ host: str
60
+ commands: List[str]
61
+ checks: List[ExpectRule] = field(default_factory=list)
62
+ text: str = ""
63
+ sent: bool = False
64
+
65
+
66
+ @dataclass
67
+ class ChangePlan:
68
+ """Junos commit confirmed, or the Cisco replace guidance. Nothing is sent."""
69
+
70
+ vendor: str
71
+ action: str
72
+ minutes: int
73
+ text: str
74
+ sent: bool = False
jackedin/py.typed ADDED
File without changes
jackedin/runner.py ADDED
@@ -0,0 +1,86 @@
1
+ """Run the JackedIN binary. Passwords stay off argv and out of log records."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ import os
7
+ import subprocess
8
+ from dataclasses import dataclass
9
+ from typing import List, Optional, Protocol, Sequence
10
+
11
+ LOG = logging.getLogger("jackedin")
12
+
13
+
14
+ @dataclass
15
+ class ProcessResult:
16
+ args: List[str]
17
+ returncode: int
18
+ stdout: str
19
+ stderr: str
20
+
21
+
22
+ class Runner(Protocol):
23
+ def run(
24
+ self,
25
+ args: Sequence[str],
26
+ *,
27
+ stdin: Optional[str] = None,
28
+ inherit_env: bool = True,
29
+ env: Optional[dict] = None,
30
+ ) -> ProcessResult:
31
+ """Run `args` without a shell. `stdin` and `env` are not logged by the client."""
32
+
33
+
34
+ class SubprocessRunner:
35
+ """The real command. `command` is the program and any prefix, not the flags."""
36
+
37
+ def __init__(self, command: Optional[Sequence[str]] = None) -> None:
38
+ if command is None:
39
+ command = [os.environ.get("JACKEDIN_BIN", "jackedin")]
40
+ self.command = list(command)
41
+
42
+ def run(
43
+ self,
44
+ args: Sequence[str],
45
+ *,
46
+ stdin: Optional[str] = None,
47
+ inherit_env: bool = True,
48
+ env: Optional[dict] = None,
49
+ ) -> ProcessResult:
50
+ argv = [*self.command, *args]
51
+ child_env = os.environ.copy() if inherit_env else _env_without_password()
52
+ if env:
53
+ child_env.update(env)
54
+ completed = subprocess.run(
55
+ argv,
56
+ input=stdin,
57
+ text=True,
58
+ capture_output=True,
59
+ env=child_env,
60
+ shell=False,
61
+ )
62
+ return ProcessResult(
63
+ args=list(args),
64
+ returncode=completed.returncode,
65
+ stdout=completed.stdout,
66
+ stderr=completed.stderr,
67
+ )
68
+
69
+
70
+ def _env_without_password() -> dict:
71
+ env = os.environ.copy()
72
+ env.pop("JACKEDIN_PASSWORD", None)
73
+ return env
74
+
75
+
76
+ def log_args(args: Sequence[str]) -> None:
77
+ """Log the flags only. Stdin and the environment are not included."""
78
+ LOG.info("jackedin %s", " ".join(args))
79
+
80
+
81
+ def redact(text: str, secrets: Sequence[str]) -> str:
82
+ cleaned = text
83
+ for secret in secrets:
84
+ if secret:
85
+ cleaned = cleaned.replace(secret, "***")
86
+ return cleaned
jackedin/testing.py ADDED
@@ -0,0 +1,54 @@
1
+ """pytest helpers for JackedIN expect rules.
2
+
3
+ `assert_matches` checks a captured config or command transcript. It does not
4
+ connect to a device.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from typing import List, Union
10
+
11
+ import pytest
12
+
13
+ from jackedin.errors import ExpectMismatch
14
+ from jackedin.expect import ExpectInput, coerce_expect, load_expect
15
+ from jackedin.models import ExecReport
16
+
17
+
18
+ def assert_matches(text: str, rules: ExpectInput) -> None:
19
+ """Raise ExpectMismatch when `text` misses a required line or contains a forbidden one."""
20
+ failures = _failures(text, rules, command=None)
21
+ if failures:
22
+ raise ExpectMismatch("\n".join(failures), failures)
23
+
24
+
25
+ def assert_report(report: ExecReport, rules: ExpectInput) -> None:
26
+ """Check each rule against the output of the command with the same name."""
27
+ loaded = load_expect(coerce_expect(rules))
28
+ failures: List[str] = []
29
+ for rule in loaded:
30
+ output = report.output_for(rule.command)
31
+ if not output and not any(item.command == rule.command for item in report.commands):
32
+ failures.append(f"{rule.command}: no output")
33
+ continue
34
+ failures.extend(_failures(output, [rule], command=rule.command))
35
+ if failures:
36
+ raise ExpectMismatch("\n".join(failures), failures)
37
+
38
+
39
+ def _failures(text: str, rules: Union[ExpectInput, list], command: str | None) -> List[str]:
40
+ loaded = rules if isinstance(rules, list) else load_expect(coerce_expect(rules))
41
+ failures: List[str] = []
42
+ for rule in loaded:
43
+ label = command or rule.command
44
+ if rule.expect_match and rule.expect_match not in text:
45
+ failures.append(f"{label}: expected {rule.expect_match!r}")
46
+ if rule.expect_no_match and rule.expect_no_match in text:
47
+ failures.append(f"{label}: did not expect {rule.expect_no_match!r}")
48
+ return failures
49
+
50
+
51
+ @pytest.fixture
52
+ def jackedin_expect():
53
+ """Return `assert_matches` for a test that already has device output."""
54
+ return assert_matches
@@ -0,0 +1,71 @@
1
+ Metadata-Version: 2.4
2
+ Name: jackedin
3
+ Version: 1.2.0
4
+ Summary: Python client for the JackedIN command line
5
+ Author: JackedIN
6
+ License: LicenseRef-JackedIN-EULA
7
+ Keywords: network,ssh,automation
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: Programming Language :: Python :: 3.9
10
+ Classifier: Programming Language :: Python :: 3.10
11
+ Classifier: Programming Language :: Python :: 3.11
12
+ Classifier: Programming Language :: Python :: 3.12
13
+ Classifier: Programming Language :: Python :: 3.13
14
+ Requires-Python: >=3.9
15
+ Description-Content-Type: text/markdown
16
+ Provides-Extra: dev
17
+ Requires-Dist: pytest>=7.0; extra == "dev"
18
+
19
+ # jackedin
20
+
21
+ Python client for the [JackedIN](https://getpathprobe.com/jackedin/) command line. It wraps `jackedin exec`, dry-run, saved sessions, and the print-only commit-confirmed plan.
22
+
23
+ This package is not published to PyPI. Install it from a checkout:
24
+
25
+ ```bash
26
+ pip install -e python
27
+ ```
28
+
29
+ Set `JACKEDIN_BIN` when the `jackedin` program is not on `PATH`.
30
+
31
+ ## Why
32
+
33
+ Network automation already speaks Python. This client lets a script call the same JackedIN engine as the terminal, including a dry-run that does not connect and YAML expect rules the command line already understands. It does not open its own SSH stack.
34
+
35
+ Run, dry-run, expect rules, saved sessions, and the print-only commit plan are free. They are not a separate paid feature.
36
+
37
+ ## Password
38
+
39
+ A password is never a command-line argument and never written to the log.
40
+
41
+ - Leave it in `JACKEDIN_PASSWORD`. The child process inherits that variable.
42
+ - Or pass `password=` to `run`. The library sends it on stdin with `--password-stdin`.
43
+
44
+ `--password` is rejected before the process starts. An expect file that contains `password:` or `secret:` is rejected before it is written.
45
+
46
+ An enable secret is the `enable` or `secret` argument. The library passes `--enable-password-env JACKEDIN_ENABLE_PASSWORD` and puts the value only in that child environment variable. On a Cisco session, or a serial session with no vendor, `enable` is sent once before the other commands. Junos does not get that command. A list that ends in `exit`, `logout`, or `quit` is refused when expect rules are set.
47
+
48
+ ## Example
49
+
50
+ Hosts in examples are `192.0.2.10` and `router1`. The user is `netops`.
51
+
52
+ ```python
53
+ from jackedin import Jackedin
54
+
55
+ device = Jackedin("192.0.2.10", username="netops")
56
+ console = Jackedin("COM5", protocol="serial", vendor="cisco") # no --user unless you set one
57
+ plan = device.dry_run(["show version"])
58
+ assert plan.sent is False
59
+
60
+ report = device.run(
61
+ ["show version"],
62
+ expect="- command: show version\n expect_match: Version\n",
63
+ )
64
+ print(report.commands[0].output)
65
+
66
+ print(device.commit_confirmed(minutes=5).text)
67
+ ```
68
+
69
+ `commit_confirmed` only prints the Junos or Cisco plan. It does not connect.
70
+
71
+ A saved session is `Jackedin.from_session("router1")`. The name is the session label, not a secret.
@@ -0,0 +1,14 @@
1
+ jackedin/__init__.py,sha256=QBjideKfw376-JfD1YBKBhoU6jiGMS52a4g0BF5v1nY,1360
2
+ jackedin/adapter.py,sha256=hFVa6N4GOTez5cZ4sMEm_Kl7AYHld4O0pkji1hjcEvM,4024
3
+ jackedin/client.py,sha256=0YFKAXE6LiCaVHVGHh_sYGYEUCr5pb-tJX3I5JhoSJE,15231
4
+ jackedin/errors.py,sha256=TMP_p20hYAdOVU50FujA-F8PkerG2sUMTupiTfFn7gM,1297
5
+ jackedin/expect.py,sha256=zIHDSJ6wRVZQ1GB_vqTmAv8pLXYZoJXqLoA9qKyFT6E,4145
6
+ jackedin/models.py,sha256=LMZRaOY6VAJU6NTrhjWRlLuCjftnZwG1hB5Iy-NLHyE,1626
7
+ jackedin/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
8
+ jackedin/runner.py,sha256=42dWp87OEVnmNuwoK829XdFP_geTgAyf4VLM8jpikZE,2251
9
+ jackedin/testing.py,sha256=JHWltaYudCsb1hgqCFyk-qCiWOUSz7eX5Cj1F801kVM,2007
10
+ jackedin-1.2.0.dist-info/METADATA,sha256=bB2bXQkJ-Rs-RsSrxxPUXHz40G1sZk7xljC4hLLSQgA,2876
11
+ jackedin-1.2.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
12
+ jackedin-1.2.0.dist-info/entry_points.txt,sha256=npspKxe6x8sxMjq8-rlWrX03ANPBGo3kThHlkxblblc,39
13
+ jackedin-1.2.0.dist-info/top_level.txt,sha256=BTdV7iomeCGQUnQRzhNIww_TNIEMWPdvZiHzeU50Wz0,9
14
+ jackedin-1.2.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [pytest11]
2
+ jackedin = jackedin.testing
@@ -0,0 +1 @@
1
+ jackedin