agent-pty 0.7.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- agent_pty/__init__.py +7 -0
- agent_pty/main.py +590 -0
- agent_pty/py.typed +0 -0
- agent_pty/session.py +1386 -0
- agent_pty-0.7.1.dist-info/METADATA +212 -0
- agent_pty-0.7.1.dist-info/RECORD +9 -0
- agent_pty-0.7.1.dist-info/WHEEL +4 -0
- agent_pty-0.7.1.dist-info/entry_points.txt +3 -0
- agent_pty-0.7.1.dist-info/licenses/LICENSE +21 -0
agent_pty/__init__.py
ADDED
agent_pty/main.py
ADDED
|
@@ -0,0 +1,590 @@
|
|
|
1
|
+
"""agent-pty: SSH with persistent, background PTY sessions."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import contextlib
|
|
6
|
+
import json
|
|
7
|
+
import os
|
|
8
|
+
import select
|
|
9
|
+
import socket
|
|
10
|
+
import subprocess
|
|
11
|
+
import sys
|
|
12
|
+
import termios
|
|
13
|
+
import time
|
|
14
|
+
import tty
|
|
15
|
+
import uuid
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
|
|
18
|
+
import click
|
|
19
|
+
|
|
20
|
+
from .session import (
|
|
21
|
+
SESSIONS_DIR,
|
|
22
|
+
clean_output,
|
|
23
|
+
ensure_dirs,
|
|
24
|
+
list_sessions,
|
|
25
|
+
log_path,
|
|
26
|
+
pid_alive,
|
|
27
|
+
prune_artifacts,
|
|
28
|
+
sock_path,
|
|
29
|
+
state_path,
|
|
30
|
+
strip_ansi,
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
CONTEXT = {"help_option_names": ["-h", "--help"]}
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
# ── client transport ─────────────────────────────────────────────
|
|
37
|
+
def _rpc(path: Path, op: str, wait: float | None = 15, **args) -> dict:
|
|
38
|
+
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
|
39
|
+
sock.settimeout(wait)
|
|
40
|
+
try:
|
|
41
|
+
sock.connect(str(path))
|
|
42
|
+
sock.sendall(json.dumps({"op": op, "args": args}).encode() + b"\n")
|
|
43
|
+
return json.loads(_recv_line(sock))
|
|
44
|
+
except (OSError, ValueError) as exc:
|
|
45
|
+
return {"ok": False, "error": str(exc)}
|
|
46
|
+
finally:
|
|
47
|
+
sock.close()
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _recv_line(sock: socket.socket) -> str:
|
|
51
|
+
chunks = bytearray()
|
|
52
|
+
while b"\n" not in chunks:
|
|
53
|
+
chunk = sock.recv(65536)
|
|
54
|
+
if not chunk:
|
|
55
|
+
break
|
|
56
|
+
chunks.extend(chunk)
|
|
57
|
+
return bytes(chunks).split(b"\n", 1)[0].decode("utf-8", errors="replace")
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _resolve(name: str | None) -> dict:
|
|
61
|
+
sessions = list_sessions(clean=True)
|
|
62
|
+
if not sessions:
|
|
63
|
+
raise click.ClickException("no live sessions; run 'agent-pty connect HOST' first")
|
|
64
|
+
if not name:
|
|
65
|
+
if len(sessions) > 1:
|
|
66
|
+
names = ", ".join(s["id"] for s in sessions)
|
|
67
|
+
raise click.ClickException(f"several sessions live ({names}); pick one with -s")
|
|
68
|
+
return sessions[0]
|
|
69
|
+
exact = [s for s in sessions if name in (s["id"], s.get("name"))]
|
|
70
|
+
if len(exact) > 1:
|
|
71
|
+
raise click.ClickException(f"several sessions are named {name!r}; use a full id")
|
|
72
|
+
if exact:
|
|
73
|
+
return exact[0]
|
|
74
|
+
partial = [s for s in sessions if s["id"].startswith(name)]
|
|
75
|
+
if len(partial) == 1:
|
|
76
|
+
return partial[0]
|
|
77
|
+
raise click.ClickException(f"no single session matches {name!r}")
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _slug(text: str) -> str:
|
|
81
|
+
return "".join(c if c.isalnum() else "-" for c in text).strip("-")
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _session_id(name: str | None, user: str | None, host: str) -> str:
|
|
85
|
+
base = _slug(name) if name else _slug(f"{user or 'ssh'}-{host}")
|
|
86
|
+
return f"{base}-{uuid.uuid4().hex[:6]}"
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _rpc_or_fail(state: dict, op: str, wait: float | None = 15, **args) -> dict:
|
|
90
|
+
response = _rpc(Path(state["socket"]), op, wait, **args)
|
|
91
|
+
if not response.get("ok"):
|
|
92
|
+
raise click.ClickException(response.get("error", "request failed"))
|
|
93
|
+
return response
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def _tail(path: Path, lines: int, raw: bool = False) -> str:
|
|
97
|
+
with path.open("rb") as fh:
|
|
98
|
+
fh.seek(0, os.SEEK_END)
|
|
99
|
+
size = fh.tell()
|
|
100
|
+
data = b""
|
|
101
|
+
while size > 0 and data.count(b"\n") <= lines and len(data) < 262_144:
|
|
102
|
+
step = min(8192, size)
|
|
103
|
+
size -= step
|
|
104
|
+
fh.seek(size)
|
|
105
|
+
data = fh.read(step) + data
|
|
106
|
+
text = clean_output(data.decode("utf-8", errors="replace"))
|
|
107
|
+
if not raw:
|
|
108
|
+
text = strip_ansi(text)
|
|
109
|
+
return "\n".join(text.splitlines()[-lines:]) + ("\n" if text else "")
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
# ── CLI ──────────────────────────────────────────────────────────
|
|
113
|
+
@click.group(context_settings=CONTEXT)
|
|
114
|
+
@click.version_option(package_name="agent-pty")
|
|
115
|
+
def cli() -> None:
|
|
116
|
+
"""SSH into a machine with a full interactive PTY, held open in the background.
|
|
117
|
+
|
|
118
|
+
Open a session once, then run commands, attach to the live shell, or move
|
|
119
|
+
files to and from it from separate invocations. Commands run with exec
|
|
120
|
+
share the shell's state: cd, exports and functions persist.
|
|
121
|
+
"""
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
@cli.command("connect")
|
|
125
|
+
@click.argument("host")
|
|
126
|
+
@click.option("-p", "--port", default=None, type=int, help="SSH port. Default 22 or ~/.ssh/config.")
|
|
127
|
+
@click.option("-u", "--user", default=None, help="Remote username. Default from ~/.ssh/config or $USER.")
|
|
128
|
+
@click.option("-i", "--key-file", default=None, help="SSH private key file.")
|
|
129
|
+
@click.option(
|
|
130
|
+
"--password",
|
|
131
|
+
default=None,
|
|
132
|
+
help="SSH password. Prompted when neither password nor key is given.",
|
|
133
|
+
)
|
|
134
|
+
@click.option("--ttl", default=30, show_default=True, type=int, help="Idle timeout in minutes.")
|
|
135
|
+
@click.option("-n", "--name", default=None, help="Friendly session name.")
|
|
136
|
+
@click.option("--insecure", is_flag=True, help="Do not verify or record host keys.")
|
|
137
|
+
@click.option("--agent/--no-agent", default=True, show_default=True, help="Use ssh-agent keys.")
|
|
138
|
+
@click.option("--connect-timeout", default=20, show_default=True, type=int, help="SSH connect timeout in seconds.")
|
|
139
|
+
@click.option(
|
|
140
|
+
"--keepalive", default=30, show_default=True, type=int, help="SSH keepalive interval in seconds, 0 to disable."
|
|
141
|
+
)
|
|
142
|
+
@click.option(
|
|
143
|
+
"-J", "--jump", "jumps", multiple=True, metavar="[USER@]HOST[:PORT]", help="Jump host, repeatable for a chain."
|
|
144
|
+
)
|
|
145
|
+
@click.option(
|
|
146
|
+
"--jump-password",
|
|
147
|
+
"jump_passwords",
|
|
148
|
+
multiple=True,
|
|
149
|
+
help="Password for a jump host, repeatable in -J order. Hops without one use ssh config keys or the agent.",
|
|
150
|
+
)
|
|
151
|
+
@click.option("--forward-agent", is_flag=True, help="Forward the local ssh-agent to the remote side.")
|
|
152
|
+
@click.option(
|
|
153
|
+
"--reconnect", default=0, show_default=True, type=int, help="Reconnect attempts after a dropped connection."
|
|
154
|
+
)
|
|
155
|
+
def connect(
|
|
156
|
+
host: str,
|
|
157
|
+
port: int,
|
|
158
|
+
user: str | None,
|
|
159
|
+
key_file: str | None,
|
|
160
|
+
password: str | None,
|
|
161
|
+
ttl: int,
|
|
162
|
+
name: str | None,
|
|
163
|
+
insecure: bool,
|
|
164
|
+
agent: bool,
|
|
165
|
+
connect_timeout: int,
|
|
166
|
+
keepalive: int,
|
|
167
|
+
jumps: tuple[str, ...],
|
|
168
|
+
jump_passwords: tuple[str, ...],
|
|
169
|
+
forward_agent: bool,
|
|
170
|
+
reconnect: int,
|
|
171
|
+
) -> None:
|
|
172
|
+
"""Open a background session with an interactive PTY on HOST.
|
|
173
|
+
|
|
174
|
+
HOST is resolved through ~/.ssh/config when it has an entry, so aliases,
|
|
175
|
+
IdentityFile, User and Port work without extra flags.
|
|
176
|
+
"""
|
|
177
|
+
if not password and not key_file:
|
|
178
|
+
if not sys.stdin.isatty():
|
|
179
|
+
raise click.ClickException("provide --password or --key-file")
|
|
180
|
+
password = click.prompt("SSH password", hide_input=True)
|
|
181
|
+
if jump_passwords and len(jump_passwords) != len(jumps):
|
|
182
|
+
raise click.ClickException("pass one --jump-password per -J hop")
|
|
183
|
+
|
|
184
|
+
ensure_dirs()
|
|
185
|
+
session_id = _session_id(name, user, host)
|
|
186
|
+
config = {
|
|
187
|
+
"id": session_id,
|
|
188
|
+
"name": name or session_id,
|
|
189
|
+
"host": host,
|
|
190
|
+
"port": port,
|
|
191
|
+
"user": user,
|
|
192
|
+
"password": password,
|
|
193
|
+
"key_file": str(Path(key_file).expanduser()) if key_file else None,
|
|
194
|
+
"insecure": insecure,
|
|
195
|
+
"agent": agent,
|
|
196
|
+
"connect_timeout": connect_timeout,
|
|
197
|
+
"keepalive": keepalive,
|
|
198
|
+
"jump": list(jumps),
|
|
199
|
+
"jump_passwords": list(jump_passwords),
|
|
200
|
+
"forward_agent": forward_agent,
|
|
201
|
+
"reconnect": reconnect,
|
|
202
|
+
"ttl": ttl,
|
|
203
|
+
}
|
|
204
|
+
config_path = SESSIONS_DIR / f"{session_id}.cfg"
|
|
205
|
+
config_path.write_text(json.dumps(config), encoding="utf-8")
|
|
206
|
+
os.chmod(config_path, 0o600)
|
|
207
|
+
|
|
208
|
+
with log_path(session_id).open("ab") as log:
|
|
209
|
+
os.chmod(log_path(session_id), 0o600)
|
|
210
|
+
proc = subprocess.Popen( # noqa: S603
|
|
211
|
+
[
|
|
212
|
+
sys.executable,
|
|
213
|
+
"-c",
|
|
214
|
+
"import sys; from agent_pty.session import serve; serve(sys.argv[1])",
|
|
215
|
+
str(config_path),
|
|
216
|
+
],
|
|
217
|
+
stdin=subprocess.DEVNULL,
|
|
218
|
+
stdout=log,
|
|
219
|
+
stderr=subprocess.STDOUT,
|
|
220
|
+
start_new_session=True,
|
|
221
|
+
close_fds=True,
|
|
222
|
+
)
|
|
223
|
+
|
|
224
|
+
deadline = time.time() + 40
|
|
225
|
+
while time.time() < deadline:
|
|
226
|
+
if proc.poll() is not None:
|
|
227
|
+
break
|
|
228
|
+
if sock_path(session_id).exists():
|
|
229
|
+
probe = _rpc(sock_path(session_id), "info", 2)
|
|
230
|
+
if probe.get("ok"):
|
|
231
|
+
target = f"{probe.get('user')}@{host}:{probe.get('port')}"
|
|
232
|
+
click.echo(f"{session_id}\t{target}\tttl {ttl}m")
|
|
233
|
+
return
|
|
234
|
+
time.sleep(0.1)
|
|
235
|
+
|
|
236
|
+
detail = ""
|
|
237
|
+
with contextlib.suppress(OSError):
|
|
238
|
+
detail = log_path(session_id).read_text(encoding="utf-8")[-800:]
|
|
239
|
+
for leftover in (config_path, sock_path(session_id), state_path(session_id), log_path(session_id)):
|
|
240
|
+
leftover.unlink(missing_ok=True)
|
|
241
|
+
raise click.ClickException(f"could not start session\n{detail}".strip())
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
@cli.command("sessions")
|
|
245
|
+
@click.option("--json", "as_json", is_flag=True, help="Print the session list as JSON.")
|
|
246
|
+
def sessions_cmd(as_json: bool) -> None:
|
|
247
|
+
"""List live background sessions."""
|
|
248
|
+
found = list_sessions(clean=True)
|
|
249
|
+
probes = {state["id"]: _rpc(Path(state["socket"]), "info", 0.5) for state in found}
|
|
250
|
+
if as_json:
|
|
251
|
+
entries = []
|
|
252
|
+
for state in found:
|
|
253
|
+
probe = probes[state["id"]]
|
|
254
|
+
entry = dict(state)
|
|
255
|
+
entry["live"] = probe.get("ok", False)
|
|
256
|
+
for key in ("idle_seconds", "uptime_seconds", "attached", "running", "forwards"):
|
|
257
|
+
entry[key] = probe.get(key)
|
|
258
|
+
entries.append(entry)
|
|
259
|
+
click.echo(json.dumps(entries, indent=2))
|
|
260
|
+
return
|
|
261
|
+
if not found:
|
|
262
|
+
click.echo("no live sessions")
|
|
263
|
+
return
|
|
264
|
+
rows = [("ID", "NAME", "TARGET", "PID", "IDLE", "STARTED", "TTL")]
|
|
265
|
+
for state in found:
|
|
266
|
+
probe = probes[state["id"]]
|
|
267
|
+
idle = f"{probe['idle_seconds']}s" if probe.get("ok") else "-"
|
|
268
|
+
rows.append(
|
|
269
|
+
(
|
|
270
|
+
state["id"],
|
|
271
|
+
state.get("name", "-"),
|
|
272
|
+
f"{state['user']}@{state['host']}:{state['port']}",
|
|
273
|
+
str(state["pid"]),
|
|
274
|
+
idle,
|
|
275
|
+
state.get("started_at", "?"),
|
|
276
|
+
f"{state.get('ttl', '?')}m",
|
|
277
|
+
)
|
|
278
|
+
)
|
|
279
|
+
widths = [max(len(row[i]) for row in rows) for i in range(len(rows[0]))]
|
|
280
|
+
for row in rows:
|
|
281
|
+
click.echo(" ".join(cell.ljust(widths[i]) for i, cell in enumerate(row)).rstrip())
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
@cli.command("exec")
|
|
285
|
+
@click.option("-s", "--session", "name", default=None, help="Session id, name, or unique prefix.")
|
|
286
|
+
@click.option("--timeout", default=120.0, show_default=True, help="Seconds to wait for output.")
|
|
287
|
+
@click.argument("command", nargs=-1, required=True)
|
|
288
|
+
def exec_cmd(name: str | None, timeout: float, command: tuple[str, ...]) -> None:
|
|
289
|
+
"""Run COMMAND in the live PTY shell. Shell state persists across calls.
|
|
290
|
+
|
|
291
|
+
The command's output is printed and its exit code becomes agent-pty's exit
|
|
292
|
+
code. On timeout the command is interrupted and agent-pty exits 124.
|
|
293
|
+
"""
|
|
294
|
+
state = _resolve(name)
|
|
295
|
+
result = _rpc(
|
|
296
|
+
Path(state["socket"]),
|
|
297
|
+
"exec",
|
|
298
|
+
timeout + 30,
|
|
299
|
+
command=" ".join(command),
|
|
300
|
+
timeout=timeout,
|
|
301
|
+
)
|
|
302
|
+
output = result.get("output") or ""
|
|
303
|
+
if output:
|
|
304
|
+
click.echo(output, nl=not output.endswith("\n"))
|
|
305
|
+
if not result.get("ok"):
|
|
306
|
+
if result.get("timed_out") or result.get("interrupted"):
|
|
307
|
+
click.echo(f"agent-pty: {result.get('error', 'interrupted')}", err=True)
|
|
308
|
+
sys.exit(int(result.get("exit_code", 124)))
|
|
309
|
+
raise click.ClickException(result.get("error", "request failed"))
|
|
310
|
+
sys.exit(int(result.get("exit_code", 0)))
|
|
311
|
+
|
|
312
|
+
|
|
313
|
+
@cli.command("shell")
|
|
314
|
+
@click.option("-s", "--session", "name", default=None, help="Session id, name, or unique prefix.")
|
|
315
|
+
def shell(name: str | None) -> None:
|
|
316
|
+
"""Attach to the live PTY. Press Ctrl-] to detach without closing it."""
|
|
317
|
+
state = _resolve(name)
|
|
318
|
+
if not sys.stdin.isatty():
|
|
319
|
+
raise click.ClickException("shell needs a TTY")
|
|
320
|
+
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
|
321
|
+
sock.settimeout(10)
|
|
322
|
+
try:
|
|
323
|
+
sock.connect(state["socket"])
|
|
324
|
+
except OSError as exc:
|
|
325
|
+
raise click.ClickException(str(exc)) from exc
|
|
326
|
+
columns, rows = os.get_terminal_size()
|
|
327
|
+
sock.sendall(json.dumps({"op": "attach", "args": {"cols": columns, "rows": rows}}).encode() + b"\n")
|
|
328
|
+
if not json.loads(_recv_line(sock)).get("ok"):
|
|
329
|
+
raise click.ClickException("attach refused: the session is running a command")
|
|
330
|
+
sock.settimeout(None)
|
|
331
|
+
|
|
332
|
+
fd = sys.stdin.fileno()
|
|
333
|
+
saved = termios.tcgetattr(fd)
|
|
334
|
+
tty.setraw(fd)
|
|
335
|
+
last_size = (columns, rows)
|
|
336
|
+
try:
|
|
337
|
+
while True:
|
|
338
|
+
ready, _, _ = select.select([sock, fd], [], [], 1.0)
|
|
339
|
+
with contextlib.suppress(OSError):
|
|
340
|
+
size = os.get_terminal_size()
|
|
341
|
+
if (size.columns, size.lines) != last_size:
|
|
342
|
+
last_size = (size.columns, size.lines)
|
|
343
|
+
_rpc(Path(state["socket"]), "resize", 2, cols=size.columns, rows=size.lines)
|
|
344
|
+
if sock in ready:
|
|
345
|
+
data = sock.recv(65536)
|
|
346
|
+
if not data:
|
|
347
|
+
break
|
|
348
|
+
sys.stdout.buffer.write(data)
|
|
349
|
+
sys.stdout.buffer.flush()
|
|
350
|
+
if fd in ready:
|
|
351
|
+
data = os.read(fd, 4096)
|
|
352
|
+
if not data or b"\x1d" in data:
|
|
353
|
+
sock.sendall(data.split(b"\x1d", 1)[0])
|
|
354
|
+
break
|
|
355
|
+
sock.sendall(data)
|
|
356
|
+
except OSError as exc:
|
|
357
|
+
click.echo(f"\r\nconnection error: {exc}", err=True)
|
|
358
|
+
finally:
|
|
359
|
+
termios.tcsetattr(fd, termios.TCSADRAIN, saved)
|
|
360
|
+
sock.close()
|
|
361
|
+
click.echo("\r\n[detached]")
|
|
362
|
+
|
|
363
|
+
|
|
364
|
+
@cli.command("logs")
|
|
365
|
+
@click.option("-s", "--session", "name", default=None, help="Session id, name, or unique prefix.")
|
|
366
|
+
@click.option("-n", "--lines", default=40, show_default=True, help="Lines to show.")
|
|
367
|
+
@click.option("-f", "--follow", is_flag=True, help="Keep printing new output.")
|
|
368
|
+
@click.option("--raw", is_flag=True, help="Keep terminal escape sequences.")
|
|
369
|
+
def logs_cmd(name: str | None, lines: int, follow: bool, raw: bool) -> None:
|
|
370
|
+
"""Show the PTY transcript of a session."""
|
|
371
|
+
state = _resolve(name)
|
|
372
|
+
path = Path(state.get("transcript") or "")
|
|
373
|
+
if not path.is_file():
|
|
374
|
+
raise click.ClickException("this session has no transcript yet")
|
|
375
|
+
click.echo(_tail(path, lines, raw), nl=False)
|
|
376
|
+
if not follow:
|
|
377
|
+
return
|
|
378
|
+
position = path.stat().st_size
|
|
379
|
+
try:
|
|
380
|
+
while True:
|
|
381
|
+
with path.open("rb") as fh:
|
|
382
|
+
fh.seek(position)
|
|
383
|
+
chunk = fh.read()
|
|
384
|
+
if chunk:
|
|
385
|
+
text = clean_output(chunk.decode("utf-8", errors="replace"))
|
|
386
|
+
click.echo(text if raw else strip_ansi(text), nl=False)
|
|
387
|
+
position += len(chunk)
|
|
388
|
+
if not pid_alive(state["pid"]):
|
|
389
|
+
click.echo("\n[session closed]")
|
|
390
|
+
return
|
|
391
|
+
time.sleep(0.25)
|
|
392
|
+
except KeyboardInterrupt:
|
|
393
|
+
return
|
|
394
|
+
|
|
395
|
+
|
|
396
|
+
@cli.command("upload")
|
|
397
|
+
@click.option("-s", "--session", "name", default=None, help="Session id, name, or unique prefix.")
|
|
398
|
+
@click.argument("local")
|
|
399
|
+
@click.argument("remote", required=False)
|
|
400
|
+
def upload(name: str | None, local: str, remote: str | None) -> None:
|
|
401
|
+
"""Upload a local FILE to the remote host."""
|
|
402
|
+
state = _resolve(name)
|
|
403
|
+
result = _rpc_or_fail(state, "upload", 3600, local=local, remote=remote, dir=False)
|
|
404
|
+
click.echo(f"uploaded {local} -> {result['remote']}")
|
|
405
|
+
|
|
406
|
+
|
|
407
|
+
@cli.command("upload-dir")
|
|
408
|
+
@click.option("-s", "--session", "name", default=None, help="Session id, name, or unique prefix.")
|
|
409
|
+
@click.argument("local")
|
|
410
|
+
@click.argument("remote", required=False)
|
|
411
|
+
def upload_dir(name: str | None, local: str, remote: str | None) -> None:
|
|
412
|
+
"""Upload a local DIRECTORY tree to the remote host."""
|
|
413
|
+
state = _resolve(name)
|
|
414
|
+
result = _rpc_or_fail(state, "upload", 3600, local=local, remote=remote, dir=True)
|
|
415
|
+
click.echo(f"uploaded {result['files']} file(s) -> {result['remote']}")
|
|
416
|
+
|
|
417
|
+
|
|
418
|
+
@cli.command("download")
|
|
419
|
+
@click.option("-s", "--session", "name", default=None, help="Session id, name, or unique prefix.")
|
|
420
|
+
@click.argument("remote")
|
|
421
|
+
@click.argument("local", required=False)
|
|
422
|
+
def download(name: str | None, remote: str, local: str | None) -> None:
|
|
423
|
+
"""Download a remote FILE."""
|
|
424
|
+
state = _resolve(name)
|
|
425
|
+
result = _rpc_or_fail(state, "download", 3600, remote=remote, local=local, dir=False)
|
|
426
|
+
click.echo(f"downloaded {remote} -> {result['local']}")
|
|
427
|
+
|
|
428
|
+
|
|
429
|
+
@cli.command("download-dir")
|
|
430
|
+
@click.option("-s", "--session", "name", default=None, help="Session id, name, or unique prefix.")
|
|
431
|
+
@click.argument("remote")
|
|
432
|
+
@click.argument("local", required=False)
|
|
433
|
+
def download_dir(name: str | None, remote: str, local: str | None) -> None:
|
|
434
|
+
"""Download a remote DIRECTORY tree."""
|
|
435
|
+
state = _resolve(name)
|
|
436
|
+
result = _rpc_or_fail(state, "download", 3600, remote=remote, local=local, dir=True)
|
|
437
|
+
click.echo(f"downloaded {result['files']} file(s) -> {result['local']}")
|
|
438
|
+
|
|
439
|
+
|
|
440
|
+
@cli.command("close")
|
|
441
|
+
@click.option("-s", "--session", "name", default=None, help="Session id, name, or unique prefix.")
|
|
442
|
+
@click.option("--all", "close_all", is_flag=True, help="Close every live session.")
|
|
443
|
+
def close(name: str | None, close_all: bool) -> None:
|
|
444
|
+
"""Close a session and its SSH connection."""
|
|
445
|
+
targets = list_sessions(clean=True) if close_all else [_resolve(name)]
|
|
446
|
+
if not targets:
|
|
447
|
+
click.echo("no live sessions")
|
|
448
|
+
return
|
|
449
|
+
for state in targets:
|
|
450
|
+
_rpc(Path(state["socket"]), "close", 10)
|
|
451
|
+
click.echo(f"closed {state['id']}")
|
|
452
|
+
|
|
453
|
+
|
|
454
|
+
@cli.command("info")
|
|
455
|
+
@click.option("-s", "--session", "name", default=None, help="Session id, name, or unique prefix.")
|
|
456
|
+
@click.option("--json", "as_json", is_flag=True, help="Print the state as JSON.")
|
|
457
|
+
def info_cmd(name: str | None, as_json: bool) -> None:
|
|
458
|
+
"""Show one session's state."""
|
|
459
|
+
state = _resolve(name)
|
|
460
|
+
result = _rpc_or_fail(state, "info", 10)
|
|
461
|
+
if as_json:
|
|
462
|
+
click.echo(json.dumps(result, indent=2))
|
|
463
|
+
return
|
|
464
|
+
keys = (
|
|
465
|
+
"id",
|
|
466
|
+
"name",
|
|
467
|
+
"host",
|
|
468
|
+
"port",
|
|
469
|
+
"user",
|
|
470
|
+
"idle_seconds",
|
|
471
|
+
"uptime_seconds",
|
|
472
|
+
"started_at",
|
|
473
|
+
"ttl",
|
|
474
|
+
"attached",
|
|
475
|
+
"connected",
|
|
476
|
+
"reconnect",
|
|
477
|
+
"jumps",
|
|
478
|
+
"forward_agent",
|
|
479
|
+
"shell",
|
|
480
|
+
"state_bytes",
|
|
481
|
+
"running",
|
|
482
|
+
"transcript",
|
|
483
|
+
)
|
|
484
|
+
for key in keys:
|
|
485
|
+
click.echo(f"{key}: {result.get(key)}")
|
|
486
|
+
for entry in result.get("forwards") or []:
|
|
487
|
+
click.echo(f"forward {entry['id']}: -{entry['direction'][0].upper()} {entry['listen']} -> {entry['target']}")
|
|
488
|
+
|
|
489
|
+
|
|
490
|
+
@cli.command("send")
|
|
491
|
+
@click.option("-s", "--session", "name", default=None, help="Session id, name, or unique prefix.")
|
|
492
|
+
@click.option("--no-newline", is_flag=True, help="Send the text without a trailing newline.")
|
|
493
|
+
@click.argument("text")
|
|
494
|
+
def send_cmd(name: str | None, no_newline: bool, text: str) -> None:
|
|
495
|
+
"""Type TEXT into the live PTY shell."""
|
|
496
|
+
state = _resolve(name)
|
|
497
|
+
_rpc_or_fail(state, "write", 10, data=text if no_newline else text + "\n")
|
|
498
|
+
click.echo("sent")
|
|
499
|
+
|
|
500
|
+
|
|
501
|
+
@cli.command("interrupt")
|
|
502
|
+
@click.option("-s", "--session", "name", default=None, help="Session id, name, or unique prefix.")
|
|
503
|
+
def interrupt_cmd(name: str | None) -> None:
|
|
504
|
+
"""Send Ctrl-C to the live PTY shell."""
|
|
505
|
+
state = _resolve(name)
|
|
506
|
+
_rpc_or_fail(state, "interrupt", 10)
|
|
507
|
+
click.echo("interrupted")
|
|
508
|
+
|
|
509
|
+
|
|
510
|
+
@cli.command("rename")
|
|
511
|
+
@click.option("-s", "--session", "name", default=None, help="Session id, name, or unique prefix.")
|
|
512
|
+
@click.argument("new_name")
|
|
513
|
+
def rename_cmd(name: str | None, new_name: str) -> None:
|
|
514
|
+
"""Give a session a new name."""
|
|
515
|
+
state = _resolve(name)
|
|
516
|
+
result = _rpc_or_fail(state, "rename", 10, name=new_name)
|
|
517
|
+
click.echo(f"renamed {state['id']} -> {result['name']}")
|
|
518
|
+
|
|
519
|
+
|
|
520
|
+
@cli.command("forward")
|
|
521
|
+
@click.option("-s", "--session", "name", default=None, help="Session id, name, or unique prefix.")
|
|
522
|
+
@click.option(
|
|
523
|
+
"-L",
|
|
524
|
+
"--local",
|
|
525
|
+
"local_forwards",
|
|
526
|
+
multiple=True,
|
|
527
|
+
metavar="[BIND:]PORT:HOST:PORT",
|
|
528
|
+
help="Listen locally and forward to the remote side.",
|
|
529
|
+
)
|
|
530
|
+
@click.option(
|
|
531
|
+
"-R",
|
|
532
|
+
"--remote",
|
|
533
|
+
"remote_forwards",
|
|
534
|
+
multiple=True,
|
|
535
|
+
metavar="[BIND:]PORT:HOST:PORT",
|
|
536
|
+
help="Listen on the remote side and forward to the local side.",
|
|
537
|
+
)
|
|
538
|
+
@click.option(
|
|
539
|
+
"-D",
|
|
540
|
+
"--dynamic",
|
|
541
|
+
"dynamic_forwards",
|
|
542
|
+
multiple=True,
|
|
543
|
+
metavar="[BIND:]PORT",
|
|
544
|
+
help="Listen locally as a SOCKS5 proxy.",
|
|
545
|
+
)
|
|
546
|
+
@click.option("--list", "list_forwards", is_flag=True, help="Show active forwards.")
|
|
547
|
+
@click.option("--remove", "remove_id", default=None, type=int, help="Remove a forward by id.")
|
|
548
|
+
def forward_cmd(
|
|
549
|
+
name: str | None,
|
|
550
|
+
local_forwards: tuple[str, ...],
|
|
551
|
+
remote_forwards: tuple[str, ...],
|
|
552
|
+
dynamic_forwards: tuple[str, ...],
|
|
553
|
+
list_forwards: bool,
|
|
554
|
+
remove_id: int | None,
|
|
555
|
+
) -> None:
|
|
556
|
+
"""Add, list, or remove SSH port forwards on a live session."""
|
|
557
|
+
state = _resolve(name)
|
|
558
|
+
if list_forwards:
|
|
559
|
+
info = _rpc_or_fail(state, "info", 10)
|
|
560
|
+
for entry in info.get("forwards") or []:
|
|
561
|
+
click.echo(f"{entry['id']}\t-{entry['direction'][0].upper()}\t{entry['listen']}\t{entry['target']}")
|
|
562
|
+
if not info.get("forwards"):
|
|
563
|
+
click.echo("no forwards")
|
|
564
|
+
return
|
|
565
|
+
if remove_id is not None:
|
|
566
|
+
_rpc_or_fail(state, "unforward", 10, id=remove_id)
|
|
567
|
+
click.echo(f"removed forward {remove_id}")
|
|
568
|
+
return
|
|
569
|
+
groups = (("local", local_forwards), ("remote", remote_forwards), ("dynamic", dynamic_forwards))
|
|
570
|
+
for direction, specs in groups:
|
|
571
|
+
for spec in specs:
|
|
572
|
+
result = _rpc_or_fail(state, "forward", 20, direction=direction, spec=spec)
|
|
573
|
+
click.echo(f"{result['id']}\t-{direction[0].upper()}\t{result['listen']}\t{result['target']}")
|
|
574
|
+
if not any(specs for _, specs in groups):
|
|
575
|
+
raise click.ClickException("pass -L, -R, -D, --list, or --remove")
|
|
576
|
+
|
|
577
|
+
|
|
578
|
+
@cli.command("prune")
|
|
579
|
+
def prune_cmd() -> None:
|
|
580
|
+
"""Delete session files left behind by closed or crashed sessions."""
|
|
581
|
+
click.echo(f"removed {prune_artifacts()} file(s)")
|
|
582
|
+
|
|
583
|
+
|
|
584
|
+
def main() -> None:
|
|
585
|
+
"""Console entry point."""
|
|
586
|
+
cli(prog_name="agent-pty")
|
|
587
|
+
|
|
588
|
+
|
|
589
|
+
if __name__ == "__main__":
|
|
590
|
+
main()
|
agent_pty/py.typed
ADDED
|
File without changes
|