diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7cbd8b0..a8a3f58 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -19,9 +19,11 @@ jobs: with: python-version: ${{ matrix.python-version }} - name: Install test and build dependencies - run: python -m pip install 'paramiko>=2.11,<5' 'packaging>=21' build twine + run: python -m pip install 'paramiko>=2.11,<5' 'packaging>=21' build twine 'mypy==2.3.1' - name: Test source run: python tools/run_checks.py + - name: Check public type contracts + run: python tools/check_public_types.py - name: Build and verify installed release run: python tools/check_release.py --output '${{ runner.temp }}/verified-artifacts' - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 @@ -29,6 +31,20 @@ jobs: name: sshscript-${{ matrix.os }}-${{ matrix.python-version }} path: ${{ runner.temp }}/verified-artifacts/ + baseline-examples: + name: Published 3.1.5 examples + runs-on: ubuntu-latest + timeout-minutes: 5 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 + with: + persist-credentials: false + - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 + with: + python-version: '3.11' + - run: python -m pip install 'sshscript==3.1.5' + - run: python -I tools/check_baseline_examples.py + openssh-integration: name: OpenSSH integration (Python ${{ matrix.python-version }}) runs-on: ubuntu-latest diff --git a/API_GUIDE.md b/API_GUIDE.md new file mode 100644 index 0000000..30a2d1c --- /dev/null +++ b/API_GUIDE.md @@ -0,0 +1,167 @@ +# Recommended SSHScript API + +This is the canonical entry point for new code and AI-generated examples. +**Version baseline: 3.1.5**, Python 3.11+. Sections marked **unreleased** require +this development checkout; installing `sshscript==3.1.5` does not provide them. +The checkout still reports 3.1.5 while these additions await a release. Do not +infer development feature availability from that version string alone. + +## Recommended choices + +| Need | Use | +| --- | --- | +| A command with dynamic arguments | `session.exec_command([program, arg, ...], check=True)` | +| Pipelines or shell expansion | A string with explicit `shell=True` or `shell="bash"`; quote dynamic values | +| Retain output | Save the returned result; read `result.stdout`, `stderr`, `exitcode` | +| Shared shell directory/environment | `session.shell()`; check each required command, save buffer text immediately | +| SSH | `with local.connect(...) as remote:`; retain host-key verification | +| Compact script | One `$` in a `.spy` file; use `$(argv, check=True)` for dynamic arguments | +| Consistent total deadline | **Unreleased:** `exec_command(command_timeout=...)` | +| Long-running program | **Unreleased:** `start(timeout=None)`, `stop()`, `wait()` | +| Session-wide failure/output policy | **Unreleased:** `set(...)`, `get(...)`, or matching properties | + +## 3.1.5: one command, one retained result + +Install the baseline with `python -m pip install "sshscript==3.1.5"`. +An argv list is one command, not a batch. Shell-looking argument text stays data. + + +```python +from contextlib import closing +import sys +from sshscript import Session + +with closing(Session()) as local: + result = local.exec_command( + [sys.executable, "-c", "import sys; print(sys.argv[1])", "a; b"], + check=True, + ) + local.exec_command([sys.executable, "-c", "pass"], check=True) + print(result.stdout.strip()) # Still the first command's output. +``` + +`CommandResult` is immutable; unpacking yields exactly stdout, stderr, exitcode. +`check=True` raises `subprocess.CalledProcessError` on nonzero exit, with text +stdout/stderr and `.result`. A timeout or transport error is not an exit status. + + +```python +from contextlib import closing +import subprocess +import sys +from sshscript import Session + +with closing(Session()) as local: + try: + local.exec_command([sys.executable, "-c", "raise SystemExit(7)"], check=True) + except subprocess.CalledProcessError as error: + print(f"failed: {error.returncode}") +``` + +## 3.1.5: SSH and optional dollar syntax + +Replace the example host with your configured host and verified known-host key. +CI executes this block with a local SSH protocol fixture in place of the login; +it does not contact example.net. OpenSSH integration tests cover the transport +separately in CI. + + +```python +from contextlib import closing +from sshscript import Session + +with closing(Session()) as local: + with local.connect("ops@example.net", timeout=10, + banner_timeout=10, auth_timeout=10) as remote: + result = remote.exec_command(["printf", "%s", "ready"], check=True) + print(result.stdout) +``` + +Save dollar syntax as `.spy`, run with `sshscript file.spy`, and syntax-check +without execution using `sshscript --check file.spy`. + + +```python +result = $(["printf", "%s", "ready"], check=True) +print(result.stdout) +``` + +## Unreleased: settings and managed jobs + +Use this source checkout for the following examples. CLI `-v`, `--stderr`, and +`--debug` override root defaults only for that execution. Child Sessions copy +their parent's settings. `set()` validates before changing anything; `get()` +returns a copy. Explicit command options override Session policy. + + +```python +from contextlib import closing +from sshscript import Session + +with closing(Session()) as local: + local.set(check=True, verbose=False, log_level="WARNING") + print(local.get("check")) + result = local.exec_command(["false"], check=False, command_timeout=5) + print(result.exitcode) +``` + +`command_timeout` is a total command budget on both backends; output does not +reset it. `CommandTimeoutError` includes partial output and termination status. +The legacy `exec_command(timeout=...)` retains different subprocess/Paramiko +semantics; do not combine it with `command_timeout`. + +For an indefinite command such as tcpdump, use `start(timeout=None)`. This safe +local example uses a small Python process instead of capturing network traffic: + + +```python +from contextlib import closing +import sys +from sshscript import Session + +with closing(Session()) as local: + with local.start( + [sys.executable, "-u", "-c", "import time; print('ready'); time.sleep(60)"], + timeout=None, stop_timeout=1, + ) as job: + try: + next(job.iter_stdout()) + finally: + result = job.stop() # Also use this after catching KeyboardInterrupt. + print(result.stop_reason, result.termination_status) +``` + +Local stop sends SIGINT, then escalates if needed. Remote PTY stop attempts +Ctrl-C; non-PTY stop closes the channel. Closure alone never confirms remote +termination. Inspect `termination_status`; `unknown` requires reconciliation. +Managed output retains bounded tails (default 1 MiB per stream), with truncation +flags. `iter_stdout()` yields text chunks and reports queue overflow explicitly. + +## Lifetime and failure rules + +- A root `with Session()` does not close the Session. These examples use + `contextlib.closing`; it calls `close()` but does not inspect its bool result. + For strict cleanup reporting, inspect `close_errors` or use `close(strict=True)`; + preserve any already-propagating exception when reporting cleanup failure. +- Remote Session, shell, and managed-job contexts own their scoped cleanup. +- A shell block manages one shell lifetime. It does not aggregate every command's + success. Console calls return two buffers, not CommandResult. Copy needed + output with `str()` before further commands or consumption. In unreleased + source, shell calls inherit `check`; interactive prompt input does not. +- A successful final shell status does not prove every pipeline stage succeeded. +- `Session.start()` keeps job results independent of Session latest-command state. + +## Compatibility forms: read, do not generate + +| Old/alternative form | Recommended new code | +| --- | --- | +| `$$command`, `onedollar()`, `twodollars()` | `$command` or `exec_command()`, with explicit shell mode when needed | +| Two-value unpacking of a Session command | A named result or three-value unpacking (console calls still return two buffers) | +| `assert` for command success | `check=True` or an explicit exception | +| Dynamic command built with `shlex.join()` | Pass argv directly; `shlex.join()` remains supported, not deprecated | +| `--check` without a filename for updates | `--check-updates`; reserve `--check file.spy` for syntax validation | + +All six executable blocks above carry explicit version profiles and run in CI. +The same source is mirrored into the website; edit this file, then use +`tools/sync_api_guide.py` to refresh the website copy. Additional protocol and +production details remain in the full documentation. diff --git a/CHANGELOG.md b/CHANGELOG.md index 11aba2b..3ac08fd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,68 @@ This project records user-visible changes here. Release artifacts and their provenance are available from the linked GitHub Release and PyPI pages. +## Unreleased + +- Add a canonical version-profiled API guide whose examples execute in CI, + plus shipped PEP 561 declarations and checked public typing examples. + +- Add Session set/get and validated check/verbose/log_level properties, child + snapshots, context-local CLI defaults, and per-command check overrides + including persistent shell commands. Session log levels are independent. + +- Add `Session.start()` and managed `CommandJob` lifetimes, streaming stdout, + bounded capture, user cancellation, and explicit termination status. +- Add opt-in `exec_command(command_timeout=...)` with the same total deadline + as `start(timeout=...)` on local and SSH backends. Legacy timeout is unchanged. +- Add `JobResult` and `CommandTimeoutError` with partial output and truncation + metadata. Local cancellation uses SIGINT then SIGKILL on an owned process + group; remote cancellation never treats channel closure as proof of a kill. +- Document unlimited tcpdump capture, Ctrl-C, bounded stop grace, and migration. + +## [3.1.5] - 2026-09-27 + +### Command API and SSH configuration + +- Accept argv lists/tuples for a single command, with local direct execution + and POSIX quoting over SSH; shell mode remains explicit for strings. +- Return immutable CommandResult snapshots with stdout, stderr, exitcode, + host, duration, and command. Unpacking/indexing now yields three values: + stdout, stderr, exitcode. Two-value unpacking must be updated. + Output values are now strings rather than live buffer objects. +- Apply check=True consistently to local and remote one-shot commands after + preserving results; CalledProcessError carries text output and result. +- Resolve common ~/.ssh/config settings with explicit API overrides; add + config opt-out, alternate files, and a connection-free settings preview. + Support ProxyCommand and ProxyJump (the latter uses local OpenSSH). +- Reject unsupported Match/Include/canonicalization rules; warn about other + unapplied config settings. ProxyJump requires noninteractive authentication + and verified jump-host keys. Existing host-key checks remain enabled. + +### Script validation + +- Add check_file(path) and --check FILE to compile Python/dollar syntax without + executing user code, imports, or commands. The no-file --check update alias + remains compatible; --check-updates is the explicit update command. +- Map tokenizer indentation errors to the original source file; retain source + mapping coverage for nested commands, interpolation, multiline expressions, + and imported .spy modules. Editor integration is deferred. + +### Documentation and community + +- Reorganize the README around installation, secure first use, compatibility, + support, and release provenance. +- Add structured issue forms, a pull request template, and a Code of Conduct. +- Clarify supported environments, security boundaries, and public test paths. + +## [3.1.4] - 2026-09-24 + +First Production/Stable release in the 3.1 line. Published through +[PyPI Trusted Publishing](https://pypi.org/project/sshscript/3.1.4/) with +verified artifacts in the +[GitHub Release](https://github.com/iapyeh/sshscript/releases/tag/v3.1.4). +This project records user-visible changes here. Release artifacts and their +provenance are available from the linked GitHub Release and PyPI pages. + ## [3.1.5] - 2026-09-27 ### Command API and SSH configuration @@ -99,3 +161,6 @@ verified artifacts in the [Unreleased]: https://github.com/iapyeh/sshscript/compare/v3.1.4...release [3.1.4]: https://github.com/iapyeh/sshscript/releases/tag/v3.1.4 + +[Unreleased]: https://github.com/iapyeh/sshscript/compare/v3.1.4...release +[3.1.4]: https://github.com/iapyeh/sshscript/releases/tag/v3.1.4 diff --git a/EXCEPTIONS.md b/EXCEPTIONS.md index 14f907b..6d7dd28 100644 --- a/EXCEPTIONS.md +++ b/EXCEPTIONS.md @@ -9,7 +9,9 @@ The following contract applies with and without `python -O`. | Invalid session, console, or channel lifecycle state | `RuntimeError` | | Operation on a closed channel or transport | `BrokenPipeError` | | Channel ends while waiting | `EOFError` | -| Timeout | `TimeoutError` | +| Legacy timeout | Original backend timeout (`subprocess.TimeoutExpired` locally; Paramiko/socket timeout remotely) | +| Managed command deadline | `CommandTimeoutError` (subclass of `TimeoutError`), with partial `JobResult` | +| Managed stdout iterator overflow | `BufferError` | | Disconnected `Session.sftp`, upload, or download | `SSHScriptException` | | Filesystem failure | Appropriate `OSError` subclass | | Paramiko failure | Original Paramiko exception and traceback | @@ -52,3 +54,19 @@ The runner locates the package and tests under `src/sshscript/`, then executes normal and optimized test suites, the dollar-syntax smoke suite, compile checks, and the package-assertion gate. CI runs these checks on Python 3.11–3.14 on Linux and macOS. The AST gate scans package runtime modules and excludes tests. + +## Managed execution (unreleased) + +`Session.start(timeout=...)` and `exec_command(command_timeout=...)` share a +monotonic total command budget. None means unlimited; finite values must be +positive. The legacy exec_command timeout remains backend-specific and cannot +be combined with command_timeout. Timeout always raises, regardless of check. +CommandTimeoutError carries command, host, timeout, elapsed, stdout, stderr, +termination_status and result. Missing exit status is None, not success. +JobResult subclasses CommandResult and adds stop_reason, termination_status, +stdout_truncated and stderr_truncated. Managed output retains bounded tails; +start() owns its result independently from Session.last_result. Deliberate stop +returns a cancellation result, even with check=True; natural failures still +raise CalledProcessError. Remote channel closure alone is not confirmation of +process termination. Unconfirmed active-job termination is reported by +Session.close() as a cleanup error. See the timeout guide for the full contract. diff --git a/MANIFEST.in b/MANIFEST.in index f45841d..b6eb1a1 100644 --- a/MANIFEST.in +++ b/MANIFEST.in @@ -5,3 +5,7 @@ include tools/setup_openssh_ci.sh include .github/dependabot.yml recursive-include .github/workflows *.yml recursive-include src/sshscript/unittest *.py *.spy + +include API_GUIDE.md +include src/sshscript/py.typed +recursive-include src/sshscript *.pyi diff --git a/README.md b/README.md index 48b80ac..0d1a052 100644 --- a/README.md +++ b/README.md @@ -1,10 +1,13 @@ # SSHScript +[![PyPI](https://img.shields.io/pypi/v/sshscript)](https://pypi.org/project/sshscript/) +[![Python](https://img.shields.io/pypi/pyversions/sshscript)](https://pypi.org/project/sshscript/) [![PyPI](https://img.shields.io/pypi/v/sshscript)](https://pypi.org/project/sshscript/) [![Python](https://img.shields.io/pypi/pyversions/sshscript)](https://pypi.org/project/sshscript/) [![CI](https://github.com/iapyeh/sshscript/actions/workflows/ci.yml/badge.svg?branch=release)](https://github.com/iapyeh/sshscript/actions/workflows/ci.yml) [![CodeQL](https://github.com/iapyeh/sshscript/actions/workflows/codeql.yml/badge.svg?branch=release)](https://github.com/iapyeh/sshscript/actions/workflows/codeql.yml) [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/iapyeh/sshscript/blob/release/LICENSE.txt) +[![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/iapyeh/sshscript/blob/release/LICENSE.txt) SSHScript is a Python automation library for running commands locally and over SSH through one `Session` API. It also provides optional dollar syntax for @@ -20,6 +23,18 @@ compact `.spy` automation files. [Security](https://github.com/iapyeh/sshscript/security/policy) · [Support](https://github.com/iapyeh/sshscript/blob/release/SUPPORT.md) +## Recommended API + +Start with [the canonical API guide](API_GUIDE.md): version-labelled examples, +recommended argv/check/result patterns, lifetime rules, and compatibility forms. +Its executable examples run in CI. The same guide is available in the +[website documentation](https://iapyeh.github.io/sshscript/v3a/recommended-api/). + +The unreleased source also ships `py.typed` and public `.pyi` declarations for +Session, results, jobs, console calls and package entry points. Legacy live +buffers and backend-specific keyword options retain `Any`; this is targeted +public typing, not a claim that every internal module is fully annotated. + ## Why SSHScript? - Use the same interface for local subprocesses and remote SSH commands. @@ -60,16 +75,15 @@ it never installs an update by itself. ## 60-second local quickstart ```python -import shlex import sys from sshscript import Session -command = shlex.join([ +command = [ sys.executable, "-c", "print('sshscript is ready')", -]) +] with Session() as local: stdout, stderr, exitcode = local.exec_command( @@ -130,6 +144,74 @@ Persistent shell and interactive console APIs retain their existing buffer and prompt semantics; this result/check contract applies to one-shot Session commands, including `$` commands outside persistent consoles. +## Session settings (unreleased) + +```python +session.set(check=True, verbose=False, log_level="DEBUG") +print(session.get()) # Independent copy of effective settings. +print(session.get("check")) # True +session.verbose = True # Same validation as set(verbose=True). +session(["false"], check=False) # Explicit per-command override. +``` + +In `.spy`, use `$.set(...)` and `$.get(...)`. Settings are `check`, `verbose`, +`verbose_stderr`, and `log_level` (logging integer or level name). New root +Sessions snapshot package/application defaults; CLI `-v`, `--stderr`, and +`--debug` override defaults only in that execution context. Child Sessions +snapshot their parent's current settings. Existing Sessions are independent. +`set()` validates every key/value before applying changes; unknown keys fail. +Properties and set/get use the same storage. Command options override settings; +running jobs retain their startup policy. Shell commands inherit check and can +override it per call; interactive prompt input is not an exit-status check. +Session logging never changes the shared logger level; application handler +filters/levels still apply. Verbose explicitly prints command output and may +expose sensitive output. No console logging handler is installed by Session. + +## Managed deadlines and long-running commands (unreleased) + +The source checkout adds a total deadline shared by local and SSH commands: + +```python +result = session.exec_command(["uname", "-s"], command_timeout=30, check=True) +``` + +This opt-in path returns `JobResult` (a `CommandResult` subclass), retains at +most 1 MiB of output per stream by default, and raises `CommandTimeoutError` +with partial output on expiry. `command_timeout=None` selects managed execution +without a deadline. Legacy `exec_command(timeout=...)` keeps its existing +backend-specific behavior; do not combine the two parameters. + +Use `Session.start()` for a command that runs until its user stops it: + +```python +from contextlib import closing +from sshscript import Session + +with closing(Session()) as local: + with local.start(["tcpdump", "-l", "-n", "-i", "eth0"], + timeout=None, stop_timeout=5, check=True) as capture: + try: + for chunk in capture.iter_stdout(): + print(chunk, end="", flush=True) + except KeyboardInterrupt: + pass + finally: + result = capture.stop() + print("\nTermination:", result.termination_status) +``` + +Choose an interface on your host and run under an account authorized to capture +packets. `start(timeout=...)` always means a total command budget; `None` means +no deadline. Local stop sends SIGINT to the owned process group, then escalates +after `stop_timeout`. Remote stop can attempt Ctrl-C with `get_pty=True`, but +closing an SSH channel alone does not prove termination: inspect +`termination_status`. A job context and `Session.close()` clean up active jobs. +Streaming yields chunks, with bounded buffering and explicit overflow errors. + +See [Timeouts, cancellation, tcpdump, and cleanup](https://iapyeh.github.io/sshscript/v3a/security-and-operations/timeouts-retries-and-cleanup/) +for the timing contract, remote example, output limits, and migration details. +These new APIs are not present in the published 3.1.5 package. + ## First secure SSH connection SSHScript uses Paramiko and verifies system host keys by default. Before the @@ -216,19 +298,21 @@ files; `run_script(source)` also accepts Dollar syntax from an in-memory string. Both forms use the same session and transport implementation as the module API: ```python -# health.spy -$hostname -if $.exitcode != 0: - raise RuntimeError("hostname failed") -print($.stdout.strip()) - -with $.connect("ops@example.net"): - $uname -s - if $.exitcode != 0: - raise RuntimeError("remote uname failed") +import paramiko + +remote = session.connect( + "user@new-host.example", + policy=paramiko.AutoAddPolicy(), +) ``` -Run exactly one file with: +Do this only in a trusted bootstrap environment. Interactive SSH sessions do +not forward the complete local process environment; only terminal/locale +defaults and values explicitly supplied through `env={...}` are sent. + +## Tests + +The canonical credential-free release gate is: ```sh sshscript health.spy diff --git a/pyproject.toml b/pyproject.toml index 9e0f9e3..8df74d6 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -58,3 +58,6 @@ package-dir = {"" = "src"} [tool.setuptools.dynamic] version = {attr = "sshscript._version.__version__"} + +[tool.setuptools.package-data] +sshscript = ["py.typed", "*.pyi"] diff --git a/src/sshscript/__init__.py b/src/sshscript/__init__.py index 8fe77be..2213af7 100755 --- a/src/sshscript/__init__.py +++ b/src/sshscript/__init__.py @@ -53,6 +53,9 @@ run_script = sshscript.run_script Session = session.Session CommandResult = session.CommandResult +CommandJob = session.CommandJob +CommandTimeoutError = session.CommandTimeoutError +JobResult = session.JobResult set_logger = errorutils.set_logger get_logger = errorutils.get_logger @@ -79,6 +82,9 @@ 'run_script', 'Session', 'CommandResult', + 'CommandJob', + 'CommandTimeoutError', + 'JobResult', 'get_logger', 'set_logger', 'spy_imports', diff --git a/src/sshscript/__init__.pyi b/src/sshscript/__init__.pyi new file mode 100644 index 0000000..4a67a9c --- /dev/null +++ b/src/sshscript/__init__.pyi @@ -0,0 +1,15 @@ +from typing import Any, ContextManager +from os import PathLike +from .session import Session as Session +from .commandresult import CommandResult as CommandResult +from .commandjob import CommandJob as CommandJob, JobResult as JobResult, CommandTimeoutError as CommandTimeoutError +from .errorutils import SSHScriptException as SSHScriptException + +__version__: str + +def check_file(script_path: str | PathLike[str]) -> int: ... +def run_file(script_path: str | PathLike[str], vars: dict[str, Any] | None = ..., showScript: bool = ...) -> int: ... +def run_script(script: str, varGlobals: dict[str, Any] | None = ..., showScript: bool = ...) -> dict[str, Any]: ... +def spy_imports() -> ContextManager[None]: ... +def get_logger() -> Any: ... +def set_logger(userlogger: Any = ..., logname: str | None = ...) -> Any: ... diff --git a/src/sshscript/channelgeneric.py b/src/sshscript/channelgeneric.py index a67d87d..4af34c9 100755 --- a/src/sshscript/channelgeneric.py +++ b/src/sshscript/channelgeneric.py @@ -67,6 +67,7 @@ def __init__(self,owner): ## an instance of Dollar self.owner = owner + self.logger = getattr(owner, "logger", logger) ## see hijack() for details self.hijacked = False @@ -80,12 +81,13 @@ def __init__(self,owner): ## 如果沒有,則送出一個dumyEcho #self._exitcode_session_id = 0 #self._command_session_id = 0 - if os.environ.get('VERBOSE'): + settings = getattr(owner, 'settings', {}) + if settings.get('verbose', bool(os.environ.get('VERBOSE'))): ## verbose-related self.dump2sys = (1,1) self.stdoutPrefix = os.environ.get('VERBOSE_STDOUT_PREFIX','🟩').encode('utf8') self.stderrPrefix = os.environ.get('VERBOSE_STDERR_PREFIX','🟨').encode('utf8') - elif os.environ.get('VERBOSE_STDERR'): + elif settings.get('verbose_stderr', bool(os.environ.get('VERBOSE_STDERR'))): self.dump2sys = (0,1) self.stdoutPrefix = b'' self.stderrPrefix = os.environ.get('VERBOSE_STDERR_PREFIX','🟨').encode('utf8') @@ -286,7 +288,7 @@ def wait_for_output(self,timeout=0,silent=False)->bool: basetime = self.lastIOAtTime[:] timeouttime = (time.time() + timeout) if timeout else 0 ret = True - logger.debug( + self.logger.debug( '%s Waiting for channel output (timeout=%s, silent=%s)', self.prefixOfLog, timeout or None, @@ -314,7 +316,7 @@ def wait_for_output(self,timeout=0,silent=False)->bool: else: raise TimeoutError(f'wait_for_output exceeded {timeout}') - logger.debug( + self.logger.debug( '%s Channel output wait completed (received=%s)', self.prefixOfLog, ret, @@ -395,7 +397,7 @@ def exitcode(self)->int: """Return the recorded status, fetching it if needed; -1 while interactive.""" if self.hijacked: #raise ValueError('exitcode is not available in current state') - logger.warning( + self.logger.warning( '%s Exit status is unavailable while the channel is in interactive mode', self.prefixOfLog, ) @@ -410,7 +412,7 @@ def log(self,msg, *args, level=logging.DEBUG, **kwargs): """Log with channel context, preserving format arguments and logging keywords.""" if isinstance(level, int) and 0 < level < logging.DEBUG: level = logging.DEBUG - logger.log(level, f'{self.prefixOfLog} {msg}', *args, **kwargs) + getattr(self, 'logger', logger).log(level, f'{self.prefixOfLog} {msg}', *args, **kwargs) def expect( self, @@ -1401,7 +1403,7 @@ def input(self,text): :text: Text to send as input """ - logger.debug( + self.logger.debug( '%s Sending channel input (length=%d, interactive=%s)', self.prefixOfLog, len(text), @@ -1826,7 +1828,7 @@ def send_command(self,command,**expections): :return: Tuple of (stdout, stderr) """ - logger.debug( + self.logger.debug( '%s Dispatching command (interactive=%s, expectations=%d) %s', self.prefixOfLog, bool(self.prompt), @@ -1874,7 +1876,7 @@ def prompt_found_callback(): if m: self._exitcode = int(m.group(1)) else: - logger.warning( + self.logger.warning( '%s Unable to parse command exit status', self.prefixOfLog, ) @@ -1891,7 +1893,7 @@ def prompt_found_callback(): ## so that when next line is getting $.exitcode, it would get the corrent exitcode ## not the exitcode of our modified command. while self.executing_lock.locked(): time.sleep(0.01) - logger.debug( + self.logger.debug( '%s Command completed (interactive=%s, exit_status=%s)', self.prefixOfLog, bool(self.prompt), @@ -2000,13 +2002,23 @@ async def _dump_stdout_err_job(self): await handler[x](newbytes) self._dumpBuf.clear() except Exception: - logger.exception('%s Channel output forwarding failed', self.prefixOfLog) + self.logger.exception('%s Channel output forwarding failed', self.prefixOfLog) raise async def _dump_stdout_err(self): handler = [self._dump_stdout,self._dump_stderr] for x,newbytes in self._dumpBuf: await handler[x](newbytes) self._dumpBuf.clear() + # One-shot completion must also forward a final unterminated line. + for name, stream, prefix in ( + ('_stdoutDumpBuf', sys.stdout, self.stdoutPrefix), + ('_stderrDumpBuf', sys.stderr, self.stderrPrefix), + ): + pending = getattr(self, name) + if pending: + stream.buffer.write(prefix + self._native_id.encode() + b':' + pending) + stream.buffer.flush() + setattr(self, name, b'') def reset_buffer(self,reason=None): """Replace the current stdout/stderr pair; return (new_pair, previous_pair).""" diff --git a/src/sshscript/channelssh.py b/src/sshscript/channelssh.py index 30017d7..30670e9 100755 --- a/src/sshscript/channelssh.py +++ b/src/sshscript/channelssh.py @@ -36,7 +36,8 @@ class ParamikoChannel(object): def __init__(self,sshchannel,get_pty,channel=None): if not isinstance(sshchannel, SSHChannel): raise TypeError('sshchannel must be SSHChannel') - self.sshchannel = sshchannel + self.sshchannel = sshchannel + self.logger = sshchannel.logger self.get_pty = get_pty self.suspending = False if channel is None: @@ -78,7 +79,7 @@ def __init__(self,sshchannel,get_pty,channel=None): ## two-dollars has no self.command if self.sshchannel.owner.command: - logger.debug( + self.logger.debug( '[SSHChannel] Executing remote command (host=%s, pty=%s)', self.sshchannel.owner.session.host, self.get_pty, @@ -118,7 +119,7 @@ async def _reading(): except (SSHException,ValueError): if self.channel.closed or self.channel.exit_status_ready(): break - logger.exception( + self.logger.exception( '[SSHChannel] SSH channel read failed (host=%s)', self.sshchannel.owner.session.host, ) @@ -126,7 +127,7 @@ async def _reading(): await asyncio.sleep(0.1) except OSError as e: if e.errno != errno.EIO and not self.channel.closed: - logger.exception( + self.logger.exception( '[SSHChannel] SSH channel reader failed (host=%s)', self.sshchannel.owner.session.host, ) @@ -166,7 +167,7 @@ def close(self): command result is kept separately from the SSH channel exit status. """ host = self.sshchannel.owner.session.host - logger.debug('[SSHChannel] Closing SSH channel (host=%s)', host) + self.logger.debug('[SSHChannel] Closing SSH channel (host=%s)', host) ## automatically send exit to shell try: if not self.channel.exit_status_ready(): @@ -176,7 +177,7 @@ def close(self): deadline = time.monotonic() + timeout_seconds while True: if time.monotonic() > deadline: - logger.warning( + self.logger.warning( '[SSHChannel] Exit status was not received before close timeout; ' 'forcing channel close (host=%s, timeout=%ss)', host, @@ -191,7 +192,7 @@ def close(self): else: time.sleep(0.1) except (SSHException, OSError): - logger.exception('[SSHChannel] Failed to close SSH channel (host=%s)', host) + self.logger.exception('[SSHChannel] Failed to close SSH channel (host=%s)', host) raise finally: self.channel.close() diff --git a/src/sshscript/channelsubprocess.py b/src/sshscript/channelsubprocess.py index b90d0de..abe79f6 100755 --- a/src/sshscript/channelsubprocess.py +++ b/src/sshscript/channelsubprocess.py @@ -200,7 +200,7 @@ async def _reading(): sel.close() POpenChannel.count += 1 await _reading() - logger.debug( + self.logger.debug( '[POpen] Subprocess reader stopped (pid=%s, returncode=%s)', self.cp.pid, self.cp.poll(), @@ -248,7 +248,7 @@ def close(self): pid = self.cp.pid if self.cp.poll() is None: timeout = 2 - logger.debug( + self.logger.debug( '[POpen] Waiting for subprocess to exit (pid=%s, timeout=%ss)', pid, timeout, @@ -256,7 +256,7 @@ def close(self): try: self.cp.wait(timeout) except subprocess.TimeoutExpired: - logger.warning( + self.logger.warning( '[POpen] Subprocess did not exit before close timeout; ' 'terminating (pid=%s, timeout=%ss)', pid, @@ -266,7 +266,7 @@ def close(self): try: self.cp.wait(timeout) except subprocess.TimeoutExpired: - logger.warning( + self.logger.warning( '[POpen] Subprocess did not terminate before timeout; ' 'killing (pid=%s, timeout=%ss)', pid, @@ -284,7 +284,7 @@ def close(self): else: fd.close() - logger.debug( + self.logger.debug( '[POpen] Subprocess channel closed (pid=%s, returncode=%s)', pid, self.cp.poll(), diff --git a/src/sshscript/channelutils.py b/src/sshscript/channelutils.py index 8985dee..9b1c9ad 100755 --- a/src/sshscript/channelutils.py +++ b/src/sshscript/channelutils.py @@ -48,6 +48,7 @@ def __init__(self,wcw,command,expect=None,password=None,initials=None,exit=None, ## instance of SSHScriptChannel self.channel = wcw.channel + self.logger = self.channel.logger self.command = command self.exit_command = exit self.password = password @@ -81,7 +82,7 @@ def enter(self): ## test if we got a prompt asking for password m = self.channel.expect(self.loginExpect,timeout=5,silent=True) if m: - logger.debug( + self.logger.debug( 'Authentication prompt detected; sending password input ' '(length=%d)', len(self.password), @@ -89,21 +90,25 @@ def enter(self): self.channel.clear() self.channel.touchIO(True) self.channel.send(self.password+'\n') + ## reconfirm login is ok - m = self.channel.expect(self.loginExpect,timeout=2,silent=True) + #self.channel.wait_for_silent(1) + m = self.channel.expect([self.loginExpect,re.compile('sorry',re.I)],timeout=2,silent=True) if m: ## Chances is MOT like this: ## Time to change your password? Type "passwd" and follow the prompts. ## -- Dru - raise PermissionError(f'"{self.loginExpect}" prompted again') - login_success = True + #raise PermissionError(f'"{self.loginExpect}" prompted again') + pass + else: + login_success = True else: - logger.debug( + self.logger.debug( 'Authentication prompt was not detected; password was not sent' ) else: ## has password, but no prompt have to wait - logger.debug( + self.logger.debug( 'No authentication prompt is configured; sending password input ' '(length=%d)', len(self.password), @@ -127,9 +132,9 @@ def enter(self): else: try: self.channel._stdout.splitlines()[-1] - logger.debug('Shell prompt detected') + self.logger.debug('Shell prompt detected') except IndexError: - logger.debug('Shell prompt was not detected') + self.logger.debug('Shell prompt was not detected') if self.initials is None: ## shell, su, sudo diff --git a/src/sshscript/commandjob.py b/src/sshscript/commandjob.py new file mode 100644 index 0000000..7529d9a --- /dev/null +++ b/src/sshscript/commandjob.py @@ -0,0 +1,424 @@ +"""Managed one-shot commands with bounded capture, cancellation and deadlines. + +SSH cancellation owns a channel, never the shared transport. Closing a channel +is not proof that its remote process (or descendants) has terminated. +""" +import codecs +from collections import deque +from dataclasses import dataclass +import math +import os +import selectors +import shlex +import signal +import sys +import subprocess +import threading +import time + +if __package__: + from .commandresult import CommandResult +else: + from commandresult import CommandResult + + +@dataclass(frozen=True) +class JobResult(CommandResult[int | None]): + """Captured tails of a managed command; None means no exit status observed.""" + exitcode: int | None + stop_reason: str = 'completed' + termination_status: str = 'confirmed' + stdout_truncated: bool = False + stderr_truncated: bool = False + + +class CommandTimeoutError(TimeoutError): + """A command budget expired, after bounded cancellation and cleanup.""" + def __init__(self, result, timeout): + super().__init__(f'command exceeded its {timeout:g}s time budget') + self.result = result + self.command = result.command + self.host = result.host + self.timeout = timeout + self.elapsed = result.duration + self.stdout = result.stdout + self.stderr = result.stderr + self.termination_status = result.termination_status + + +def _seconds(value, name, allow_none=True): + if value is None and allow_none: + return + if isinstance(value, bool) or not isinstance(value, (int, float)): + raise TypeError(f'{name} must be a finite positive number' + (' or None' if allow_none else '')) + if not math.isfinite(value) or value <= 0: + raise ValueError(f'{name} must be finite and greater than zero') + + +class CommandJob: + """Owned command. Use Session.start(), wait(), stop(), and a with block. + + iter_stdout() yields UTF-8 text chunks (not necessarily complete lines). + Capture retains at most capture_limit bytes per stream. The streaming queue + retains 128 chunks; a slow consumer gets BufferError rather than silent loss. + wait()/stop() are repeatable. stop() requests SIGINT locally, or Ctrl-C on a + remote PTY, then allows stop_timeout seconds before forced cleanup. + """ + def __init__(self, session, execution, *, timeout=None, stop_timeout=3, + capture_limit=1024 * 1024, check=False, input=None, env=None, + get_pty=False): + _seconds(timeout, 'timeout') + _seconds(stop_timeout, 'stop_timeout', False) + if isinstance(capture_limit, bool) or not isinstance(capture_limit, int): + raise TypeError('capture_limit must be an integer') + if capture_limit < 0: + raise ValueError('capture_limit must be nonnegative') + if not isinstance(check, bool) or not isinstance(get_pty, bool): + raise TypeError('check and get_pty must be bool') + if get_pty and session._client is None: + raise ValueError('managed local jobs do not support get_pty; use Session.enter()') + if input is not None and not isinstance(input, (str, bytes)): + raise TypeError('input must be str, bytes or None') + if env is not None: + if not isinstance(env, dict) or not all(isinstance(k, str) and isinstance(v, str) for k, v in env.items()): + raise TypeError('env must map strings to strings') + if any(not k or '\x00' in k + v or '=' in k for k, v in env.items()): + raise ValueError('env contains an invalid name or value') + self._session = session # Keep the transport owner alive for this job. + self.settings = session.get() + self.logger = execution.logger + self.command = execution.argv or execution.command + self.host = session.host + self._client = session._client + self._argv = ([execution.shell_executable or '/bin/sh', '-c', execution.command] + if execution.use_shell else list(execution.argv or shlex.split(execution.command))) + self.timeout = timeout + self.stop_timeout = stop_timeout + self.capture_limit = capture_limit + self.check = check + self._input = input.encode('utf-8') if isinstance(input, str) else (input or b'') + self._env = env + self._pty = get_pty + self._condition = threading.Condition() + self._tails = [bytearray(), bytearray()] + self._truncated = [False, False] + self._chunks = deque(maxlen=128) + self.dropped_stdout_chunks = 0 + self._signal_lock = threading.Lock() + self._sent_local_signals = set() + self._process = self._channel = None + self._status = None + self._error = None + self._reason = None + self._cancelled_at = None + self._worker_done = threading.Event() + self._done = threading.Event() + self._result = None + self._started = time.monotonic() + self._deadline = None if timeout is None else self._started + timeout + self._worker = threading.Thread(target=self._run, name='sshscript-command-io', daemon=True) + self._monitor = threading.Thread(target=self._watch, name='sshscript-command-watch', daemon=True) + + def _launch(self): + self._worker.start() + self._monitor.start() + return self + + @property + def done(self): + return self._done.is_set() + + @property + def stdout(self): + with self._condition: + return bytes(self._tails[0]).decode('utf-8', errors='replace') + + @property + def stderr(self): + with self._condition: + return bytes(self._tails[1]).decode('utf-8', errors='replace') + + @property + def exitcode(self): + return self._result.exitcode if self.done else self._status + + def clear(self): + """Clear live captured tails; previously returned snapshots stay valid.""" + with self._condition: + for tail in self._tails: + tail.clear() + + def _capture(self, stream, data): + if self.settings['verbose'] or (stream == 1 and self.settings['verbose_stderr']): + target = sys.stdout if stream == 0 else sys.stderr + target.write(data.decode('utf-8', errors='replace')) + target.flush() + with self._condition: + if self.done: + return + tail = self._tails[stream] + tail.extend(data) + if len(tail) > self.capture_limit: + self._truncated[stream] = True + del tail[:len(tail) - self.capture_limit] + if stream == 0: + if len(self._chunks) == self._chunks.maxlen: + self.dropped_stdout_chunks += 1 + self._chunks.append(data) + self._condition.notify_all() + + def _request_stop(self, reason): + with self._condition: + if not self.done and not self._worker_done.is_set() and self._reason is None: + now = time.monotonic() + self._reason = 'timeout' if self._deadline is not None and now >= self._deadline else reason + self._cancelled_at = now + self._condition.notify_all() + + def _signal(self, force=False): + process, channel = self._process, self._channel + if process is not None: + # Own process group includes ordinary shell pipelines/descendants. + # Descendants which create a new session are outside this guarantee. + sig = signal.SIGKILL if force else signal.SIGINT + with self._signal_lock: + if sig not in self._sent_local_signals: + try: + os.killpg(process.pid, sig) + except ProcessLookupError: + pass + self._sent_local_signals.add(sig) + if channel is not None: + if force or not self._pty: + channel.close() + elif channel.send_ready(): + channel.send(b'\x03') + + def _watch(self): + signalled_resource = None + while not self._worker_done.wait(0.02): + now = time.monotonic() + if self._deadline is not None and now >= self._deadline: + self._request_stop('timeout') + if self._reason is not None: + resource = self._process if self._process is not None else self._channel + try: + if resource is not None and resource is not signalled_resource: + self._signal() + signalled_resource = resource + if now >= self._cancelled_at + self.stop_timeout: + self._signal(force=True) + if self._worker_done.wait(1): + break + # Never wait indefinitely for a broken backend to close. + break + except Exception as exc: + self._error = exc + try: + self._signal(force=True) + except Exception: + pass + self._worker_done.wait(1) + break + with self._condition: + status = self._status + self._result = JobResult( + self.stdout, self.stderr, status, self.host, + time.monotonic() - self._started, self.command, + self._reason or 'completed', + 'confirmed' if status is not None else 'unknown', + *self._truncated, + ) + self._done.set() + self._condition.notify_all() + + def _run(self): + self.logger.debug('Starting managed command (host=%s)', self.host) + try: + if self._client is None: + self._run_local() + else: + self._run_remote() + except Exception as exc: + if self._reason is None or self._client is None: + self._error = exc + finally: + try: + if self._channel is not None: + self._channel.close() + except Exception as exc: + if self._error is None: + self._error = exc + finally: + if self._deadline is not None and time.monotonic() >= self._deadline: + self._request_stop('timeout') + self._worker_done.set() + + def _run_local(self): + process = subprocess.Popen(self._argv, stdin=subprocess.PIPE, + stdout=subprocess.PIPE, stderr=subprocess.PIPE, + env=None if self._env is None else dict(os.environ, **self._env), + start_new_session=True) + self._process = process + try: + # Cancellation may have arrived while Popen was creating the process. + if self._reason is not None: + self._signal(force=True) + with selectors.DefaultSelector() as selector: + for index, stream in enumerate((process.stdout, process.stderr)): + os.set_blocking(stream.fileno(), False) + selector.register(stream, selectors.EVENT_READ, index) + pending = memoryview(self._input) + if pending: + os.set_blocking(process.stdin.fileno(), False) + selector.register(process.stdin, selectors.EVENT_WRITE, 2) + else: + process.stdin.close() + while selector.get_map(): + for key, _ in selector.select(0.02): + if key.data == 2: + try: + pending = pending[os.write(key.fd, pending[:8192]):] + except BrokenPipeError: + pending = pending[:0] + except BlockingIOError: + continue + if not pending: + selector.unregister(key.fileobj) + key.fileobj.close() + else: + try: + data = os.read(key.fd, 8192) + except BlockingIOError: + continue + if data: + self._capture(key.data, data) + else: + selector.unregister(key.fileobj) + key.fileobj.close() + if self._reason is not None and time.monotonic() >= self._cancelled_at + self.stop_timeout: + self._signal(force=True) + break + while process.poll() is None: + if self._reason is not None and time.monotonic() >= self._cancelled_at + self.stop_timeout: + self._signal(force=True) + break + time.sleep(0.02) + self._status = process.wait(timeout=1) + finally: + if process.poll() is None: + self._signal(force=True) + try: + self._status = process.wait(timeout=1) + except subprocess.TimeoutExpired: + pass + for stream in (process.stdin, process.stdout, process.stderr): + stream.close() + + def _run_remote(self): + remaining = None if self._deadline is None else max(0.001, self._deadline - time.monotonic()) + channel = self._client.get_transport().open_session(timeout=remaining) + self._channel = channel + if self._reason is not None: + channel.close() + return + if self._pty: + channel.get_pty() + if self._env: + channel.update_environment(self._env) + channel.exec_command('exec ' + shlex.join(self._argv)) + channel.settimeout(0.0) + pending = memoryview(self._input) + eof_sent = False + while True: + made_progress = False + # Read only one bounded chunk per stream per turn: a busy stdout + # must not starve stderr, stdin, completion or cancellation. + for index, ready, read in ((0, channel.recv_ready, channel.recv), + (1, channel.recv_stderr_ready, channel.recv_stderr)): + if ready(): + data = read(8192) + if data: + self._capture(index, data) + made_progress = True + if pending and channel.send_ready(): + sent = channel.send(pending[:8192].tobytes()) + if sent == 0: + raise BrokenPipeError('SSH stdin closed before input was sent') + pending = pending[sent:] + if not pending and not eof_sent: + # Keep PTY input open so stop() can send Ctrl-C. + if not self._pty: + channel.shutdown_write() + eof_sent = True + if channel.exit_status_ready() and not channel.recv_ready() and not channel.recv_stderr_ready() and (channel.eof_received or channel.closed): + status = channel.recv_exit_status() + self._status = None if status == -1 else status + if self._status is None and self._reason is None: + raise EOFError('SSH channel closed without an exit status') + return + if channel.closed and not channel.recv_ready() and not channel.recv_stderr_ready(): + if self._reason is None: + raise EOFError('SSH channel closed before command completion') + return + if not made_progress: + time.sleep(0.01) + + def wait(self): + """Wait for completion. The job's deadline continues while nobody waits.""" + self._done.wait() + if self._result.stop_reason == 'timeout': + raise CommandTimeoutError(self._result, self.timeout) + if self._error is not None: + raise self._error + if self.check and self._result.stop_reason == 'completed' and self._result.exitcode != 0: + error = subprocess.CalledProcessError(self._result.exitcode, self.command, + output=self._result.stdout, stderr=self._result.stderr) + error.result = self._result + raise error + return self._result + + def stop(self): + """Request user cancellation, finish bounded cleanup, return JobResult. + + An unconfirmed remote stop is returned as termination_status='unknown'. + An earlier deadline still raises CommandTimeoutError. + """ + self._request_stop('cancelled') + return self.wait() + + def iter_stdout(self): + """Yield decoded text chunks; fail explicitly if the consumer falls behind.""" + decoder = codecs.getincrementaldecoder('utf-8')(errors='replace') + while True: + with self._condition: + self._condition.wait_for(lambda: self._chunks or self.done) + if self.dropped_stdout_chunks: + raise BufferError('stdout consumer fell behind; use faster streaming or redirect output at the source') + data = self._chunks.popleft() if self._chunks else None + if data is None and self.done: + break + text = decoder.decode(data) + if text: + yield text + text = decoder.decode(b'', final=True) + if text: + yield text + self.wait() + + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_value, traceback): + try: + self.stop() if not self.done else self.wait() + except Exception as exc: + if exc_value is None: + raise + if exc is not exc_value and not ( + isinstance(exc, CommandTimeoutError) + and isinstance(exc_value, CommandTimeoutError) + and exc.result is exc_value.result + ): + exc_value.add_note(f'command cleanup also raised {type(exc).__name__}') + return False diff --git a/src/sshscript/commandjob.pyi b/src/sshscript/commandjob.pyi new file mode 100644 index 0000000..a21f2c3 --- /dev/null +++ b/src/sshscript/commandjob.pyi @@ -0,0 +1,45 @@ +from dataclasses import dataclass +from types import TracebackType +from typing import Iterator +from .commandresult import CommandResult + +@dataclass(frozen=True) +class JobResult(CommandResult[int | None]): + stop_reason: str = ... + termination_status: str = ... + stdout_truncated: bool = ... + stderr_truncated: bool = ... + +class CommandTimeoutError(TimeoutError): + result: JobResult + command: str | tuple[str, ...] + host: str | None + timeout: float + elapsed: float + stdout: str + stderr: str + termination_status: str + def __init__(self, result: JobResult, timeout: float) -> None: ... + +class CommandJob: + command: str | tuple[str, ...] + host: str | None + timeout: float | None + stop_timeout: float + capture_limit: int + check: bool + dropped_stdout_chunks: int + @property + def done(self) -> bool: ... + @property + def stdout(self) -> str: ... + @property + def stderr(self) -> str: ... + @property + def exitcode(self) -> int | None: ... + def clear(self) -> None: ... + def wait(self) -> JobResult: ... + def stop(self) -> JobResult: ... + def iter_stdout(self) -> Iterator[str]: ... + def __enter__(self) -> CommandJob: ... + def __exit__(self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None) -> bool: ... diff --git a/src/sshscript/commandresult.py b/src/sshscript/commandresult.py index 984761c..bb55903 100644 --- a/src/sshscript/commandresult.py +++ b/src/sshscript/commandresult.py @@ -1,9 +1,12 @@ """Immutable snapshots of completed commands.""" from dataclasses import dataclass +from typing import Generic, TypeVar + +_Status = TypeVar("_Status", bound=int | None) @dataclass(frozen=True) -class CommandResult: +class CommandResult(Generic[_Status]): """One completed command, with text output and elapsed monotonic seconds. Three-value unpacking/indexing yields ``stdout, stderr, exitcode``. @@ -13,7 +16,7 @@ class CommandResult: stdout: str stderr: str - exitcode: int + exitcode: _Status host: str | None duration: float command: str | tuple[str, ...] diff --git a/src/sshscript/commandresult.pyi b/src/sshscript/commandresult.pyi new file mode 100644 index 0000000..c6a7441 --- /dev/null +++ b/src/sshscript/commandresult.pyi @@ -0,0 +1,18 @@ +from dataclasses import dataclass +from typing import Generic, Iterator, TypeVar, overload + +_Status = TypeVar('_Status', bound=int | None) +@dataclass(frozen=True) +class CommandResult(Generic[_Status]): + stdout: str + stderr: str + exitcode: _Status + host: str | None + duration: float + command: str | tuple[str, ...] + def __iter__(self) -> Iterator[str | _Status]: ... + def __len__(self) -> int: ... + @overload + def __getitem__(self, index: int) -> str | _Status: ... + @overload + def __getitem__(self, index: slice) -> tuple[str | _Status, ...]: ... diff --git a/src/sshscript/dollar.py b/src/sshscript/dollar.py index 12888cc..bd31712 100755 --- a/src/sshscript/dollar.py +++ b/src/sshscript/dollar.py @@ -22,10 +22,12 @@ import threading if __package__: + from .sessionsettings import SessionLogger from .errorutils import command_requires_shell, command_summary, get_logger from .channelsubprocess import POpenChannel from .channelssh import SSHChannel else: + from sessionsettings import SessionLogger from errorutils import command_requires_shell, command_summary, get_logger from channelsubprocess import POpenChannel from channelssh import SSHChannel @@ -68,6 +70,8 @@ def __init__(self,session,command=None,for_with=False,use_shell=None, self.command = command self.argv = None self.session = session # Session instance in context + self.settings = session.get() + self.logger = SessionLogger(self.settings) self.channel = None self.use_shell = use_shell self.shell_executable = shell_executable @@ -164,7 +168,7 @@ def task_exception_handler(t): newloop.stop() except Exception as exc: self._worker_exception = exc - logger.debug( + self.logger.debug( 'Command worker failed (exception_type=%s)', type(exc).__name__, ) @@ -186,7 +190,7 @@ def task_exception_handler(task): if self.channel is not None: self.channel.fail(exc) - logger.debug( + self.logger.debug( 'Command worker failed (exception_type=%s)', type(exc).__name__, ) @@ -291,7 +295,7 @@ async def exec_by_subprocess(self,get_pty:bool): cpargs = shlex.split(self.command) summary = command_summary(cpargs) if get_pty: - logger.debug( + self.logger.debug( 'Starting interactive subprocess ' '(executable=%s, pty=%s, argc=%d)', summary['executable'], @@ -378,7 +382,7 @@ async def exec_by_subprocess(self,get_pty:bool): await self.channel.async_start_interaction() elif 1: - logger.debug( + self.logger.debug( 'Starting interactive subprocess ' '(executable=%s, pty=%s, argc=%d)', summary['executable'], @@ -420,7 +424,7 @@ async def exec_by_subprocess(self,get_pty:bool): ) ''' else: - logger.debug('Starting interactive subprocess without a PTY') + self.logger.debug('Starting interactive subprocess without a PTY') ## pros: ## su (get_pty=False) works and stderr does not mixed with stdout ## cons: @@ -468,7 +472,7 @@ async def exec_by_subprocess(self,get_pty:bool): ## with_pty is always False self.channel = POpenChannel(self,None,None,None,[],False) self.channel.increase_layer('') - logger.debug( + self.logger.debug( 'Executing subprocess ' '(executable=%s, shell=%s, pty=%s, argc=%d, ' 'shell_reasons=%s, command_length=%d)', @@ -542,7 +546,7 @@ async def exec_by_ssh(self,get_pty:bool)->None: summary = command_summary(argv) argc = summary['arg_count'] - logger.debug( + self.logger.debug( 'Executing SSH command ' '(host=%s, executable=%s, shell=%s, pty=%s, argc=%s, ' 'shell_reasons=%s, command_length=%d)', @@ -582,7 +586,7 @@ async def exec_by_ssh(self,get_pty:bool)->None: await self.channel._add_stderr_data(stderr_data) await self.channel._dump_stdout_err() self.channel._exitcode = stdout.channel.recv_exit_status() - logger.debug( + self.logger.debug( 'SSH command completed (host=%s, exit_code=%s)', host, self.exitcode, diff --git a/src/sshscript/dollarchanger.py b/src/sshscript/dollarchanger.py index 1dbdd07..9b4b89a 100755 --- a/src/sshscript/dollarchanger.py +++ b/src/sshscript/dollarchanger.py @@ -229,7 +229,19 @@ def callback(node): or \ (isinstance(nodeitem.context_expr.func.value, ast.Subscript) and isinstance(nodeitem.context_expr.func.value.value,ast.Name) and nodeitem.context_expr.func.value.value.id == '_sshscriptstack_') ): - if nodeitem.context_expr.func.attr in ('connect','open'): + if nodeitem.context_expr.func.attr == 'start': + # A managed job owns a command, not a new Session/console. + # Keep dollar commands in its body on the current Session. + nodeitem.managed_job = True + if self.currentConsole: + nodeitem.context_expr.func.value = ast.copy_location( + ast.Name(id=self.currentConsole[-1], ctx=ast.Load()), + nodeitem.context_expr.func.value, + ) + else: + nodeitem.context_expr.func.value = self._template( + self.tmplLineForSSHScriptInstance.value, nodeitem.context_expr) + elif nodeitem.context_expr.func.attr in ('connect','open'): ## self.tmplLineForSSHScriptInstance is an ast.Expr, so we need to take .value if len(self.currentConsole): nodeitem.context_expr.func.value.id = self.currentConsole[-1] @@ -504,7 +516,7 @@ def _callback_(node): newnode.args = node.args[:] newnode.keywords = node.keywords[:] elif isinstance(node, ast.withitem): - self.insideWithitem = True + self.insideWithitem = not getattr(node, 'managed_job', False) elif isinstance(node,ast.Name) and node.id in ('_sshscript_in_context_', '_sshscriptstack_'): self.containsSSHScriptStack[-1] = True diff --git a/src/sshscript/patching.py b/src/sshscript/patching.py index 8a587d5..8816fe8 100755 --- a/src/sshscript/patching.py +++ b/src/sshscript/patching.py @@ -20,6 +20,7 @@ session stack. Ordinary Python threads do not implicitly inherit that context. """ +import contextvars import functools import threading import weakref @@ -160,6 +161,7 @@ def context_thread( registered only for its run and discarded in finally; this does not patch threading.Thread or close the inherited sessions. """ + execution_context = contextvars.copy_context() parent_stack = peek_thread_stack() initial_stack = ( parent_stack.snapshot() if parent_stack is not None else [] @@ -176,7 +178,7 @@ def wrapped_target(*target_args, **target_kwargs): ) set_thread_stack(stack) try: - return target(*target_args, **target_kwargs) + return execution_context.run(target, *target_args, **target_kwargs) finally: clear_thread_stack() diff --git a/src/sshscript/py.typed b/src/sshscript/py.typed new file mode 100644 index 0000000..e69de29 diff --git a/src/sshscript/session.py b/src/sshscript/session.py index eaf8d9b..b5b5184 100755 --- a/src/sshscript/session.py +++ b/src/sshscript/session.py @@ -23,6 +23,7 @@ import patching import ast +import contextvars import threading import paramiko import stat @@ -38,8 +39,11 @@ import subprocess import socket import shlex +import weakref from select import select if __package__: + from .sessionsettings import UNSET, validate, root_defaults, SessionLogger + from .commandjob import CommandJob, CommandTimeoutError, JobResult from .commandresult import CommandResult from .sshconfig import resolve_connection from .dollar import Dollar @@ -49,6 +53,8 @@ from . import dollarparser else: + from sessionsettings import UNSET, validate, root_defaults, SessionLogger + from commandjob import CommandJob, CommandTimeoutError, JobResult from commandresult import CommandResult from sshconfig import resolve_connection ## called directly from the same folder @@ -59,6 +65,7 @@ import dollarparser ## setup logger +_COMMAND_TIMEOUT_UNSET = object() logger = get_logger() SSHScriptExportedNames = set(['sftp','client','logger']) # default to exposed properties SSHScriptExportedNamesByAlias = {} @@ -350,13 +357,35 @@ def __init__(self,parent=None): self.lineNumberCount = 0 - self.logger = logger + self._settings = parent.get() if parent is not None else root_defaults() + self.logger = SessionLogger(self._settings) ## when exec_command() or withdollar() was called, ## this value was stored, so user can access its stdout, stderr and exitcode ## by self.stdout and self.stderr, self.exitcode self._lastDollar = None self.last_result = None + self._jobs = weakref.WeakSet() self._attached_stack = None + @export2Dollar + def set(self, **settings): + """Atomically update this Session's validated execution policy.""" + values = validate(settings) + self._settings.update(values) + + @export2Dollar + def get(self, name=None): + """Return a setting, or an independent copy of all effective settings.""" + if name is None: + return dict(self._settings) + if name not in self._settings: + raise ValueError(f'unknown Session setting: {name}') + return self._settings[name] + + check = property(lambda self: self.get('check'), lambda self, v: self.set(check=v)) + verbose = property(lambda self: self.get('verbose'), lambda self, v: self.set(verbose=v)) + verbose_stderr = property(lambda self: self.get('verbose_stderr'), lambda self, v: self.set(verbose_stderr=v)) + log_level = property(lambda self: self.get('log_level'), lambda self, v: self.set(log_level=v)) + ## added in v2.0.3 ## always return the session which is not connected to execute commands by subprocess at localhost @property @@ -564,12 +593,12 @@ def local_session(self): return p @export2Dollar('break') def _break(self,code=0,message=''): - logger.debug('Script requested break (exit_code=%s)', code) + self.logger.debug('Script requested break (exit_code=%s)', code) raise SSHScriptBreak(message,code) @export2Dollar def exit(self,code=0,message=''): - logger.debug('Script requested exit (exit_code=%s)', code) + self.logger.debug('Script requested exit (exit_code=%s)', code) raise SSHScriptExit(message,code) @export2Dollar @@ -619,7 +648,7 @@ def connect(self,host,username=None,password=None,port=None,policy=None,*,ssh_co kw = effective has_proxy = 'proxyCommand' in kw - logger.debug( + self.logger.debug( 'Opening SSH connection (host=%s, port=%s, username=%s, nested=%s, proxy=%s)', host, port, @@ -640,7 +669,7 @@ def connect_client(host,username,password,port,policy,**kw): try: client.close() except BaseException as cleanup_exc: - logger.warning( + self.logger.warning( 'Unable to close SSH client after connection failure ' '(host=%s, exception_type=%s)', host, @@ -676,7 +705,7 @@ def connect_client(host,username,password,port,policy,**kw): try: if is_nested: ## a nested connection - logger.debug( + self.logger.debug( 'Opening nested SSH transport (host=%s, port=%s, username=%s)', host, port, @@ -688,7 +717,7 @@ def connect_client(host,username,password,port,policy,**kw): subsession._sock = self._client.get_transport().open_channel("direct-tcpip", dest_addr, local_addr) subsession._client = connect_client(host,username,password,port,policy,sock=subsession._sock,**kw) elif has_proxy: - logger.debug( + self.logger.debug( 'Opening SSH connection through proxy command ' '(host=%s, port=%s, username=%s)', host, @@ -702,7 +731,7 @@ def connect_client(host,username,password,port,policy,**kw): kw.setdefault('auth_timeout', 30) subsession._client = connect_client(host,username,password,port,policy,sock=subsession._sock,**kw) else: - logger.debug( + self.logger.debug( 'Opening direct SSH transport (host=%s, port=%s, username=%s)', host, port, @@ -716,7 +745,7 @@ def connect_client(host,username,password,port,policy,**kw): keepAliveInterval ) - logger.debug( + self.logger.debug( 'Configured SSH keepalive (host=%s, interval_seconds=%s)', host, keepAliveInterval, @@ -736,7 +765,7 @@ def connect_client(host,username,password,port,policy,**kw): try: subsession.close() except BaseException as cleanup_exc: - logger.warning( + self.logger.warning( 'Unable to clean up failed SSH connection ' '(host=%s, exception_type=%s)', host, @@ -984,6 +1013,7 @@ def executeScript(script,_vars,showScript=False): raise TimeoutError('Timed out waiting for the script execution lock') + execution_context = contextvars.copy_context() def runner(*args): runSession = f"{self.host}:{threading.current_thread().native_id}" started_at = time.monotonic() @@ -992,7 +1022,7 @@ def runner(*args): exception_type = None ret = {} try: - ret['value'] = executeScript(*args) + ret['value'] = execution_context.run(executeScript, *args) except SystemExit as e: ret['system_exit'] = e outcome = 'system_exit' @@ -1008,7 +1038,7 @@ def runner(*args): outcome = 'error' exception_type = type(e).__name__ finally: - logger.debug( + self.logger.debug( 'Script execution finished ' '(session=%s, outcome=%s, exit_code=%s, exception_type=%s, duration_ms=%d)', runSession, @@ -1039,10 +1069,63 @@ def clear(self): if self._lastDollar: self._lastDollar.clear() - def exec_command(self,cmd,*,shell=None,shell_executable=None,check=False, + @export2Dollar + def start(self, cmd, *, shell=None, shell_executable=None, timeout=None, + stop_timeout=3, capture_limit=1024 * 1024, check=UNSET, + input=None, env=None, get_pty=False): + """Start an owned command; use its context manager, stop(), and wait(). + + timeout is a total command budget on both backends, None is unlimited. + Capture retains bounded output tails. iter_stdout() streams text chunks. + start() does not change Session.last_result or the legacy output buffers. + Local PTYs are unsupported here; use enter() for interactive local tools. + """ + if check is UNSET: + check = self.check + if self.closed: + raise RuntimeError('cannot execute on a closed session') + if self._client is not None and not self.connected: + raise BrokenPipeError('SSH transport is not active') + argv = None + if isinstance(cmd, (list, tuple)): + if not cmd or not all(isinstance(arg, str) for arg in cmd): + if not cmd: + raise ValueError('argument sequence must be nonempty') + raise TypeError('every command argument must be str') + if not cmd[0] or any('\x00' in arg for arg in cmd): + raise ValueError('executable must be nonempty and arguments cannot contain NUL') + if (shell is not None and shell is not False) or shell_executable is not None: + raise ValueError('argument sequences require shell=None or shell=False') + argv = tuple(cmd) + cmd = shlex.join(argv) + shell = False + elif not isinstance(cmd, str): + raise TypeError('command must be str, list, or tuple') + if not cmd.strip() or '\x00' in cmd: + raise ValueError('command must be nonempty and cannot contain NUL') + if isinstance(shell, str): + if shell_executable is not None: + raise ValueError('use either shell="name" or shell_executable, not both') + shell_executable, shell = shell, True + elif shell is not None and not isinstance(shell, bool): + raise TypeError('shell must be None, bool, or a shell executable name') + execution = Dollar(self, cmd, use_shell=shell, shell_executable=shell_executable) + execution.argv = argv + job = CommandJob(self, execution, timeout=timeout, stop_timeout=stop_timeout, + capture_limit=capture_limit, check=check, input=input, + env=env, get_pty=get_pty) + self._jobs.add(job) + return job._launch() + + def exec_command(self,cmd,*,shell=None,shell_executable=None,check=UNSET, + command_timeout=_COMMAND_TIMEOUT_UNSET, _legacy_twodollars=False,**kw): """Execute one command and return a CommandResult; also session(cmd). + command_timeout opts into a total deadline on both backends (None means + unlimited), bounded capture and CommandTimeoutError. Legacy timeout keeps + its subprocess/Paramiko meaning; specifying both is an error. + Wait for completion on this session's host. stdout, stderr, and exitcode remain available on the session as the latest command result. Check exitcode for command failure; execution/transport errors propagate. check=True @@ -1066,6 +1149,26 @@ def exec_command(self,cmd,*,shell=None,shell_executable=None,check=False, stdout, stderr, exitcode = session("cat", input="hello") status = session.exitcode """ + if check is UNSET: + check = self.check + if command_timeout is not _COMMAND_TIMEOUT_UNSET: + if 'timeout' in kw: + raise ValueError('use command_timeout or legacy timeout, not both') + if _legacy_twodollars: + shell = True + job = self.start(cmd, shell=shell, shell_executable=shell_executable, + timeout=command_timeout, check=check, **kw) + self._lastDollar = job + self.last_result = None + try: + with job: + result = job.wait() + except subprocess.CalledProcessError as exc: + self.last_result = exc.result + raise + self.last_result = result + return result + if self.closed: raise RuntimeError('cannot execute on a closed session') if self._client is not None and not self.connected: @@ -1330,6 +1433,17 @@ def close(self, strict=False): return not close_errors cleanup_errors = [] + for job in tuple(getattr(self, '_jobs', ())): + if not job.done: + try: + result = job.stop() + if result.termination_status == 'unknown': + cleanup_errors.append(('stop command', RuntimeError('command termination is unconfirmed'))) + except CommandTimeoutError as exc: + if exc.termination_status == 'unknown': + cleanup_errors.append(('stop command', exc)) + except Exception as exc: + cleanup_errors.append(('stop command', exc)) transport = None for subsession in reversed(tuple(self.subsessions)): @@ -1364,7 +1478,7 @@ def close(self, strict=False): self._client.close() except Exception as exc: cleanup_errors.append(('close SSH client', exc)) - logger.debug( + self.logger.debug( 'Unable to close SSH client cleanly ' '(host=%s, exception_type=%s)', self.host, @@ -1397,7 +1511,7 @@ def close(self, strict=False): )) if forced_kill: - logger.warning( + self.logger.warning( 'Proxy command required forced termination ' '(host=%s, pid=%s)', self.host, @@ -1415,7 +1529,7 @@ def close(self, strict=False): self._sock = None except Exception as exc: cleanup_errors.append(('clean up SSH socket', exc)) - logger.debug( + self.logger.debug( 'Unable to close SSH socket cleanly ' '(host=%s, exception_type=%s)', self.host, @@ -1426,7 +1540,7 @@ def close(self, strict=False): if self.host is not None: - logger.debug( + self.logger.debug( 'SSH connection closed (host=%s, port=%s, username=%s)', self.host, self.port, @@ -1444,14 +1558,14 @@ def close(self, strict=False): try: self.parent.subsessions.remove(self) except ValueError: - logger.debug( + self.logger.debug( 'Session is not registered with its parent ' '(session=%s, parent=%s)', self, self.parent, ) else: - logger.debug( + self.logger.debug( 'Removed session from its parent session (session=%s, parent=%s)', self, self.parent, @@ -1460,7 +1574,7 @@ def close(self, strict=False): self.close_errors = tuple(cleanup_errors) for operation, exc in self.close_errors: - logger.warning( + self.logger.warning( 'Session cleanup step failed ' '(operation=%s, exception_type=%s)', operation, diff --git a/src/sshscript/session.pyi b/src/sshscript/session.pyi new file mode 100644 index 0000000..9ba0712 --- /dev/null +++ b/src/sshscript/session.pyi @@ -0,0 +1,67 @@ +from os import PathLike +from types import TracebackType +from typing import Any, ContextManager, Literal, TypedDict, overload +from .commandjob import CommandJob, CommandTimeoutError as CommandTimeoutError, JobResult +from .commandresult import CommandResult as CommandResult +from .sessionwrapper import SessionWrapper + +Command = str | list[str] | tuple[str, ...] +class SessionSettings(TypedDict): + check: bool + verbose: bool + verbose_stderr: bool + log_level: int + +class Session: + closed: bool + last_result: CommandResult[int] | JobResult | None + close_errors: tuple[tuple[str, Exception], ...] + logger: Any + check: bool + verbose: bool + verbose_stderr: bool + @property + def log_level(self) -> int: ... + @log_level.setter + def log_level(self, value: int | str) -> None: ... + def __init__(self, parent: Session | None = ...) -> None: ... + def set(self, *, check: bool = ..., verbose: bool = ..., verbose_stderr: bool = ..., log_level: int | str = ...) -> None: ... + @overload + def get(self, name: None = ...) -> SessionSettings: ... + @overload + def get(self, name: Literal['check', 'verbose', 'verbose_stderr']) -> bool: ... + @overload + def get(self, name: Literal['log_level']) -> int: ... + @overload + def get(self, name: str) -> bool | int: ... + @property + def host(self) -> str | None: ... + @property + def connected(self) -> bool: ... + @property + def stdout(self) -> Any: ... + @property + def stderr(self) -> Any: ... + @property + def exitcode(self) -> int | None: ... + @overload + def exec_command(self, cmd: Command, *, shell: bool | str | None = ..., shell_executable: str | None = ..., check: bool = ..., command_timeout: float | None, **kw: Any) -> JobResult: ... + @overload + def exec_command(self, cmd: Command, *, shell: bool | str | None = ..., shell_executable: str | None = ..., check: bool = ..., **kw: Any) -> CommandResult[int]: ... + __call__ = exec_command + send_line = exec_command + def start(self, cmd: Command, *, shell: bool | str | None = ..., shell_executable: str | None = ..., timeout: float | None = ..., stop_timeout: float = ..., capture_limit: int = ..., check: bool = ..., input: str | bytes | None = ..., env: dict[str, str] | None = ..., get_pty: bool = ...) -> CommandJob: ... + def connect(self, host: str, username: str | None = ..., password: str | None = ..., port: int | None = ..., policy: Any = ..., *, ssh_config: str | PathLike[str] | bool | None = ..., **kw: Any) -> Session: ... + @staticmethod + def resolve_connection(host: str, **kwargs: Any) -> dict[str, Any]: ... + def shell(self, command: str | None = ..., funcname: str = ..., get_pty: bool = ..., *args: Any, **kw: Any) -> ContextManager[SessionWrapper]: ... + def enter(self, command: str, expect: Any = ..., password: str | None = ..., exit: str | None = ..., shell: bool = ..., get_pty: bool = ..., prompt: Any = ...) -> ContextManager[SessionWrapper]: ... + def sudo(self, password: str | None = ..., username: str | None = ..., expect: Any = ..., initials: Any = ..., shell: bool = ..., login: bool = ..., get_pty: bool = ...) -> ContextManager[SessionWrapper]: ... + def su(self, username: str, password: str | None = ..., expect: Any = ..., initials: Any = ..., shell: bool = ..., login: bool = ..., get_pty: bool = ...) -> ContextManager[SessionWrapper]: ... + def upload(self, src: str | PathLike[str], dst: str, makedirs: bool = ..., overwrite: bool = ...) -> tuple[str, str]: ... + def download(self, src: str, dst: str | PathLike[str] | None = ...) -> tuple[str, str]: ... + def clear(self) -> None: ... + def close(self, strict: bool = ...) -> bool: ... + disconnect = close + def __enter__(self) -> Session: ... + def __exit__(self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None) -> bool: ... diff --git a/src/sshscript/sessionsettings.py b/src/sshscript/sessionsettings.py new file mode 100644 index 0000000..232b231 --- /dev/null +++ b/src/sshscript/sessionsettings.py @@ -0,0 +1,86 @@ +"""Validated Session policies and context-local CLI defaults.""" +from contextlib import contextmanager +from contextvars import ContextVar +import logging +import os +from types import MappingProxyType + +DEFAULTS = MappingProxyType(dict(check=False, verbose=False, verbose_stderr=False, + log_level=logging.INFO)) +UNSET = object() +_defaults = ContextVar('sshscript_execution_defaults', default={}) + + +def validate(values): + result = dict(values) + for key, value in result.items(): + if key not in DEFAULTS: + raise ValueError(f'unknown Session setting: {key}') + if key == 'log_level': + if isinstance(value, str): + value = logging.getLevelName(value.upper()) + if not isinstance(value, int): + raise ValueError("unknown log_level name") + if isinstance(value, bool) or not isinstance(value, int): + raise TypeError('log_level must be a logging level number or name') + if value < 0: + raise ValueError('log_level must be nonnegative') + result[key] = value + elif not isinstance(value, bool): + raise TypeError(f'{key} must be bool') + return result + + +def root_defaults(): + # Preserve explicit application logging and legacy environment configuration. + if __package__: + from .errorutils import get_logger + else: + from errorutils import get_logger + values = dict(DEFAULTS, log_level=get_logger().getEffectiveLevel(), + verbose=bool(os.environ.get('VERBOSE')), + verbose_stderr=bool(os.environ.get('VERBOSE_STDERR'))) + values.update(_defaults.get()) + return values + + +@contextmanager +def execution_defaults(**values): + token = _defaults.set(dict(_defaults.get(), **validate(values))) + try: + yield + finally: + _defaults.reset(token) + + +class SessionLogger: + """Filter by session policy without changing a shared logger's level. + + Application handler levels, logger filters, and logging.disable still apply. + """ + def __init__(self, settings): + self.settings = settings + + def log(self, level, message, *args, **kwargs): + if level < self.settings['log_level']: + return + if __package__: + from .errorutils import get_logger + else: + from errorutils import get_logger + target = get_logger()._logger + if target.disabled or level <= logging.root.manager.disable: + return + # _log creates and handles a record without the shared isEnabledFor gate. + target._log(level, message, args, **kwargs) + + def debug(self, msg, *args, **kw): self.log(logging.DEBUG, msg, *args, **kw) + def info(self, msg, *args, **kw): self.log(logging.INFO, msg, *args, **kw) + def warning(self, msg, *args, **kw): self.log(logging.WARNING, msg, *args, **kw) + def error(self, msg, *args, **kw): self.log(logging.ERROR, msg, *args, **kw) + def critical(self, msg, *args, **kw): self.log(logging.CRITICAL, msg, *args, **kw) + def exception(self, msg, *args, **kw): + kw.setdefault('exc_info', True) + self.error(msg, *args, **kw) + def isEnabledFor(self, level): + return level >= self.settings['log_level'] diff --git a/src/sshscript/sessionwrapper.py b/src/sshscript/sessionwrapper.py index 6c07a91..9967102 100755 --- a/src/sshscript/sessionwrapper.py +++ b/src/sshscript/sessionwrapper.py @@ -16,9 +16,13 @@ """Public console operations over a channel shared by shell and interactive contexts.""" +import subprocess + if __package__: + from .sessionsettings import UNSET from . import patching else: + from sessionsettings import UNSET import patching if __package__: @@ -108,14 +112,37 @@ def input(self,s,timeout=60): #result.result() return result - def send_line(self,s,**expections): + def set(self, **settings): + """Configure the owning Session, including from $.set inside a shell.""" + self.channel.owner.session.set(**settings) + + def get(self, name=None): + return self.channel.owner.session.get(name) + + def send_line(self,s,*,check=UNSET,**expections): """Execute a shell command and return (stdout, stderr); also console(command). + check inherits the Session policy unless explicitly supplied. command_timeout bounds command completion (default 60 seconds). Other keyword names are expected patterns and their values are reply strings. In an enter() context this delegates to input() and returns its status. """ - return self.channel.send_line(s,**expections) + session = self.channel.owner.session + enabled = session.check if check is UNSET else check + if not isinstance(enabled, bool): + raise TypeError('check must be bool') + # Interactive input is not a command exit-status boundary. + if self.channel.hijacked: + return self.channel.send_line(s, **expections) + settings = session.get() + self.channel.dump2sys = (int(settings['verbose']), int(settings['verbose'] or settings['verbose_stderr'])) + self.channel.logger.settings = settings + result = self.channel.send_line(s, **expections) + if enabled and self.channel.exitcode != 0: + stdout, stderr = result + raise subprocess.CalledProcessError(self.channel.exitcode, s, + output=str(stdout), stderr=str(stderr)) + return result ## alias for sendline __call__ = send_line exec_command = send_line diff --git a/src/sshscript/sessionwrapper.pyi b/src/sshscript/sessionwrapper.pyi new file mode 100644 index 0000000..f5cbad1 --- /dev/null +++ b/src/sshscript/sessionwrapper.pyi @@ -0,0 +1,19 @@ +from typing import Any + +class SessionWrapper: + @property + def stdout(self) -> Any: ... + @property + def stderr(self) -> Any: ... + @property + def exitcode(self) -> int: ... + @property + def closed(self) -> bool: ... + def set(self, *, check: bool = ..., verbose: bool = ..., verbose_stderr: bool = ..., log_level: int | str = ...) -> None: ... + def get(self, name: str | None = ...) -> Any: ... + def send_line(self, s: str, *, check: bool = ..., **expectations: Any) -> tuple[Any, Any] | str | None: ... + __call__ = send_line + exec_command = send_line + def send(self, s: str) -> None: ... + def input(self, s: str, timeout: float = ...) -> str | None: ... + def expect(self, rawpat: Any, **kwargs: Any) -> Any: ... diff --git a/src/sshscript/sshscript.py b/src/sshscript/sshscript.py index 9d52efd..88caa66 100755 --- a/src/sshscript/sshscript.py +++ b/src/sshscript/sshscript.py @@ -32,7 +32,8 @@ def warning_on_one_line(message, category, filename, lineno, file=None, line=Non return '%s:%s: %s: %s\n' % (filename, lineno, category.__name__, message) if __package__: from ._version import __version__ - from .session import Session, CommandResult + from .sessionsettings import execution_defaults + from .session import Session, CommandResult, CommandJob, CommandTimeoutError, JobResult from .errorutils import SSHScriptExit, SSHScriptBreak, get_logger, set_logger, SSHScriptException,command_summary ## 2025/3/3 v2.0.3 feature: import *.spy file directly from . import spyimporter @@ -42,7 +43,8 @@ def warning_on_one_line(message, category, filename, lineno, file=None, line=Non mydir = os.path.abspath(os.path.dirname(__file__)) if not mydir in sys.path: sys.path.insert(0,mydir) from _version import __version__ - from session import Session, CommandResult + from sessionsettings import execution_defaults + from session import Session, CommandResult, CommandJob, CommandTimeoutError, JobResult from errorutils import SSHScriptExit, SSHScriptBreak, get_logger, set_logger, SSHScriptException,command_summary import spyimporter import dollarparser @@ -355,14 +357,13 @@ def get_current_version(): sys.argv[0] = args.path - if args.debug: - os.environ['DEBUG'] = str(args.debug) - logger.reset_debug() - + policy = {} + if args.debug is not None: + policy['log_level'] = max(10, args.debug) if args.verbose: - os.environ['VERBOSE'] = '1' + policy['verbose'] = True elif args.verbose_stderr: - os.environ['VERBOSE_STDERR'] = '1' + policy.update(verbose=False, verbose_stderr=True) try: if args.check: @@ -372,10 +373,11 @@ def get_current_version(): parser.error('--check and --script cannot be combined') exitcode = check_file(args.path) else: - exitcode = run_file( - args.path, - showScript=args.showScript, - ) + with execution_defaults(**policy): + exitcode = run_file( + args.path, + showScript=args.showScript, + ) except SSHScriptExit as e: sys.exit(e.errno) except SSHScriptException as e: diff --git a/src/sshscript/unittest/test_command_job.py b/src/sshscript/unittest/test_command_job.py new file mode 100644 index 0000000..3cd0658 --- /dev/null +++ b/src/sshscript/unittest/test_command_job.py @@ -0,0 +1,297 @@ +"""Managed command contracts using processes and real Paramiko over socketpair.""" +import os +import signal +import socket +import subprocess +import sys +import threading +import time +import unittest +from unittest.mock import Mock, patch + +import paramiko +from session import Session, CommandTimeoutError +import sshscript + + +class Server(paramiko.ServerInterface): + def __init__(self): + self.processes = [] + self.workers = [] + self.release = threading.Event() + + def check_auth_none(self, username): + return paramiko.AUTH_SUCCESSFUL + + def check_channel_request(self, kind, chanid): + return paramiko.OPEN_SUCCEEDED + + def check_channel_pty_request(self, *args): + return True + + def check_channel_exec_request(self, channel, command): + if command == b'exec stall-ack': + self.release.wait(3) + return False + def execute(): + process = subprocess.Popen(command.decode(), shell=True, stdout=subprocess.PIPE, + stderr=subprocess.PIPE, stdin=subprocess.DEVNULL, + start_new_session=True) + self.processes.append(process) + def pump(stream, send): + try: + while data := os.read(stream.fileno(), 8192): + send(data) + except (OSError, EOFError): + pass + pumps = [threading.Thread(target=pump, args=(process.stdout, channel.sendall), daemon=True), + threading.Thread(target=pump, args=(process.stderr, channel.sendall_stderr), daemon=True)] + for thread in pumps: + thread.start() + try: + status = process.wait() + for thread in pumps: + thread.join(1) + if not channel.closed: + channel.send_exit_status(status) + channel.shutdown_write() + except (OSError, EOFError): + pass + finally: + channel.close() + for stream in (process.stdout, process.stderr): + stream.close() + thread = threading.Thread(target=execute, daemon=True) + self.workers.append(thread) + thread.start() + return True + + +class CommandJobTests(unittest.TestCase): + def local(self): + session = Session() + self.addCleanup(session.close) + return session + + def remote(self): + left, right = socket.socketpair() + server_transport = paramiko.Transport(left) + client_transport = paramiko.Transport(right) + server_transport.add_server_key(paramiko.RSAKey.generate(1024)) + server = Server() + server_transport.start_server(event=threading.Event(), server=server) + client_transport.start_client(timeout=3) + client_transport.auth_none('test') + # Accept incoming channels so the server transport retains their lifetime. + channels = [] + def accept(): + while server_transport.is_active(): + channel = server_transport.accept(0.1) + if channel is not None: + channels.append(channel) + acceptor = threading.Thread(target=accept, daemon=True) + acceptor.start() + client = paramiko.SSHClient() + client._transport = client_transport + session = self.local() + session._client = client + session.host = 'socketpair.test' + def cleanup(): + server.release.set() + client_transport.close() + server_transport.close() + for process in server.processes: + if process.poll() is None: + os.killpg(process.pid, signal.SIGKILL) + process.wait(timeout=3) + for worker in server.workers: + worker.join(3) + acceptor.join(1) + left.close() + right.close() + self.addCleanup(cleanup) + return session + + def command(self, source): + return [sys.executable, '-u', '-c', source] + + def test_exports_and_success_on_both_backends(self): + self.assertIs(sshscript.CommandTimeoutError, CommandTimeoutError) + for session in (self.local(), self.remote()): + with self.subTest(host=session.host): + result = session(self.command('import sys; print("out"); print("err", file=sys.stderr)'), command_timeout=3) + self.assertEqual((result.stdout, result.stderr, result.exitcode), ('out\n', 'err\n', 0)) + self.assertIs(result, session.last_result) + self.assertEqual(session.stdout, 'out\n') + self.assertEqual(result.stop_reason, 'completed') + + def test_continuous_output_does_not_reset_deadline(self): + for session in (self.local(), self.remote()): + with self.subTest(host=session.host): + start = time.monotonic() + with self.assertRaises(CommandTimeoutError) as caught: + session(self.command('import time\nwhile True:\n print("tick"); time.sleep(.01)'), command_timeout=.3, stop_timeout=.1) + self.assertLess(time.monotonic() - start, 2) + self.assertIn('tick', caught.exception.stdout) + self.assertEqual(caught.exception.result.stop_reason, 'timeout') + self.assertIsNone(session.last_result) + self.assertEqual(caught.exception.termination_status, 'confirmed' if session.host is None else 'unknown') + + def test_silent_command_and_unconsumed_stdin_are_bounded(self): + for session in (self.local(), self.remote()): + start = time.monotonic() + with self.assertRaises(CommandTimeoutError): + session(self.command('import time; time.sleep(10)'), command_timeout=.15, + stop_timeout=.1, input=b'x' * 4_000_000) + self.assertLess(time.monotonic() - start, 2) + + def test_local_stop_allows_sigint_handler_to_flush(self): + source = 'import signal,time,sys\ndef stop(*args):\n print("flushed"); sys.exit(0)\nsignal.signal(signal.SIGINT,stop)\nprint("ready")\nwhile True: time.sleep(.1)' + with self.local().start(self.command(source), timeout=None, check=True) as job: + self.assertIn('ready', next(job.iter_stdout())) + result = job.stop() + self.assertIn('flushed', result.stdout) + self.assertEqual(result.stop_reason, 'cancelled') + self.assertEqual(result.termination_status, 'confirmed') + self.assertIs(job.stop(), result) + self.assertIs(job.wait(), result) + + def test_stop_escalates_when_sigint_ignored(self): + source = 'import signal,time\nsignal.signal(signal.SIGINT,signal.SIG_IGN)\nprint("ready")\nwhile True: time.sleep(.1)' + with self.local().start(self.command(source), stop_timeout=.1) as job: + next(job.iter_stdout()) + start = time.monotonic() + result = job.stop() + self.assertLess(time.monotonic() - start, 2) + self.assertEqual(result.exitcode, -signal.SIGKILL) + + def test_remote_stop_unknown_keeps_transport_usable(self): + session = self.remote() + with session.start(self.command('import time; print("ready"); time.sleep(10)'), stop_timeout=.1) as job: + next(job.iter_stdout()) + result = job.stop() + self.assertEqual(result.termination_status, 'unknown') + self.assertIsNone(result.exitcode) + self.assertEqual(session(['printf', 'alive'], command_timeout=2).stdout, 'alive') + + def test_deadline_covers_exec_request_ack(self): + start = time.monotonic() + with self.assertRaises(CommandTimeoutError): + self.remote()(['stall-ack'], command_timeout=.15, stop_timeout=.1) + self.assertLess(time.monotonic() - start, 2) + + def test_deadline_runs_without_wait(self): + job = self.local().start(self.command('import time; time.sleep(10)'), timeout=.1, stop_timeout=.1) + self.assertTrue(job._done.wait(2)) + with self.assertRaises(CommandTimeoutError): + job.wait() + + def test_capture_is_bounded_and_queue_overflow_visible(self): + with self.local().start(self.command('import sys; sys.stdout.write("x"*2_000_000); sys.stderr.write("y"*2_000_000)'), capture_limit=100, timeout=3) as job: + result = job.wait() + self.assertEqual(result.stdout, 'x' * 100) + self.assertEqual(result.stderr, 'y' * 100) + self.assertTrue(result.stdout_truncated and result.stderr_truncated) + with self.assertRaises(BufferError): + list(job.iter_stdout()) + + def test_large_stderr_drained_on_ssh(self): + result = self.remote()(self.command('import sys; sys.stderr.write("y"*3_000_000); print("done")'), command_timeout=5, capture_limit=100) + self.assertEqual(result.stdout, 'done\n') + self.assertTrue(result.stderr_truncated) + + def test_local_input_env_and_utf8_stream(self): + with self.local().start(self.command('import os,sys; print(os.environ["JOB_TEST"]); print(sys.stdin.read())'), input='中文', env={'JOB_TEST': 'yes'}) as job: + self.assertEqual(''.join(job.iter_stdout()), 'yes\n中文\n') + + def test_context_and_session_close_stop_jobs(self): + session = self.local() + with session.start(self.command('import time; time.sleep(10)'), stop_timeout=.1) as job: + pass + self.assertTrue(job.done) + job = session.start(self.command('import time; time.sleep(10)'), stop_timeout=.1) + session.close(strict=True) + self.assertTrue(job.done) + + def test_check_error_and_primary_exception_preserved(self): + session = self.local() + with self.assertRaises(subprocess.CalledProcessError) as caught: + session(self.command('import sys; sys.exit(7)'), command_timeout=2, check=True) + self.assertIs(caught.exception.result, session.last_result) + with self.assertRaisesRegex(ValueError, 'primary'): + with session.start(self.command('import time; time.sleep(10)'), stop_timeout=.1): + raise ValueError('primary') + + def test_invalid_options_never_launch(self): + session = self.local() + with patch('commandjob.subprocess.Popen') as popen: + for value in (0, -1, float('nan'), float('inf')): + with self.assertRaises(ValueError): + session.start(['true'], timeout=value) + with self.assertRaises(TypeError): + session.start(['true'], timeout=True) + with self.assertRaises(ValueError): + session(['true'], timeout=1, command_timeout=1) + with self.assertRaises(ValueError): + session.start(['true'], get_pty=True) + popen.assert_not_called() + + def test_spy_managed_commands_and_start(self): + namespace = sshscript.run_script( + 'result = $(["printf", "managed"], command_timeout=2)\n' + 'with $.start(["printf", "stream"], timeout=2) as job:\n' + ' text = "".join(job.iter_stdout())\n' + ' sibling = $(["printf", "same-session"], command_timeout=2)\n' + ) + self.assertEqual(namespace['result'].stdout, 'managed') + self.assertEqual(namespace['text'], 'stream') + self.assertEqual(namespace['sibling'].stdout, 'same-session') + + def test_job_keeps_session_owner_alive(self): + with Session().start(self.command('print("alive")'), timeout=2) as job: + self.assertEqual(job.wait().stdout, 'alive\n') + + def test_remote_pty_sends_interrupt_and_retains_acknowledged_status(self): + session = self.local() + session.host = 'pty.test' + session._client = Mock() + channel = Mock() + session._client.get_transport.return_value.open_session.return_value = channel + interrupted = threading.Event() + started = threading.Event() + channel.closed = False + channel.eof_received = False + channel.recv_ready.return_value = False + channel.recv_stderr_ready.return_value = False + channel.exit_status_ready.side_effect = interrupted.is_set + channel.exec_command.side_effect = lambda cmd: started.set() + channel.send_ready.return_value = True + def send(data): + self.assertEqual(data, b'\x03') + channel.eof_received = True + interrupted.set() + return 1 + channel.send.side_effect = send + channel.recv_exit_status.return_value = 130 + with session.start(['tcpdump'], get_pty=True, check=True, stop_timeout=.2) as job: + self.assertTrue(started.wait(1)) + result = job.stop() + self.assertEqual(result.termination_status, 'confirmed') + self.assertEqual(result.exitcode, 130) + channel.shutdown_write.assert_not_called() + + def test_session_clear_preserves_managed_snapshot(self): + session = self.local() + result = session(['printf', 'saved'], command_timeout=2) + session.clear() + self.assertEqual(session.stdout, '') + self.assertEqual(result.stdout, 'saved') + self.assertIs(session.last_result, result) + + def test_legacy_timeout_unchanged(self): + with self.assertRaises(subprocess.TimeoutExpired): + self.local()(self.command('import time; time.sleep(10)'), timeout=.05) + + +if __name__ == '__main__': + unittest.main() diff --git a/src/sshscript/unittest/test_openssh_integration.py b/src/sshscript/unittest/test_openssh_integration.py index 5bc0994..9c82ac9 100644 --- a/src/sshscript/unittest/test_openssh_integration.py +++ b/src/sshscript/unittest/test_openssh_integration.py @@ -16,7 +16,7 @@ import paramiko -from sshscript import Session +from sshscript import Session, CommandTimeoutError ENABLED = os.environ.get("SSHSCRIPT_OPENSSH_TESTS") == "1" @@ -130,6 +130,29 @@ def _remove_remote_tree(self, remote, path): timeout=10, ) + def test_managed_deadline_and_pty_stop(self): + remote = self._connect() + started = time.monotonic() + with self.assertRaises(CommandTimeoutError) as caught: + remote.exec_command( + ["sh", "-c", "while :; do echo tick; sleep 0.05; done"], + command_timeout=0.5, stop_timeout=0.2, + ) + self.assertLess(time.monotonic() - started, 3) + self.assertIn("tick", caught.exception.stdout) + self.assertEqual(caught.exception.termination_status, "unknown") + # POSIX terminal job control is exercised against a real OpenSSH PTY. + with remote.start( + ["sh", "-c", "trap 'echo flushed; exit 0' INT; echo ready; while :; do sleep 0.1; done"], + get_pty=True, timeout=10, stop_timeout=2, + ) as job: + self.assertIn("ready", next(job.iter_stdout())) + result = job.stop() + self.assertEqual(result.termination_status, "confirmed") + self.assertEqual(result.stop_reason, "cancelled") + self.assertIn("flushed", result.stdout) + self.assertEqual(remote.exec_command(["printf", "alive"], command_timeout=3).stdout, "alive") + def test_host_key_reject_trust_and_mismatch(self): self.known_hosts.write_text("", encoding="utf-8") unknown_parent = self._new_parent() diff --git a/src/sshscript/unittest/test_public_types.py b/src/sshscript/unittest/test_public_types.py new file mode 100644 index 0000000..f43ab26 --- /dev/null +++ b/src/sshscript/unittest/test_public_types.py @@ -0,0 +1,27 @@ +"""Keep annotated public methods and shipped PEP 561 files aligned.""" +import ast +import inspect +from pathlib import Path +import unittest +from session import Session +from commandjob import CommandJob + +class PublicTypeTests(unittest.TestCase): + def test_public_stub_methods_exist_and_keywords_match(self): + root = Path(__file__).resolve().parents[1] + self.assertTrue((root / 'py.typed').is_file()) + for filename, cls in [('session.pyi', Session), ('commandjob.pyi', CommandJob)]: + tree = ast.parse((root / filename).read_text()) + definition = next(n for n in tree.body if isinstance(n, ast.ClassDef) and n.name == cls.__name__) + for node in definition.body: + if not isinstance(node, ast.FunctionDef): + continue + implementation = getattr(cls, node.name) + if isinstance(implementation, property): + continue + signature = inspect.signature(implementation) + params = signature.parameters + dynamic = any(p.kind == p.VAR_KEYWORD for p in params.values()) + for argument in node.args.args + node.args.kwonlyargs: + self.assertTrue(argument.arg in params or dynamic, + f'{filename}: {node.name}.{argument.arg}') diff --git a/src/sshscript/unittest/test_recommended_examples.py b/src/sshscript/unittest/test_recommended_examples.py new file mode 100644 index 0000000..94f6b27 --- /dev/null +++ b/src/sshscript/unittest/test_recommended_examples.py @@ -0,0 +1,44 @@ +"""Execute every canonical example, including SSH via a real Paramiko fixture.""" +from contextlib import redirect_stdout +from io import StringIO +import json +from pathlib import Path +import re +from unittest.mock import patch + +import unittest +import test_command_job as fixtures +import sshscript + + +class RecommendedExamplesTests(unittest.TestCase): + local = fixtures.CommandJobTests.local + remote = fixtures.CommandJobTests.remote + + +def test_canonical_examples(self): + here = Path(__file__).resolve() + guide = next((p / 'API_GUIDE.md' for p in here.parents if (p / 'API_GUIDE.md').is_file()), None) + self.assertIsNotNone(guide, 'canonical guide must ship in source distributions') + text = guide.read_text() + blocks = re.findall(r'\n```python\n(.*?)```', text, re.S) + self.assertEqual(len(blocks), text.count('```python'), 'every example needs a version profile') + self.assertEqual(len(blocks), 6) + ids = set() + for metadata, source in blocks: + example = json.loads(metadata) + self.assertNotIn(example['id'], ids) + ids.add(example['id']) + self.assertIn(example['profile'], ('3.1.5', 'unreleased')) + with self.subTest(example=example['id']): + output = StringIO() + with redirect_stdout(output): + if example.get('fixture') == 'ssh': + remote = self.remote() + with patch.object(sshscript.Session, 'connect', return_value=remote): + sshscript.run_script(source) + else: + sshscript.run_script(source) + self.assertEqual(output.getvalue(), example['stdout']) + +RecommendedExamplesTests.test_canonical_examples = test_canonical_examples diff --git a/src/sshscript/unittest/test_session_settings.py b/src/sshscript/unittest/test_session_settings.py new file mode 100644 index 0000000..c95c516 --- /dev/null +++ b/src/sshscript/unittest/test_session_settings.py @@ -0,0 +1,121 @@ +"""Session policy precedence, isolation and CLI/script integration.""" +from contextlib import redirect_stdout +from io import StringIO +import logging +import os +from pathlib import Path +import subprocess +import sys +import tempfile +import unittest +from unittest.mock import patch + +from session import Session +from sessionsettings import execution_defaults +import errorutils +import sshscript + + +class SettingsTests(unittest.TestCase): + def session(self, parent=None): + session = Session(parent) + self.addCleanup(session.close) + return session + + def test_validation_properties_and_child_snapshot(self): + parent = self.session() + parent.set(check=True, verbose=True, log_level='DEBUG') + child = self.session(parent) + parent.set(check=False, verbose=False) + self.assertTrue(child.check) + child.verbose = False + self.assertFalse(child.get('verbose')) + before = child.get() + with self.assertRaises(TypeError): + child.set(check=False, verbose=1) + self.assertEqual(child.get(), before) + with self.assertRaises(ValueError): child.set(typo=True) + with self.assertRaises(ValueError): child.get('typo') + copy = child.get(); copy['check'] = False + self.assertTrue(child.check) + + def test_context_defaults_reset_and_script_worker(self): + old = self.session().get() + with execution_defaults(check=True, log_level='ERROR'): + self.assertTrue(self.session().check) + namespace = sshscript.run_script('from sshscript import Session\ns = Session()\nsettings = s.get()\ns.close()') + self.assertTrue(namespace['settings']['check']) + self.assertEqual(self.session().get(), old) + + def test_check_precedence_legacy_managed_and_console(self): + session = self.session(); session.check = True + for options in ({}, {'command_timeout': 2}): + with self.assertRaises(subprocess.CalledProcessError): + session(['false'], **options) + self.assertEqual(session(['false'], check=False, **options).exitcode, 1) + with session.start(['false'], check=False) as job: + self.assertEqual(job.wait().exitcode, 1) + with session.shell('bash') as console: + with self.assertRaises(subprocess.CalledProcessError) as caught: + console('false') + self.assertEqual(caught.exception.returncode, 1) + console('false', check=False) + self.assertEqual(console.exitcode, 1) + session.check = False + console('false') + + def test_spy_set_get_and_failure(self): + with self.assertRaises(subprocess.CalledProcessError): + sshscript.run_script('with $.shell("bash"):\n $.set(check=True)\n $false\n') + namespace = sshscript.run_script('$.set(check=True)\nvalue = $.get("check")\n$("false", check=False)\n') + self.assertTrue(namespace['value']) + + def test_spy_thread_inherits_cli_context_defaults(self): + with execution_defaults(check=True): + namespace = sshscript.run_script( + 'policy = $.get()\nimport threading\nfrom sshscript import Session\n' + 'values = []\ndef work():\n' + ' s = Session()\n values.append(s.get("check"))\n s.close()\n' + 't = threading.Thread(target=work)\nt.start()\nt.join()\n' + ) + self.assertEqual(namespace['values'], [True]) + + def test_logging_isolation_does_not_mutate_shared_level(self): + logger = errorutils.get_logger()._logger + stream = StringIO(); handler = logging.StreamHandler(stream) + previous = logger.level + logger.addHandler(handler); logger.setLevel(logging.ERROR) + self.addCleanup(logger.removeHandler, handler) + self.addCleanup(logger.setLevel, previous) + first, second = self.session(), self.session() + first.log_level = 'DEBUG'; second.log_level = 'ERROR' + first(['printf', 'first']) + first.logger.debug('first-marker') + second.logger.debug('second-marker') + self.assertIn('Executing subprocess', stream.getvalue()) + self.assertIn('first-marker', stream.getvalue()) + self.assertNotIn('second-marker', stream.getvalue()) + self.assertEqual(logger.level, logging.ERROR) + + def test_managed_verbose_snapshot(self): + session = self.session(); session.verbose = True + capture = StringIO() + with redirect_stdout(capture): + job = session.start([sys.executable, '-c', 'import time; time.sleep(.1); print("shown")']) + session.verbose = False + job.wait() + session(['printf', 'hidden'], command_timeout=2) + self.assertEqual(capture.getvalue(), 'shown\n') + + def test_cli_sets_root_and_nested_defaults_without_environment_mutation(self): + with tempfile.TemporaryDirectory() as tmp: + path = Path(tmp)/'settings.spy' + path.write_text('from sshscript import Session\nimport os\nprint($.get("verbose"), $.get("log_level"), Session().get("verbose"))\nprint(os.environ.get("VERBOSE"), os.environ.get("DEBUG"))\n$printf visible-output\n$.set(verbose=False)\n$printf hidden-output\n') + env = dict(os.environ, PYTHONPATH=str(Path(__file__).resolve().parents[1])) + env.pop('VERBOSE', None); env.pop('DEBUG', None) + result = subprocess.run([sys.executable, str(Path(sshscript.__file__)), str(path), '-v', '--debug'], env=env, text=True, capture_output=True, timeout=10) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn('True 10 True', result.stdout) + self.assertIn('None None', result.stdout) + self.assertIn('visible-output', result.stdout) + self.assertNotIn('hidden-output', result.stdout) diff --git a/src/sshscript/unittest/test_ssh_security.py b/src/sshscript/unittest/test_ssh_security.py index 121b04e..a8656cb 100644 --- a/src/sshscript/unittest/test_ssh_security.py +++ b/src/sshscript/unittest/test_ssh_security.py @@ -89,11 +89,14 @@ def make_paramiko_channel(self, explicit_environment=None): sshchannel = channelssh.SSHChannel.__new__(channelssh.SSHChannel) owner = Mock() owner.command = '' + owner.session = Session() + self.addCleanup(owner.session.close) owner.session.host = 'example.test' owner._parameters_to_execute = { 'environment': explicit_environment or {}, } sshchannel.owner = owner + sshchannel.logger = owner.session.logger sshchannel.wait_for_silent = Mock() remote_channel = Mock() client = Mock() @@ -175,7 +178,8 @@ def read(self): stderr = Stream(b'err', remote_channel) client = Mock() client.exec_command.return_value = stdin, stdout, stderr - remote_session = Mock() + remote_session = Session() + self.addCleanup(remote_session.close) remote_session.host = 'example.test' remote_session._client = client @@ -235,8 +239,8 @@ def read(self): Stream(b'host-name\n'), Stream(b''), ) - remote_session = Mock() - remote_session.connected = True + remote_session = Session() + self.addCleanup(remote_session.close) remote_session.host = 'example.test' remote_session._client = client diff --git a/tools/check_baseline_examples.py b/tools/check_baseline_examples.py new file mode 100644 index 0000000..3787bea --- /dev/null +++ b/tools/check_baseline_examples.py @@ -0,0 +1,29 @@ +"""Run canonical credential-free stable examples against installed 3.1.5. + +Run with python -I after installing sshscript==3.1.5. The SSH example uses +an authenticated fixture in test_recommended_examples instead of a real host. +""" +from contextlib import redirect_stdout +from io import StringIO +import json +from pathlib import Path +import re +import sshscript + +if sshscript.__version__ != '3.1.5': + raise RuntimeError('This check requires the published 3.1.5 baseline') +source = (Path(__file__).resolve().parents[1] / 'API_GUIDE.md').read_text() +count = 0 +for metadata, code in re.findall(r'\n```python\n(.*?)```', source, re.S): + example = json.loads(metadata) + if example['profile'] != '3.1.5' or example.get('fixture'): + continue + output = StringIO() + with redirect_stdout(output): + sshscript.run_script(code) + if output.getvalue() != example['stdout']: + raise RuntimeError(f'Baseline example failed: {example["id"]}') + count += 1 +if count != 3: + raise RuntimeError('Expected three credential-free baseline examples') +print('Published 3.1.5: all three credential-free canonical examples passed') diff --git a/tools/check_public_types.py b/tools/check_public_types.py new file mode 100644 index 0000000..9fdeb15 --- /dev/null +++ b/tools/check_public_types.py @@ -0,0 +1,62 @@ +"""Check PEP 561 consumer behavior using real positive and negative examples.""" +from pathlib import Path +import shutil +import subprocess +import sys +import tempfile + +VALID = '''from typing import assert_type +from sshscript import Session, CommandResult, JobResult, CommandJob +s = Session() +s.set(check=True, log_level="DEBUG") +s.verbose = False +s.log_level = "WARNING" +assert_type(s.get("check"), bool) +assert_type(s.get("log_level"), int) +r = s.exec_command(["printf", "ready"], check=True) +assert_type(r, CommandResult[int]) +assert_type(r.stdout, str) +assert_type(r.exitcode, int) +m = s.exec_command(["printf", "ready"], command_timeout=2) +assert_type(m, JobResult) +assert_type(m.exitcode, int | None) +assert_type(s(["true"], command_timeout=2), JobResult) +assert_type(s.start(["true"]), CommandJob) +with s.connect("host") as remote: + assert_type(remote, Session) +''' +INVALID = '''from sshscript import Session +s = Session() +s.set(chek=True) +s.verbose = "yes" +s.exec_command(123) +s.exec_command(["true"], check="yes") +''' + +def main(): + root = Path(__file__).resolve().parents[1] + package = root / 'src/sshscript' if (root / 'src/sshscript').is_dir() else root + with tempfile.TemporaryDirectory(prefix='sshscript-types-') as tmp: + folder = Path(tmp) + target = folder / 'sshscript' + target.mkdir() + for pattern in ('*.py', '*.pyi', 'py.typed'): + for source in package.glob(pattern): + shutil.copy2(source, target / source.name) + for name, source in [('valid', VALID), ('invalid', INVALID)]: + path = folder / f'{name}.py' + path.write_text(source) + result = subprocess.run( + [sys.executable, '-m', 'mypy', '--strict', '--ignore-missing-imports', + '--follow-imports=silent', '--cache-dir', str(folder / 'cache'), str(path)], + cwd=folder, text=True, capture_output=True, timeout=60, + ) + output = result.stdout + result.stderr + if name == 'valid' and result.returncode: + raise RuntimeError(output) + if name == 'invalid' and (result.returncode != 1 or 'Found 4 errors' not in output): + raise RuntimeError('Expected all four invalid uses to be rejected:\n' + output) + print('Public types: valid consumer accepted; four invalid uses rejected') + +if __name__ == '__main__': + main() diff --git a/tools/prepare_release.py b/tools/prepare_release.py index 4d56d01..93ffb3c 100644 --- a/tools/prepare_release.py +++ b/tools/prepare_release.py @@ -3,9 +3,9 @@ import shutil from pathlib import Path -MODULES = '__init__ _version sshscript session commandresult sshconfig patching errorutils tokenparser dollarparser dollarchanger spyimporter channelssh channelsubprocess channelutils channelgeneric sessionwrapper stdio dollar'.split() +MODULES = '__init__ _version sshscript session sessionsettings commandresult commandjob sshconfig patching errorutils tokenparser dollarparser dollarchanger spyimporter channelssh channelsubprocess channelutils channelgeneric sessionwrapper stdio dollar'.split() ROOT_FILES = [ - 'pyproject.toml', 'README.md', 'LICENSE.txt', 'RELEASING.md', + 'API_GUIDE.md', 'pyproject.toml', 'README.md', 'LICENSE.txt', 'RELEASING.md', 'MANIFEST.in', 'CHANGELOG.md', 'CONTRIBUTING.md', 'EXCEPTIONS.md', 'SECURITY.md', 'SUPPORT.md', 'CODE_OF_CONDUCT.md', '.gitignore', '.github/ISSUE_TEMPLATE/bug_report.yml', @@ -16,11 +16,11 @@ '.github/workflows/release.yml', ] TOOLS = [ - 'prepare_release.py', 'check_release.py', 'run_checks.py', + 'check_baseline_examples.py', 'sync_api_guide.py', 'check_public_types.py', 'prepare_release.py', 'check_release.py', 'run_checks.py', 'publish_release.py', 'setup_openssh_ci.sh', ] TESTS = [ - 'test_command_api.py', 'test_ssh_config.py', 'test_check_file.py', + 'test_recommended_examples.py', 'test_public_types.py', 'test_session_settings.py', 'test_command_job.py', 'test_command_api.py', 'test_ssh_config.py', 'test_check_file.py', 'check_package_asserts.py', 'dollar_syntax.spy', 'dollar_syntax_fixture.spy', 'language.spy', 'language_fixture.spy', 'test_channelgeneric_expect.py', 'test_file_transfer.py', @@ -42,6 +42,7 @@ def prepare(source, destination): pairs += [(source / 'tools' / p, destination / 'tools' / p) for p in TOOLS] pairs += [(package / (p + '.py'), destination / 'src/sshscript' / (p + '.py')) for p in MODULES] pairs += [(package / 'unittest' / p, destination / 'src/sshscript/unittest' / p) for p in TESTS] + pairs += [(package / p, destination / 'src/sshscript' / p) for p in ('py.typed', '__init__.pyi', 'session.pyi', 'sessionwrapper.pyi', 'commandjob.pyi', 'commandresult.pyi')] missing = [str(src) for src, _ in pairs if not src.is_file()] if missing: raise FileNotFoundError('Missing release inputs: ' + ', '.join(missing)) diff --git a/tools/sync_api_guide.py b/tools/sync_api_guide.py new file mode 100644 index 0000000..95b13ce --- /dev/null +++ b/tools/sync_api_guide.py @@ -0,0 +1,37 @@ +"""Render the canonical guide into a separately checked-out documentation site.""" +import argparse +from datetime import datetime +import os +import re +import time +from pathlib import Path + +HEADER = '''--- +title: "Recommended SSHScript API" +parent: "SSHScript v3.1 Documentation" +nav_order: 0 +permalink: /v3a/recommended-api/ +--- + + + +''' + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('destination', type=Path) + parser.add_argument('--check', action='store_true') + args = parser.parse_args() + content = HEADER + (Path(__file__).resolve().parents[1] / 'API_GUIDE.md').read_text() + if args.check: + existing = re.sub(r"\nLast Updated: [^\n]+\n?$", "", args.destination.read_text()) + if existing.rstrip() != content.rstrip(): + raise SystemExit('Canonical guide website copy is stale') + else: + stamp = int(time.time()) + updated = datetime.fromtimestamp(stamp).strftime("%Y-%m-%d %H:%M:%S") + args.destination.write_text(content.rstrip() + f"\n\nLast Updated: {updated}\n") + os.utime(args.destination, (stamp, stamp)) + +if __name__ == '__main__': + main()