@appitlabs/remote-exec 0.0.0-stage → 0.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +111 -2
- package/package.json +38 -4
- package/skills/remote-exec/SKILL.md +96 -0
- package/skills/remote-exec/assets/demo.gif +0 -0
- package/skills/remote-exec/scripts/rx.py +203 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Ibrahim M. Badr (Appit Labs)
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,112 @@
|
|
|
1
|
-
#
|
|
1
|
+
# remote-exec
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
<h3 align="center">Run one command on a remote server without hanging on a prompt.</h3>
|
|
4
|
+
|
|
5
|
+
<p align="center">
|
|
6
|
+
<a href="LICENSE"><img alt="license" src="https://img.shields.io/badge/license-MIT-3DA639?style=flat-square"></a>
|
|
7
|
+
<img alt="agents" src="https://img.shields.io/badge/works%20in-pi%20%7C%20Claude%20Code%20%7C%20Codex%20%7C%20Cursor-4B5563?style=flat-square">
|
|
8
|
+
<img alt="skillspector" src="https://img.shields.io/badge/SkillSpector-0%2F100%20SAFE-2EA043?style=flat-square">
|
|
9
|
+
<img alt="cost" src="https://img.shields.io/badge/session%20cost-~80%20tok-6E7681?style=flat-square">
|
|
10
|
+
</p>
|
|
11
|
+
|
|
12
|
+
<p align="center">
|
|
13
|
+
<img alt="remote-exec demo — real run, regenerable from demos/remote-exec.json" src="skills/remote-exec/assets/demo.gif" width="900">
|
|
14
|
+
</p>
|
|
15
|
+
|
|
16
|
+
## What it is
|
|
17
|
+
|
|
18
|
+
`remote-exec` is **one-shot SSH with guard rails**: registered hosts, hard timeouts, no
|
|
19
|
+
interactive prompts, a single-call health probe (uptime, disks over 70%, memory, containers, GPU,
|
|
20
|
+
listening ports) and file put/get. Every call either returns an answer or fails inside the timeout you
|
|
21
|
+
set.
|
|
22
|
+
|
|
23
|
+
## The problem it removes
|
|
24
|
+
|
|
25
|
+
SSH from an agent fails in three predictable ways: it blocks forever on a password prompt, it
|
|
26
|
+
mangles the remote quoting, or it starts something long-lived and never returns. That is why sessions end
|
|
27
|
+
up hand-writing `ssh -o BatchMode=yes -o ConnectTimeout=… 'bash -lc …'` **825 times**. Here the flags are
|
|
28
|
+
fixed, hosts are aliases, and the timeout is a parameter.
|
|
29
|
+
|
|
30
|
+
## Install
|
|
31
|
+
|
|
32
|
+
```bash
|
|
33
|
+
# any agent, via the skills CLI — this one, or all twelve at once
|
|
34
|
+
npx skills add Appit-labs/remote-exec -g -y
|
|
35
|
+
npx skills add Appit-labs/appit-skills -g -y
|
|
36
|
+
|
|
37
|
+
# Claude Code — the whole collection as one marketplace
|
|
38
|
+
claude plugin marketplace add Appit-labs/appit-skills
|
|
39
|
+
claude plugin install remote-exec@appit-skills
|
|
40
|
+
|
|
41
|
+
# pi
|
|
42
|
+
pi install git:github.com/Appit-labs/remote-exec
|
|
43
|
+
|
|
44
|
+
# any agent that reads a skills directory
|
|
45
|
+
git clone git@github.com:Appit-labs/remote-exec.git
|
|
46
|
+
cp -r remote-exec/skills/remote-exec ~/.claude/skills/ # or ~/.codex/skills/, .cursor/skills/, …
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
> **npm name.** `remote-exec` on npm belongs to another author. This skill is published as
|
|
50
|
+
> `@appitlabs/remote-exec`, and the whole collection as `@appitlabs/skills`.
|
|
51
|
+
|
|
52
|
+
## Use
|
|
53
|
+
|
|
54
|
+
- **Register a host** — `scripts/rx.py add staging deploy@10.0.0.5 --key /path/to/key`
|
|
55
|
+
- **Health in one call** — `scripts/rx.py probe staging`
|
|
56
|
+
- **Run / logs / copy** — `run` · `logs` · `put` · `get`, each with `--timeout`
|
|
57
|
+
- **See what is registered** — `scripts/rx.py ls`
|
|
58
|
+
|
|
59
|
+
## What it does not do
|
|
60
|
+
|
|
61
|
+
- Password authentication is not supported, on purpose — use a key (`ssh-copy-id`).
|
|
62
|
+
- It does not run interactive programs (`vim`, `top`, `psql` without `-c`); long jobs go to a log you poll.
|
|
63
|
+
|
|
64
|
+
## Requires
|
|
65
|
+
|
|
66
|
+
- `ssh` client and key-based auth to the target.
|
|
67
|
+
- Optional hosts file at `~/.config/rx/hosts.json` (mode 600, outside any repo).
|
|
68
|
+
- Python 3.9+ (stdlib only).
|
|
69
|
+
|
|
70
|
+
## Cost
|
|
71
|
+
|
|
72
|
+
| | tokens |
|
|
73
|
+
| --- | --- |
|
|
74
|
+
| always-on — the description, paid every session | ~80 |
|
|
75
|
+
| on invoke | ~0.9k |
|
|
76
|
+
|
|
77
|
+
The demo above is not a mockup: `demos/remote-exec.json` holds the captured run and
|
|
78
|
+
`tools/make_demo.py` renders it, so it can be regenerated and audited.
|
|
79
|
+
|
|
80
|
+
## Provenance
|
|
81
|
+
|
|
82
|
+
Every command in this skill was run against a real target before it was written down: a live
|
|
83
|
+
database, a staging host, a failing CI run, a browser session. The repository was created and
|
|
84
|
+
published on 2026-11-18; where the workflow itself is older, `CHANGELOG.md` carries the dates.
|
|
85
|
+
|
|
86
|
+
## Security
|
|
87
|
+
|
|
88
|
+
SkillSpector: **0/100, SAFE, 0 open findings** against the committed baseline. Every accepted
|
|
89
|
+
finding is listed with its reason in [SECURITY.md](SECURITY.md). No `shell=True`, no credential
|
|
90
|
+
storage, no network destination chosen at runtime.
|
|
91
|
+
|
|
92
|
+
## Part of the Appit collection
|
|
93
|
+
|
|
94
|
+
All twelve, one install: `npx skills add Appit-labs/appit-skills -g -y`.
|
|
95
|
+
|
|
96
|
+
- [`live-qa`](https://github.com/Appit-labs/live-qa) — live QA in a real browser
|
|
97
|
+
- [`ci-triage`](https://github.com/Appit-labs/ci-triage) — red CI to the failing line
|
|
98
|
+
- [`pg-inspect`](https://github.com/Appit-labs/pg-inspect) — read-only Postgres inspection
|
|
99
|
+
- [`repo-runbook`](https://github.com/Appit-labs/repo-runbook) — the verified runbook in AGENTS.md
|
|
100
|
+
- [`remote-exec`](https://github.com/Appit-labs/remote-exec) — SSH that cannot hang ← this skill
|
|
101
|
+
- [`trello-tickets`](https://github.com/Appit-labs/trello-tickets) — seven ticket types, one card
|
|
102
|
+
- [`cloud-browser`](https://github.com/Appit-labs/cloud-browser) — hosted browsers that stop billing
|
|
103
|
+
- [`open-design`](https://github.com/Appit-labs/open-design) — the OpenDesign monorepo
|
|
104
|
+
- [`blender-pipeline`](https://github.com/Appit-labs/blender-pipeline) — Blender via MCP
|
|
105
|
+
- [`code-scan`](https://github.com/Appit-labs/code-scan) — Skylos + Fallow, one gate
|
|
106
|
+
- [`release`](https://github.com/Appit-labs/release) — conventional commits to a tag
|
|
107
|
+
- [`hermes-setup`](https://github.com/Appit-labs/hermes-setup) — least-privilege agent wiring
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
## License
|
|
111
|
+
|
|
112
|
+
MIT, copyright Appit Labs. See [LICENSE](LICENSE).
|
package/package.json
CHANGED
|
@@ -1,6 +1,40 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@appitlabs/remote-exec",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.2",
|
|
4
|
+
"description": "One-shot SSH for agents: aliased hosts, hard timeouts, no password-prompt hangs, one-call health probe, file put/get.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"keywords": [
|
|
7
|
+
"agent-skill",
|
|
8
|
+
"pi-package",
|
|
9
|
+
"claude-code-plugin",
|
|
10
|
+
"codex-skill"
|
|
11
|
+
],
|
|
12
|
+
"pi": {
|
|
13
|
+
"skills": [
|
|
14
|
+
"./skills"
|
|
15
|
+
]
|
|
16
|
+
},
|
|
17
|
+
"files": [
|
|
18
|
+
"skills",
|
|
19
|
+
"README.md",
|
|
20
|
+
"LICENSE",
|
|
21
|
+
"NOTICE"
|
|
22
|
+
],
|
|
23
|
+
"repository": {
|
|
24
|
+
"type": "git",
|
|
25
|
+
"url": "https://github.com/Appit-labs/remote-exec.git"
|
|
26
|
+
},
|
|
27
|
+
"author": {
|
|
28
|
+
"name": "Ibrahim M. Badr",
|
|
29
|
+
"url": "https://github.com/ibrahimbdr"
|
|
30
|
+
},
|
|
31
|
+
"contributors": [
|
|
32
|
+
{
|
|
33
|
+
"name": "Appit Labs",
|
|
34
|
+
"url": "https://github.com/Appit-Labs"
|
|
35
|
+
}
|
|
36
|
+
],
|
|
37
|
+
"publishConfig": {
|
|
38
|
+
"access": "public"
|
|
39
|
+
}
|
|
40
|
+
}
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: remote-exec
|
|
3
|
+
description: Run commands on a remote server over SSH without hanging — aliased hosts, hard timeouts, non-interactive auth, plus one-shot probes (disk, memory, docker, GPU, ports) and file put/get. Use when a task needs to check or fix something on a remote box, a stage/prod host, a GPU worker, or any machine that is not this one.
|
|
4
|
+
allowed-tools:
|
|
5
|
+
- Bash
|
|
6
|
+
- Read
|
|
7
|
+
- Write
|
|
8
|
+
permissions:
|
|
9
|
+
- shell
|
|
10
|
+
- env
|
|
11
|
+
- file_read
|
|
12
|
+
- file_write
|
|
13
|
+
license: MIT
|
|
14
|
+
---
|
|
15
|
+
|
|
16
|
+
# Remote exec
|
|
17
|
+
|
|
18
|
+
SSH from an agent fails in three predictable ways: it prompts for a password and
|
|
19
|
+
blocks forever, quoting mangles the remote command, or the command starts
|
|
20
|
+
something long-lived and the call never returns. This wrapper removes all three.
|
|
21
|
+
|
|
22
|
+
```
|
|
23
|
+
python3 "$SKILL_DIR/scripts/rx.py" <command>
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
**Not for:** provisioning a box, managing users or installing agents — it assumes the host exists and you already have an alias. Anything that must survive your session belongs in systemd, not in this wrapper.
|
|
27
|
+
|
|
28
|
+
## Portability
|
|
29
|
+
|
|
30
|
+
Works in any agent that can run shell commands (pi, Claude Code, Codex, Cursor,
|
|
31
|
+
Gemini CLI, …): the instructions are plain Markdown and the helper is a stdlib
|
|
32
|
+
script. Commands use `$SKILL_DIR` for this skill's own directory — the folder that
|
|
33
|
+
holds this `SKILL.md`. Set it once per session, for example:
|
|
34
|
+
|
|
35
|
+
```bash
|
|
36
|
+
SKILL_DIR=~/.claude/skills/remote-exec # or ~/.codex/skills/…, ~/.pi/agent/skills/…, .cursor/skills/…
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
## Hosts
|
|
40
|
+
|
|
41
|
+
```
|
|
42
|
+
rx.py add stage deploy@10.0.0.5:2222 --key /path/to/your/key --note staging
|
|
43
|
+
rx.py ls
|
|
44
|
+
rx.py rm stage
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
Stored in `~/.config/rx/hosts.json` (mode 600), never in the repo and never in a
|
|
48
|
+
skill file. A raw `[user@]host[:port]` works without registering, so one-off
|
|
49
|
+
boxes need no setup.
|
|
50
|
+
|
|
51
|
+
## Commands
|
|
52
|
+
|
|
53
|
+
| Need | Command |
|
|
54
|
+
| --- | --- |
|
|
55
|
+
| is the box healthy, in one round trip | `probe stage` |
|
|
56
|
+
| run something | `run stage "systemctl is-active api"` |
|
|
57
|
+
| run with the user's login shell (`~/.bashrc` env) | `run stage "source ~/.nvm/nvm.sh && node -v" --login` |
|
|
58
|
+
| tail a container or unit | `logs stage api --lines=120` |
|
|
59
|
+
| copy up / down | `put stage ./x.tar /tmp/x.tar` / `get stage /var/log/app.log ./app.log` |
|
|
60
|
+
| bound the wait | `--timeout=120` on any command (default 60s) |
|
|
61
|
+
|
|
62
|
+
`probe` replaces the four or five separate calls usually spent finding out
|
|
63
|
+
whether a box is out of disk: it returns hostname, uptime, only filesystems over
|
|
64
|
+
70%, memory, running containers, GPU memory/util, and listening ports.
|
|
65
|
+
|
|
66
|
+
## Rules
|
|
67
|
+
|
|
68
|
+
- **One round trip beats five.** Anything you would run as three commands to build
|
|
69
|
+
context belongs in a single `run "a; b; c"`, because each call costs latency and
|
|
70
|
+
context.
|
|
71
|
+
- **Quote for the remote shell, not yours.** The command is one string; single
|
|
72
|
+
quotes inside it survive. If it needs `$VAR` expanded remotely, use double
|
|
73
|
+
quotes deliberately, or `--login` with an explicit `bash -lc`.
|
|
74
|
+
- **Never start an interactive process** (`vim`, `top`, `psql` with no `-c`,
|
|
75
|
+
`docker exec -it`). Prefer `psql -c "..."`, `docker logs --tail`, `journalctl -n`.
|
|
76
|
+
- **Long jobs go to a log, not the call**: detach the job, redirect it to a file
|
|
77
|
+
under `/tmp`, then poll that file. A 60s timeout on a 20-minute run returns
|
|
78
|
+
nothing useful.
|
|
79
|
+
- **Destructive remote commands** (rm, migrations, service restarts, anything on
|
|
80
|
+
prod) need the user's explicit go-ahead first, and you show the exact command
|
|
81
|
+
before running it.
|
|
82
|
+
- Reported failures are real failures: a non-zero exit is printed to stderr and
|
|
83
|
+
returned as the exit code. Do not re-run blindly; read the error.
|
|
84
|
+
|
|
85
|
+
## Keys and auth
|
|
86
|
+
|
|
87
|
+
Password auth cannot work here by design (BatchMode). If the user has only a
|
|
88
|
+
password, ask them to add a key (`ssh-copy-id`) or run the password-requiring step
|
|
89
|
+
themselves. `StrictHostKeyChecking=accept-new` trusts a new host once, then pins
|
|
90
|
+
it; it does not weaken an existing known_hosts entry.
|
|
91
|
+
|
|
92
|
+
## Self-check
|
|
93
|
+
|
|
94
|
+
`python3 "$SKILL_DIR/scripts/rx.py" self-test` verifies alias parsing
|
|
95
|
+
(including IPv6 and `host:port`), the 600 config mode, the BatchMode flags, and
|
|
96
|
+
quoting of a hostile command. Run it after editing the script.
|
|
Binary file
|
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""One-shot SSH for agents: non-interactive, time-boxed, no TTY hangs.
|
|
3
|
+
|
|
4
|
+
rx.py ls
|
|
5
|
+
rx.py add <alias> [user@]host[:port] [--key PATH] [--note TEXT]
|
|
6
|
+
rx.py rm <alias>
|
|
7
|
+
rx.py run <target> "<command>" [--timeout=60] [--login] [--yes-sudo]
|
|
8
|
+
rx.py probe <target> # uptime, disk, memory, docker, ports in ONE round trip
|
|
9
|
+
rx.py logs <target> <docker-name|unit> [--lines=80]
|
|
10
|
+
rx.py put <target> <local> <remote> [--timeout=300]
|
|
11
|
+
rx.py get <target> <remote> <local> [--timeout=300]
|
|
12
|
+
rx.py self-test
|
|
13
|
+
|
|
14
|
+
Target is an alias from ~/.config/rx/hosts.json, or a raw [user@]host[:port].
|
|
15
|
+
Every call uses BatchMode + ConnectTimeout so a bad host fails in seconds instead
|
|
16
|
+
of hanging a session on a password prompt.
|
|
17
|
+
"""
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
import json
|
|
21
|
+
import os
|
|
22
|
+
import shlex
|
|
23
|
+
import subprocess
|
|
24
|
+
import sys
|
|
25
|
+
from pathlib import Path
|
|
26
|
+
|
|
27
|
+
CONFIG = Path(os.environ.get("RX_CONFIG", Path.home() / ".config" / "rx" / "hosts.json"))
|
|
28
|
+
SSH_OPTS = ["-o", "BatchMode=yes", "-o", "ConnectTimeout=10",
|
|
29
|
+
"-o", "ServerAliveInterval=15", "-o", "ServerAliveCountMax=3",
|
|
30
|
+
"-o", "StrictHostKeyChecking=accept-new"]
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def load_hosts() -> dict:
|
|
34
|
+
try:
|
|
35
|
+
return json.loads(CONFIG.read_text())
|
|
36
|
+
except (OSError, ValueError):
|
|
37
|
+
return {}
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def save_hosts(hosts: dict) -> None:
|
|
41
|
+
CONFIG.parent.mkdir(parents=True, exist_ok=True)
|
|
42
|
+
CONFIG.write_text(json.dumps(hosts, indent=2, sort_keys=True) + "\n")
|
|
43
|
+
CONFIG.chmod(0o600)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def parse_target(target: str) -> tuple[str, int | None, dict]:
|
|
47
|
+
hosts = load_hosts()
|
|
48
|
+
entry = hosts.get(target)
|
|
49
|
+
if entry:
|
|
50
|
+
return entry["host"], entry.get("port"), entry
|
|
51
|
+
port = None
|
|
52
|
+
host = target
|
|
53
|
+
if target.count(":") == 1 and not target.startswith("["):
|
|
54
|
+
maybe_host, maybe_port = target.split(":")
|
|
55
|
+
if maybe_port.isdigit():
|
|
56
|
+
host, port = maybe_host, int(maybe_port)
|
|
57
|
+
return host, port, {}
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def ssh_argv(target: str, timeout: int, login: bool) -> list[str]:
|
|
61
|
+
host, port, entry = parse_target(target)
|
|
62
|
+
argv = ["ssh", *SSH_OPTS, "-o", f"ConnectTimeout={min(timeout, 10)}"]
|
|
63
|
+
if port:
|
|
64
|
+
argv += ["-p", str(port)]
|
|
65
|
+
if entry.get("key"):
|
|
66
|
+
argv += ["-i", os.path.expanduser(entry["key"])]
|
|
67
|
+
argv.append(host)
|
|
68
|
+
return argv
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def execute(target: str, remote_cmd: str, timeout: int, login: bool = False) -> int:
|
|
72
|
+
argv = ssh_argv(target, timeout, login)
|
|
73
|
+
argv.append(f"bash -lc {shlex.quote(remote_cmd)}" if login else remote_cmd)
|
|
74
|
+
try:
|
|
75
|
+
proc = subprocess.run(argv, capture_output=True, text=True, timeout=timeout)
|
|
76
|
+
except subprocess.TimeoutExpired:
|
|
77
|
+
print(f"timed out after {timeout}s: {remote_cmd[:60]}", file=sys.stderr)
|
|
78
|
+
return 124
|
|
79
|
+
if proc.stdout:
|
|
80
|
+
sys.stdout.write(proc.stdout)
|
|
81
|
+
if proc.returncode != 0 and proc.stderr:
|
|
82
|
+
sys.stderr.write(proc.stderr)
|
|
83
|
+
return proc.returncode
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
PROBE = r"""echo "== host"; hostname; uptime | sed 's/^ *//'
|
|
87
|
+
echo "== disk"; df -h --output=target,size,used,pcent 2>/dev/null | awk 'NR==1||(($4+0)>=70 && $1 !~ /^\/snap/)' | head -8
|
|
88
|
+
echo "== mem"; free -h 2>/dev/null | awk 'NR<=2'
|
|
89
|
+
echo "== docker"; (docker ps --format '{{.Names}}\t{{.Status}}' 2>/dev/null || echo "none") | head -12
|
|
90
|
+
echo "== load/gpu"; (command -v nvidia-smi >/dev/null && nvidia-smi --query-gpu=name,memory.used,memory.total,utilization.gpu --format=csv,noheader) || echo "no gpu"
|
|
91
|
+
echo "== ports"; (ss -ltnp 2>/dev/null || netstat -ltnp 2>/dev/null) | awk 'NR>1{print $4}' | sort -u | head -12"""
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def cmd_probe(target: str, timeout: int) -> int:
|
|
95
|
+
return execute(target, PROBE, timeout)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def cmd_logs(target: str, name: str, lines: int, timeout: int) -> int:
|
|
99
|
+
cmd = (f"if docker ps --format '{{{{.Names}}}}' | grep -qx {shlex.quote(name)}; then "
|
|
100
|
+
f"docker logs --tail {lines} {shlex.quote(name)} 2>&1; "
|
|
101
|
+
f"else journalctl -u {shlex.quote(name)} -n {lines} --no-pager 2>&1; fi")
|
|
102
|
+
return execute(target, cmd, timeout)
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def cmd_put(target: str, local: str, remote: str, timeout: int) -> int:
|
|
106
|
+
argv = ssh_argv(target, timeout, False) + [f"cat > {shlex.quote(remote)}"]
|
|
107
|
+
with open(local, "rb") as fh:
|
|
108
|
+
proc = subprocess.run(argv, stdin=fh, timeout=timeout)
|
|
109
|
+
return proc.returncode
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def cmd_get(target: str, remote: str, local: str, timeout: int) -> int:
|
|
113
|
+
argv = ssh_argv(target, timeout, False) + [f"cat {shlex.quote(remote)}"]
|
|
114
|
+
proc = subprocess.run(argv, capture_output=True, timeout=timeout)
|
|
115
|
+
if proc.returncode != 0:
|
|
116
|
+
sys.stderr.write(proc.stderr.decode("utf-8", "replace"))
|
|
117
|
+
return proc.returncode
|
|
118
|
+
Path(local).write_bytes(proc.stdout)
|
|
119
|
+
return 0
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def cmd_add(alias: str, spec: str, key: str | None, note: str | None) -> int:
|
|
123
|
+
hosts = load_hosts()
|
|
124
|
+
host, port = spec, None
|
|
125
|
+
if spec.count(":") == 1 and spec.split(":")[1].isdigit():
|
|
126
|
+
host, port = spec.split(":")[0], int(spec.split(":")[1])
|
|
127
|
+
hosts[alias] = {"host": host, "port": port, "key": key, "note": note}
|
|
128
|
+
save_hosts(hosts)
|
|
129
|
+
print(f"added {alias} -> {host}{':' + str(port) if port else ''}")
|
|
130
|
+
return 0
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def cmd_ls() -> int:
|
|
134
|
+
hosts = load_hosts()
|
|
135
|
+
if not hosts:
|
|
136
|
+
print(f"no hosts in {CONFIG}; add one: rx.py add stage me@1.2.3.4")
|
|
137
|
+
return 0
|
|
138
|
+
for alias, entry in sorted(hosts.items()):
|
|
139
|
+
port = f":{entry['port']}" if entry.get("port") else ""
|
|
140
|
+
note = f" # {entry['note']}" if entry.get("note") else ""
|
|
141
|
+
print(f"{alias:16} {entry['host']}{port}{note}")
|
|
142
|
+
return 0
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def self_test() -> int:
|
|
146
|
+
import tempfile
|
|
147
|
+
global CONFIG
|
|
148
|
+
with tempfile.TemporaryDirectory() as tmp:
|
|
149
|
+
CONFIG = Path(tmp) / "hosts.json"
|
|
150
|
+
assert cmd_add("stage", "deploy@10.0.0.5:2222", "/tmp/demo_key", "staging") == 0
|
|
151
|
+
host, port, entry = parse_target("stage")
|
|
152
|
+
assert (host, port) == ("deploy@10.0.0.5", 2222), (host, port)
|
|
153
|
+
assert entry["key"].endswith("demo_key")
|
|
154
|
+
assert parse_target("root@1.2.3.4")[0] == "root@1.2.3.4"
|
|
155
|
+
assert parse_target("host:99")[1] == 99
|
|
156
|
+
assert parse_target("2001:db8::1")[0] == "2001:db8::1", "ipv6 must not split"
|
|
157
|
+
argv = ssh_argv("stage", 30, False)
|
|
158
|
+
assert "-o" in argv and "BatchMode=yes" in argv and "-p" in argv and "2222" in argv
|
|
159
|
+
assert oct(CONFIG.stat().st_mode)[-3:] == "600", "config must be private"
|
|
160
|
+
tricky = "echo 'a b' && ls \"$HOME\""
|
|
161
|
+
assert shlex.quote(tricky).count("'") >= 2
|
|
162
|
+
print("self-test ok")
|
|
163
|
+
return 0
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def main(argv: list[str]) -> int:
|
|
167
|
+
opts = dict(a.lstrip("-").split("=", 1) for a in argv[1:] if a.startswith("--") and "=" in a)
|
|
168
|
+
args = [a for a in argv[1:] if not a.startswith("--")]
|
|
169
|
+
if not args or args[0] in {"-h", "--help", "help"}:
|
|
170
|
+
print(__doc__)
|
|
171
|
+
return 0
|
|
172
|
+
cmd, rest = args[0], args[1:]
|
|
173
|
+
timeout = int(opts.get("timeout", 60))
|
|
174
|
+
if cmd == "self-test":
|
|
175
|
+
return self_test()
|
|
176
|
+
if cmd == "ls":
|
|
177
|
+
return cmd_ls()
|
|
178
|
+
if cmd == "add" and len(rest) >= 2:
|
|
179
|
+
return cmd_add(rest[0], rest[1], opts.get("key"), opts.get("note"))
|
|
180
|
+
if cmd == "rm" and rest:
|
|
181
|
+
hosts = load_hosts()
|
|
182
|
+
if hosts.pop(rest[0], None) is None:
|
|
183
|
+
print(f"no alias {rest[0]}", file=sys.stderr)
|
|
184
|
+
return 2
|
|
185
|
+
save_hosts(hosts)
|
|
186
|
+
print(f"removed {rest[0]}")
|
|
187
|
+
return 0
|
|
188
|
+
if cmd == "run" and len(rest) >= 2:
|
|
189
|
+
return execute(rest[0], rest[1], timeout, login="login" in opts)
|
|
190
|
+
if cmd == "probe" and rest:
|
|
191
|
+
return cmd_probe(rest[0], timeout)
|
|
192
|
+
if cmd == "logs" and len(rest) >= 2:
|
|
193
|
+
return cmd_logs(rest[0], rest[1], int(opts.get("lines", 80)), timeout)
|
|
194
|
+
if cmd == "put" and len(rest) >= 3:
|
|
195
|
+
return cmd_put(rest[0], rest[1], rest[2], timeout)
|
|
196
|
+
if cmd == "get" and len(rest) >= 3:
|
|
197
|
+
return cmd_get(rest[0], rest[1], rest[2], timeout)
|
|
198
|
+
print(f"unknown or incomplete command: {' '.join(args)}", file=sys.stderr)
|
|
199
|
+
return 2
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
if __name__ == "__main__":
|
|
203
|
+
raise SystemExit(main(sys.argv))
|