Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 17 additions & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -19,16 +19,32 @@ 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
with:
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
Expand Down
167 changes: 167 additions & 0 deletions API_GUIDE.md
Original file line number Diff line number Diff line change
@@ -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.

<!-- example: {"id":"argv", "profile":"3.1.5", "stdout":"a; b\n"} -->
```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.

<!-- example: {"id":"failure", "profile":"3.1.5", "stdout":"failed: 7\n"} -->
```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.

<!-- example: {"id":"ssh", "profile":"3.1.5", "fixture":"ssh", "stdout":"ready\n"} -->
```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`.

<!-- example: {"id":"dollar", "profile":"3.1.5", "stdout":"ready\n"} -->
```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.

<!-- example: {"id":"settings", "profile":"unreleased", "stdout":"True\n1\n"} -->
```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:

<!-- example: {"id":"stop", "profile":"unreleased", "stdout":"cancelled confirmed\n"} -->
```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.
65 changes: 65 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
20 changes: 19 additions & 1 deletion EXCEPTIONS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down Expand Up @@ -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.
4 changes: 4 additions & 0 deletions MANIFEST.in
Original file line number Diff line number Diff line change
Expand Up @@ -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
Loading
Loading