setup-ssh-cli 0.1.0__py3-none-any.whl → 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
setup_ssh/__init__.py CHANGED
@@ -1,3 +1,3 @@
1
1
  """Manage a small, cross-platform group of SSH devices."""
2
2
 
3
- __version__ = "0.1.0"
3
+ __version__ = "0.2.0"
setup_ssh/cli.py CHANGED
@@ -4,12 +4,14 @@ import argparse
4
4
  import getpass
5
5
  import socket
6
6
  import sys
7
+ from dataclasses import replace
7
8
  from pathlib import Path
8
9
 
9
10
  import paramiko
10
11
 
11
12
  from . import __version__
12
13
  from .fleet import Check, Fleet
14
+ from .local_setup import prepare_local
13
15
  from .state import Device, Inventory, SetupError, default_path
14
16
  from .transport import (
15
17
  Connector,
@@ -66,6 +68,22 @@ def make_parser() -> argparse.ArgumentParser:
66
68
  parser.add_argument("--batch", action="store_true", help="No password or host-trust prompts")
67
69
  commands = parser.add_subparsers(dest="command", required=True)
68
70
  commands.add_parser("init", help="Guided enrollment and setup for a new group")
71
+ prepare = commands.add_parser(
72
+ "prepare-local", help="Enable local OpenSSH and allow peers through UFW"
73
+ )
74
+ prepare.add_argument(
75
+ "--allow-from",
76
+ action="append",
77
+ default=[],
78
+ metavar="IP",
79
+ help="Peer source IP (repeat for each address)",
80
+ )
81
+ prepare.add_argument(
82
+ "--port", type=int, default=22, help="Existing sshd port to allow (default: 22)"
83
+ )
84
+ prepare.add_argument(
85
+ "--dry-run", action="store_true", help="Show commands without running sudo"
86
+ )
69
87
  add = commands.add_parser("add", help="Enroll a device, then synchronize the group")
70
88
  add.add_argument("--name")
71
89
  add.add_argument("--host", help="LAN or NetBird address")
@@ -85,6 +103,12 @@ def make_parser() -> argparse.ArgumentParser:
85
103
  "--dry-run", action="store_true", help="Show the saved plan without connecting"
86
104
  )
87
105
  commands.add_parser("check", help="Test all connection directions without editing SSH files")
106
+ commands.add_parser("dashboard", help="Inspect devices and live peer SSH connections")
107
+ export = commands.add_parser("export", help="Export a portable public inventory")
108
+ export.add_argument("file", type=Path)
109
+ import_command = commands.add_parser("import", help="Import a read-only fleet inventory")
110
+ import_command.add_argument("file", type=Path)
111
+ import_command.add_argument("--local", required=True, help="Alias of this enrolled account")
88
112
  commands.add_parser("list", help="List enrolled devices")
89
113
  commands.add_parser("plan", help="Show the saved plan without connecting or modifying files")
90
114
  remove = commands.add_parser("remove", help="Remove a device and revoke its key on peers")
@@ -115,12 +139,45 @@ def report(checks: list[Check]) -> int:
115
139
  return 1 if failures else 0
116
140
 
117
141
 
142
+ def import_inventory(
143
+ path: Path, existing: Inventory, source: Path, local: str, batch: bool
144
+ ) -> None:
145
+ portable = Inventory.load(source.expanduser())
146
+ if not portable.devices:
147
+ raise SetupError("The source file has no enrolled devices.")
148
+ selected = portable.find(local)
149
+ if not current_account_matches(selected.user):
150
+ raise SetupError(f"Run the import as the enrolled account {selected.user}.")
151
+ if selected.platform not in {"auto", local_platform()}:
152
+ raise SetupError(f"{selected.name} is enrolled as {selected.platform}.")
153
+ if not selected.public_key or not selected.host_key:
154
+ raise SetupError(f"Finish syncing {selected.name} on the management machine before import.")
155
+ if path.exists() and (not existing.read_only or existing.group_id != portable.group_id):
156
+ raise SetupError(
157
+ "Choose a different --config path. The destination contains another inventory."
158
+ )
159
+ imported = replace(
160
+ portable,
161
+ devices=[replace(device, local=device.id == selected.id) for device in portable.devices],
162
+ version=2,
163
+ )
164
+ print(f"Read-only inventory for {selected.name} at {path}")
165
+ for device in imported.devices:
166
+ print(f" {device.name:16} {device.user}@{device.host}:{device.port}")
167
+ if batch or confirm("Save this inventory?"):
168
+ imported.save(path, overwrite=existing.read_only)
169
+ print("Inventory saved. Run setup-ssh dashboard to inspect connections.")
170
+
171
+
118
172
  def main(argv: list[str] | None = None) -> int:
119
173
  parser = make_parser()
120
174
  args = parser.parse_args(argv)
121
175
  if not 1 <= args.timeout <= 300:
122
176
  parser.error("--timeout must be between 1 and 300 seconds")
123
177
  try:
178
+ if args.command == "prepare-local":
179
+ prepare_local(args.allow_from, args.port, args.dry_run, args.batch, confirm)
180
+ return 0
124
181
  if args.command == "doctor":
125
182
  print("\n".join(diagnostics()))
126
183
  print("\n" + doctor_instructions(args.os or local_platform()))
@@ -132,6 +189,37 @@ def main(argv: list[str] | None = None) -> int:
132
189
  return 0
133
190
  path = args.config.expanduser().absolute()
134
191
  inventory = Inventory.load(path)
192
+ if inventory.read_only and args.command in {"init", "add", "sync", "remove"}:
193
+ raise SetupError(
194
+ "This inventory is read-only. Run management commands on the original machine."
195
+ )
196
+ if args.command == "import":
197
+ import_inventory(path, inventory, args.file, args.local, args.batch)
198
+ return 0
199
+ if args.command == "export":
200
+ if not inventory.devices:
201
+ raise SetupError("There are no enrolled devices to export.")
202
+ portable = replace(
203
+ inventory,
204
+ devices=[replace(device, local=False) for device in inventory.devices],
205
+ version=2,
206
+ )
207
+ portable.save(args.file.expanduser(), overwrite=False)
208
+ print(f"Exported public inventory to {args.file}.")
209
+ return 0
210
+ if args.command == "dashboard":
211
+ try:
212
+ from .dashboard import Dashboard
213
+ except ModuleNotFoundError as exc:
214
+ if exc.name != "textual":
215
+ raise
216
+ raise SetupError(
217
+ 'Install the dashboard extra with uv tool install "setup-ssh-cli[dashboard]".'
218
+ ) from exc
219
+ if not sys.stdin.isatty() or not sys.stdout.isatty():
220
+ raise SetupError("The dashboard requires an interactive terminal.")
221
+ Dashboard(path, args.timeout).run()
222
+ return 0
135
223
  if args.command == "list":
136
224
  if not inventory.devices:
137
225
  print("No devices yet. Run setup-ssh init.")
@@ -151,7 +239,7 @@ def main(argv: list[str] | None = None) -> int:
151
239
  connector = Connector(
152
240
  inventory,
153
241
  timeout=args.timeout,
154
- batch=args.batch,
242
+ batch=args.batch or inventory.read_only,
155
243
  confirm=confirm,
156
244
  save=lambda: inventory.save(path),
157
245
  )
setup_ssh/dashboard.py ADDED
@@ -0,0 +1,175 @@
1
+ """Textual interface for inspecting an enrolled fleet."""
2
+
3
+ from contextlib import closing
4
+ from pathlib import Path
5
+
6
+ from rich.text import Text
7
+ from textual import work
8
+ from textual.app import App, ComposeResult
9
+ from textual.message import Message
10
+ from textual.widgets import DataTable, Footer, Label, TabbedContent, TabPane
11
+ from textual.worker import Worker, WorkerState, get_current_worker
12
+
13
+ from .state import Inventory, SetupError
14
+ from .status import Observation, inspect
15
+
16
+
17
+ class Observed(Message):
18
+ def __init__(self, observation: Observation):
19
+ super().__init__()
20
+ self.observation = observation
21
+
22
+
23
+ class Dashboard(App):
24
+ TITLE = "setup-ssh dashboard"
25
+ BINDINGS = [("r", "refresh_fleet", "Refresh"), ("q", "quit", "Quit")]
26
+ CSS = """
27
+ TabbedContent { height: 1fr; }
28
+ DataTable { height: 1fr; }
29
+ #summary { padding: 0 1; }
30
+ #detail { padding: 0 1; max-height: 6; overflow-y: auto; }
31
+ """
32
+
33
+ def __init__(self, path: Path, timeout: int):
34
+ super().__init__()
35
+ self.path = path
36
+ self.timeout = timeout
37
+ self.inventory = Inventory.load(path)
38
+ self.results: dict[tuple[str, str | None], Observation] = {}
39
+ self.selection: tuple[str, str | None] | None = None
40
+ self.probe: Worker | None = None
41
+
42
+ def compose(self) -> ComposeResult:
43
+ yield Label(id="summary")
44
+ with TabbedContent():
45
+ with TabPane("Connections", id="connections"):
46
+ yield DataTable(id="matrix", cursor_type="cell", fixed_columns=1)
47
+ with TabPane("Devices", id="devices"):
48
+ yield DataTable(id="hosts", cursor_type="row")
49
+ yield Label(id="detail")
50
+ yield Footer()
51
+
52
+ def on_mount(self) -> None:
53
+ self.action_refresh_fleet()
54
+
55
+ def action_refresh_fleet(self) -> None:
56
+ if self.probe is not None:
57
+ return
58
+ summary = self.query_one("#summary", Label)
59
+ try:
60
+ self.inventory = Inventory.load(self.path)
61
+ except SetupError as exc:
62
+ summary.update(Text(str(exc)))
63
+ return
64
+ devices = self.inventory.devices
65
+ matrix = self.query_one("#matrix", DataTable)
66
+ hosts = self.query_one("#hosts", DataTable)
67
+ matrix.clear(columns=True)
68
+ hosts.clear(columns=True)
69
+ matrix.add_column("From / To", key="source")
70
+ hosts.add_columns("Alias", "Account", "Status")
71
+ for device in devices:
72
+ matrix.add_column(device.name, key=device.id)
73
+ for device in devices:
74
+ matrix.add_row(
75
+ device.name,
76
+ *("—" if peer.id == device.id else "Pending" for peer in devices),
77
+ key=device.id,
78
+ )
79
+ account = f"{device.user}@{device.host}:{device.port}"
80
+ hosts.add_row(device.name, Text(account), "Pending", key=device.id)
81
+ self.results.clear()
82
+ self.selection = (devices[0].id, None) if devices else None
83
+ self.show_detail()
84
+ if not devices:
85
+ summary.update("No enrolled devices")
86
+ self.query_one("#detail", Label).update(
87
+ Text(
88
+ f"Inventory: {self.path}\n"
89
+ "Run setup-ssh init to set up a fleet, or import an existing inventory.\n"
90
+ "Press r after saving the inventory."
91
+ )
92
+ )
93
+ return
94
+ summary.update("Checking devices and SSH connections…")
95
+ self.probe = self.run_checks(self.inventory)
96
+
97
+ @work(thread=True, exit_on_error=False)
98
+ def run_checks(self, inventory: Inventory) -> None:
99
+ worker = get_current_worker()
100
+ with closing(inspect(inventory, self.timeout)) as observations:
101
+ for observation in observations:
102
+ if worker.is_cancelled:
103
+ break
104
+ self.post_message(Observed(observation))
105
+
106
+ def on_observed(self, message: Observed) -> None:
107
+ result = message.observation
108
+ self.results[result.source, result.destination] = result
109
+ color = {
110
+ "OK": "green",
111
+ "Ready": "green",
112
+ "Failed": "red",
113
+ "Unreachable": "red",
114
+ "Blocked": "yellow",
115
+ "Setup pending": "yellow",
116
+ "Untested": "dim",
117
+ }[result.status]
118
+ value = Text(result.status, style=color)
119
+ if result.destination is None:
120
+ table = self.query_one("#hosts", DataTable)
121
+ table.update_cell_at((table.get_row_index(result.source), 2), value)
122
+ else:
123
+ self.query_one("#matrix", DataTable).update_cell(
124
+ result.source, result.destination, value
125
+ )
126
+ if self.selection == (result.source, result.destination):
127
+ self.show_detail()
128
+
129
+ def on_worker_state_changed(self, event: Worker.StateChanged) -> None:
130
+ if event.worker is not self.probe:
131
+ return
132
+ summary = self.query_one("#summary", Label)
133
+ if event.state == WorkerState.SUCCESS:
134
+ self.probe = None
135
+ checks = [result for result in self.results.values() if result.destination is not None]
136
+ passed = sum(result.status == "OK" for result in checks)
137
+ failed = sum(result.status == "Failed" for result in checks)
138
+ summary.update(
139
+ f"{passed} passed · {failed} failed · {len(checks) - passed - failed} untested"
140
+ )
141
+ elif event.state == WorkerState.ERROR:
142
+ self.probe = None
143
+ summary.update(Text(f"Refresh interrupted. {event.worker.error}"))
144
+
145
+ def on_data_table_cell_highlighted(self, event: DataTable.CellHighlighted) -> None:
146
+ source, destination = event.cell_key
147
+ self.selection = source.value, None if destination.value == "source" else destination.value
148
+ self.show_detail()
149
+
150
+ def on_data_table_row_highlighted(self, event: DataTable.RowHighlighted) -> None:
151
+ self.selection = event.row_key.value, None
152
+ self.show_detail()
153
+
154
+ def show_detail(self) -> None:
155
+ detail = self.query_one("#detail", Label)
156
+ if self.selection is None:
157
+ detail.update("")
158
+ return
159
+ source, destination = self.selection
160
+ names = {device.id: device.name for device in self.inventory.devices}
161
+ if source not in names or (destination is not None and destination not in names):
162
+ detail.update("")
163
+ return
164
+ if source == destination:
165
+ detail.update("Each device checks the other peers.")
166
+ return
167
+ title = names[source] if destination is None else f"{names[source]} → {names[destination]}"
168
+ result = self.results.get(self.selection)
169
+ if result is None:
170
+ detail.update(Text(f"{title} · Waiting for refresh"))
171
+ return
172
+ message = "".join(
173
+ char if char.isprintable() or char == "\n" else " " for char in result.detail
174
+ )
175
+ detail.update(Text(f"{title} · {result.status} · {result.at:%H:%M:%S %Z}\n{message}"))
setup_ssh/fleet.py CHANGED
@@ -25,7 +25,7 @@ class Fleet:
25
25
  def __init__(
26
26
  self,
27
27
  inventory: Inventory,
28
- path: Path,
28
+ path: Path | None,
29
29
  connector: Connector,
30
30
  output: Callable[[str], None] = print,
31
31
  ):
@@ -35,6 +35,8 @@ class Fleet:
35
35
  self.output = output
36
36
 
37
37
  def save(self) -> None:
38
+ if self.path is None or self.inventory.read_only:
39
+ raise SetupError("This inventory is read-only.")
38
40
  self.inventory.save(self.path)
39
41
 
40
42
  def connect_all(self, *, skip_offline: bool = False) -> dict[str, Session]:
@@ -65,6 +67,8 @@ class Fleet:
65
67
  raise
66
68
 
67
69
  def sync(self, *, check: bool = True, skip_offline: bool = False) -> list[Check]:
70
+ if self.path is None or self.inventory.read_only:
71
+ raise SetupError("This inventory is read-only.")
68
72
  if not self.inventory.devices:
69
73
  raise SetupError("No devices are enrolled. Run setup-ssh init or add first.")
70
74
  sessions = self.connect_all(skip_offline=skip_offline)
@@ -136,32 +140,35 @@ class Fleet:
136
140
  for destination in available:
137
141
  if source.id == destination.id:
138
142
  continue
139
- try:
140
- result = sessions[source.id].run(
141
- script(
142
- self.inventory,
143
- source,
144
- "check",
145
- destination=destination,
146
- timeout=self.connector.timeout,
147
- ),
148
- timeout=self.connector.timeout + 15,
149
- )
150
- ok = result.code == 0 and "setup-ssh-ok" in result.stdout.splitlines()
151
- detail = (
152
- ""
153
- if ok
154
- else (result.stderr or result.stdout or f"exit {result.code}").strip()
155
- )
156
- except (SetupError, OSError, paramiko.SSHException) as exc:
157
- ok, detail = False, str(exc)
158
- check = Check(source.name, destination.name, ok, detail)
143
+ check = self.check_direction(sessions[source.id], source, destination)
159
144
  checks.append(check)
160
- self.output(f" {source.name} -> {destination.name}: {'OK' if ok else 'FAILED'}")
161
- if detail:
162
- self.output(f" {detail}")
145
+ self.output(
146
+ f" {source.name} -> {destination.name}: {'OK' if check.ok else 'FAILED'}"
147
+ )
148
+ if check.detail:
149
+ self.output(f" {check.detail}")
163
150
  return checks
164
151
 
152
+ def check_direction(
153
+ self, session: Session, source: Device, destination: Device, *, normal_alias: bool = False
154
+ ) -> Check:
155
+ try:
156
+ result = session.run(
157
+ script(
158
+ self.inventory,
159
+ source,
160
+ "check-alias" if normal_alias else "check",
161
+ destination=destination,
162
+ timeout=self.connector.timeout,
163
+ ),
164
+ timeout=self.connector.timeout + 15,
165
+ )
166
+ ok = result.code == 0 and "setup-ssh-ok" in result.stdout.splitlines()
167
+ detail = "" if ok else (result.stderr or result.stdout or f"exit {result.code}").strip()
168
+ except (SetupError, OSError, EOFError, paramiko.SSHException) as exc:
169
+ ok, detail = False, str(exc)
170
+ return Check(source.name, destination.name, ok, detail)
171
+
165
172
  def check(self) -> list[Check]:
166
173
  if len(self.inventory.devices) < 2:
167
174
  raise SetupError("Add at least two devices first.")
@@ -175,6 +182,8 @@ class Fleet:
175
182
  session.close()
176
183
 
177
184
  def remove(self, device: Device) -> list[str]:
185
+ if self.path is None or self.inventory.read_only:
186
+ raise SetupError("This inventory is read-only.")
178
187
  # Save revocation intent first: a future sync must never reauthorize this device.
179
188
  self.inventory.devices.remove(device)
180
189
  self.save()
@@ -0,0 +1,104 @@
1
+ """Prepare the local Linux SSH server without elevating the enrollment process."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import shlex
7
+ import shutil
8
+ import subprocess
9
+ import sys
10
+ from collections.abc import Callable
11
+ from ipaddress import ip_address
12
+
13
+ from .state import SetupError
14
+
15
+
16
+ def run(command: list[str], *, capture: bool = False) -> subprocess.CompletedProcess[str]:
17
+ result = subprocess.run(command, capture_output=capture, text=True, check=False)
18
+ if result.returncode:
19
+ detail = f" {result.stderr.strip()}" if capture and result.stderr else ""
20
+ raise SetupError(f"Command failed ({result.returncode}): {shlex.join(command)}.{detail}")
21
+ return result
22
+
23
+
24
+ def prepare_local(
25
+ sources: list[str],
26
+ port: int,
27
+ dry_run: bool,
28
+ batch: bool,
29
+ confirm: Callable[[str], bool],
30
+ ) -> None:
31
+ if not sys.platform.startswith("linux"):
32
+ raise SetupError("prepare-local supports Linux with systemd. See setup-ssh doctor.")
33
+ if not 1 <= port <= 65535:
34
+ raise SetupError("SSH port must be between 1 and 65535.")
35
+ if batch and not dry_run:
36
+ raise SetupError(
37
+ "prepare-local requires interactive approval. Use --dry-run in batch mode."
38
+ )
39
+ if not dry_run and os.geteuid() == 0:
40
+ raise SetupError("Run prepare-local as your normal user. It calls sudo for system changes.")
41
+
42
+ peers = {}
43
+ for source in sources:
44
+ address = ip_address(source)
45
+ if (
46
+ address.is_unspecified
47
+ or address.is_multicast
48
+ or getattr(address, "scope_id", None) is not None
49
+ ):
50
+ raise SetupError(f"Use an unscoped peer IP address: {source}")
51
+ peers[str(address)] = None
52
+
53
+ for program in ("systemctl", "ssh-keygen", "sudo"):
54
+ if not shutil.which(program):
55
+ raise SetupError(f"{program} is required. See setup-ssh doctor.")
56
+ units = run(
57
+ [
58
+ "systemctl",
59
+ "list-unit-files",
60
+ "--type=service",
61
+ "--no-legend",
62
+ "--no-pager",
63
+ "sshd.service",
64
+ "ssh.service",
65
+ ],
66
+ capture=True,
67
+ )
68
+ available = {line.split()[0] for line in units.stdout.splitlines() if line.strip()}
69
+ unit = next((name for name in ("sshd.service", "ssh.service") if name in available), None)
70
+ if unit is None:
71
+ raise SetupError("OpenSSH server service was not found. See setup-ssh doctor.")
72
+
73
+ status = ["sudo", "ufw", "status"]
74
+ if peers and not shutil.which("ufw"):
75
+ raise SetupError("UFW was not found. See setup-ssh doctor to configure the local firewall.")
76
+
77
+ rules = [
78
+ ["sudo", "ufw", "allow", "from", peer, "to", "any", "port", str(port), "proto", "tcp"]
79
+ for peer in peers
80
+ ]
81
+ commands = [
82
+ ["sudo", "ssh-keygen", "-A"],
83
+ ["sudo", "systemctl", "enable", "--now", unit],
84
+ *rules,
85
+ ]
86
+ print("Local SSH setup will run:")
87
+ for command in ([status] if rules else []) + commands:
88
+ print(f" {shlex.join(command)}")
89
+ if not rules:
90
+ print("Supply --allow-from for each peer to add UFW rules.")
91
+ if dry_run:
92
+ return
93
+ if not confirm("Apply these local changes?"):
94
+ return
95
+
96
+ if rules:
97
+ result = run(status, capture=True)
98
+ if "Status: active" not in result.stdout.splitlines():
99
+ raise SetupError(
100
+ "UFW must be active before adding rules. Review its configuration first."
101
+ )
102
+ for command in commands:
103
+ run(command)
104
+ print("Local setup applied. Continue enrollment from the computer managing the group.")
setup_ssh/render.py CHANGED
@@ -81,7 +81,9 @@ def script(
81
81
  destination: Device | None = None,
82
82
  timeout: int = 10,
83
83
  ) -> str:
84
- if action not in {"prepare", "apply", "remove", "check"}:
84
+ if action == "check-alias" and destination is None:
85
+ raise ValueError("Alias checks require a destination.")
86
+ if action not in {"prepare", "apply", "remove", "check", "check-alias"}:
85
87
  raise ValueError(f"Unknown action: {action}")
86
88
  payload = {
87
89
  "group": inventory.group_id,
@@ -93,6 +95,8 @@ def script(
93
95
  "known_hosts": known_hosts(inventory) if action == "apply" else "",
94
96
  "authorized_keys": authorized_keys(inventory, device) if action == "apply" else "",
95
97
  }
98
+ if action == "check-alias" and destination is not None:
99
+ payload["destination_pin"] = host_alias(inventory, destination)
96
100
  if device.platform == "windows":
97
101
  encoded = base64.b64encode(json.dumps(payload).encode()).decode()
98
102
  template = files("setup_ssh").joinpath("templates/windows.ps1").read_text("utf-8")
setup_ssh/state.py CHANGED
@@ -98,8 +98,16 @@ class Inventory:
98
98
  devices: list[Device] = field(default_factory=list)
99
99
  version: int = 1
100
100
 
101
+ @property
102
+ def read_only(self) -> bool:
103
+ return self.version == 2
104
+
101
105
  def validate(self) -> None:
102
- if self.version != 1 or not re.fullmatch(r"[0-9a-f]{12}", self.group_id):
106
+ if (
107
+ type(self.version) is not int
108
+ or self.version not in {1, 2}
109
+ or not re.fullmatch(r"[0-9a-f]{12}", self.group_id)
110
+ ):
103
111
  raise SetupError("Unsupported or malformed inventory.")
104
112
  names: set[str] = set()
105
113
  ids: set[str] = set()
@@ -145,7 +153,7 @@ class Inventory:
145
153
  except (OSError, ValueError, KeyError, TypeError, AttributeError) as exc:
146
154
  raise SetupError(f"Cannot read inventory {path}: {exc}") from exc
147
155
 
148
- def save(self, path: Path) -> None:
156
+ def save(self, path: Path, *, overwrite: bool = True) -> None:
149
157
  self.validate()
150
158
  path.parent.mkdir(parents=True, exist_ok=True)
151
159
  fd, temp = tempfile.mkstemp(prefix=".inventory-", dir=path.parent)
@@ -153,7 +161,10 @@ class Inventory:
153
161
  with os.fdopen(fd, "w", encoding="utf-8") as stream:
154
162
  json.dump(asdict(self), stream, indent=2)
155
163
  stream.write("\n")
156
- os.replace(temp, path)
164
+ if overwrite:
165
+ os.replace(temp, path)
166
+ else:
167
+ os.link(temp, path)
157
168
  finally:
158
169
  if os.path.exists(temp):
159
170
  os.unlink(temp)
setup_ssh/status.py ADDED
@@ -0,0 +1,66 @@
1
+ """Read-only checks from each enrolled SSH account."""
2
+
3
+ import socket
4
+ from collections.abc import Iterator
5
+ from copy import deepcopy
6
+ from dataclasses import dataclass
7
+ from datetime import datetime
8
+
9
+ from .fleet import Fleet
10
+ from .state import Inventory, SetupError
11
+ from .transport import Connector, DeviceUnavailableError
12
+
13
+
14
+ @dataclass(frozen=True)
15
+ class Observation:
16
+ source: str
17
+ status: str
18
+ detail: str
19
+ at: datetime
20
+ destination: str | None = None
21
+
22
+
23
+ def inspect(inventory: Inventory, timeout: int) -> Iterator[Observation]:
24
+ snapshot = deepcopy(inventory)
25
+ connector = Connector(
26
+ snapshot, timeout=timeout, batch=True, confirm=lambda _: False, save=lambda: None
27
+ )
28
+ fleet = Fleet(snapshot, None, connector)
29
+ for source in snapshot.devices:
30
+ destinations = [device for device in snapshot.devices if device.id != source.id]
31
+ session = None
32
+ if not (source.host_key and source.public_key):
33
+ try:
34
+ with socket.create_connection((source.host, source.port), timeout=timeout):
35
+ status, detail = (
36
+ "Setup pending",
37
+ "SSH port reachable. Run sync to finish setup.",
38
+ )
39
+ except OSError as exc:
40
+ status, detail = "Unreachable", str(exc)
41
+ else:
42
+ try:
43
+ session = connector.open(source)
44
+ status, detail = "Ready", "Source available for checks."
45
+ except DeviceUnavailableError as exc:
46
+ status, detail = "Unreachable", str(exc)
47
+ except SetupError as exc:
48
+ status, detail = "Blocked", str(exc)
49
+ try:
50
+ yield Observation(source.id, status, detail, datetime.now().astimezone())
51
+ for destination in destinations:
52
+ if session is None:
53
+ state, reason = "Untested", f"Source {source.name}: {detail}"
54
+ elif not (destination.public_key and destination.host_key):
55
+ state, reason = "Setup pending", f"{destination.name} needs sync."
56
+ else:
57
+ check = fleet.check_direction(session, source, destination, normal_alias=True)
58
+ state, reason = (
59
+ ("OK", "SSH alias works.") if check.ok else ("Failed", check.detail)
60
+ )
61
+ yield Observation(
62
+ source.id, state, reason, datetime.now().astimezone(), destination.id
63
+ )
64
+ finally:
65
+ if session is not None:
66
+ session.close()
@@ -98,9 +98,20 @@ case "$ACTION" in
98
98
  managed "$SSH_DIR/config" '' prepend
99
99
  fi
100
100
  ;;
101
- check)
101
+ check|check-alias)
102
102
  [ -f "$GROUP_DIR/config" ] || fail "No managed SSH configuration. Run sync first."
103
- exec ssh -F "$GROUP_DIR/config" \
103
+ set --
104
+ if [ "$ACTION" = check ]; then
105
+ set -- -F "$GROUP_DIR/config"
106
+ else
107
+ effective=$(ssh -G -T "$DESTINATION") || fail "Cannot resolve SSH alias $DESTINATION."
108
+ pin=$(printf '%s\n' "$effective" | awk '$1 == "hostkeyalias" { print $2; exit }')
109
+ [ "$pin" = "$DESTINATION_PIN" ] ||
110
+ fail "SSH alias $DESTINATION does not select this fleet's host key. Check ~/.ssh/config and run sync."
111
+ set -- -T -o StrictHostKeyChecking=yes -o UpdateHostKeys=no \
112
+ -o ClearAllForwardings=yes -o ForwardAgent=no -o ControlPath=none
113
+ fi
114
+ exec ssh "$@" \
104
115
  -o BatchMode=yes -o PasswordAuthentication=no -o KbdInteractiveAuthentication=no \
105
116
  -o PreferredAuthentications=publickey -o IdentityAgent=none \
106
117
  -o ConnectionAttempts=1 -o "ConnectTimeout=$TIMEOUT" \
@@ -104,10 +104,20 @@ function Authorized-Path {
104
104
  }
105
105
 
106
106
  try {
107
- if ($p.action -eq 'check') {
107
+ if ($p.action -in 'check', 'check-alias') {
108
108
  $configPath = Join-Path $groupDir 'config'
109
109
  if (-not (Test-Path -LiteralPath $configPath)) { throw 'No managed configuration. Run sync.' }
110
- & ssh.exe '-F' $configPath '-o' 'BatchMode=yes' '-o' 'PasswordAuthentication=no' `
110
+ $checkOptions = @('-F', $configPath)
111
+ if ($p.action -eq 'check-alias') {
112
+ $effective = & ssh.exe '-G' '-T' $p.destination
113
+ if ($LASTEXITCODE -ne 0) { throw "Cannot resolve SSH alias $($p.destination)." }
114
+ if ($effective -cnotcontains ('hostkeyalias ' + $p.destination_pin)) {
115
+ throw "SSH alias $($p.destination) does not select this fleet's host key. Check ~/.ssh/config and run sync."
116
+ }
117
+ $checkOptions = @('-T', '-o', 'StrictHostKeyChecking=yes', '-o', 'UpdateHostKeys=no',
118
+ '-o', 'ClearAllForwardings=yes', '-o', 'ForwardAgent=no', '-o', 'ControlPath=none')
119
+ }
120
+ & ssh.exe @checkOptions '-o' 'BatchMode=yes' '-o' 'PasswordAuthentication=no' `
111
121
  '-o' 'KbdInteractiveAuthentication=no' '-o' 'PreferredAuthentications=publickey' `
112
122
  '-o' 'IdentityAgent=none' '-o' 'ConnectionAttempts=1' `
113
123
  '-o' ('ConnectTimeout=' + $p.timeout) $p.destination 'echo setup-ssh-ok'
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: setup-ssh-cli
3
- Version: 0.1.0
3
+ Version: 0.2.0
4
4
  Summary: Set up passwordless SSH between your Linux, Windows, and macOS devices.
5
5
  Author: beepboopbit
6
6
  License-Expression: MIT
@@ -20,8 +20,14 @@ Requires-Python: >=3.11
20
20
  Description-Content-Type: text/markdown
21
21
  License-File: LICENSE
22
22
  Requires-Dist: paramiko<5,>=3.4
23
+ Provides-Extra: dashboard
24
+ Requires-Dist: textual>=1; extra == "dashboard"
23
25
  Dynamic: license-file
24
26
 
27
+ <p align="center">
28
+ <img src="assets/icon.png" alt="setup-ssh icon" width="160" height="160">
29
+ </p>
30
+
25
31
  # setup-ssh
26
32
 
27
33
  I made this because my lazy ass got tired of setting up SSH keys and remembering
@@ -75,7 +81,18 @@ key, and you don't need to run setup again just to SSH into something.
75
81
 
76
82
  ## Add another computer
77
83
 
78
- Enable SSH on it, then run these from your original setup computer:
84
+ On a Linux target with systemd and UFW, run the guided preparation locally as
85
+ your normal user. Repeat `--allow-from` for each trusted peer source IP.
86
+
87
+ ```sh
88
+ setup-ssh prepare-local --allow-from 10.10.0.20 --allow-from 10.10.0.23
89
+ ```
90
+
91
+ The command previews the changes and asks before using sudo to generate missing
92
+ host keys, enable OpenSSH, and add the specified UFW rules. Use `--dry-run` to
93
+ preview without invoking sudo. For other platforms and firewalls, see
94
+ `setup-ssh doctor`. Once SSH is reachable, run these from your original setup
95
+ computer:
79
96
 
80
97
  ```sh
81
98
  setup-ssh add --no-sync
@@ -90,6 +107,7 @@ does both steps for you.
90
107
 
91
108
  ```sh
92
109
  setup-ssh list # saved devices
110
+ setup-ssh dashboard # live device and connection status (optional extra)
93
111
  setup-ssh sync --skip-offline # update the ones that are online
94
112
  setup-ssh --batch sync --skip-offline # same, with no password/trust prompts
95
113
  setup-ssh check # test every direction; all devices online
@@ -98,6 +116,8 @@ setup-ssh doctor --os windows # SSH setup instructions for an OS
98
116
  setup-ssh --help
99
117
  ```
100
118
 
119
+ [Install the dashboard and copy an inventory to another enrolled device](docs/usage.md#dashboard-and-portable-inventory).
120
+
101
121
  Removing a device needs to reach the other computers to revoke its access there.
102
122
  If some are offline, sync them later.
103
123
 
@@ -0,0 +1,18 @@
1
+ setup_ssh/__init__.py,sha256=EJ5DIgLKA9mMv4aVMANi-RILzNj52ZIkOzea65E1trY,82
2
+ setup_ssh/__main__.py,sha256=k1ocEWawweo1qCJWNFAAvyxz3tcY13dzvCenHszij30,48
3
+ setup_ssh/cli.py,sha256=D29fR6sG5KcovBwdUtwDgm1ngY1RWtUIduJ0ui9_MBg,13769
4
+ setup_ssh/dashboard.py,sha256=5XZzpFpGSJU6QeNCGpFuXjYkXetWy4eg2LJ9WpNmAhc,7046
5
+ setup_ssh/fleet.py,sha256=zjlszw8O-dHOvFfXkTOwc-OtcGhIQVV5JJaRlzcx3wE,10289
6
+ setup_ssh/local_setup.py,sha256=xBOaJa3MMbpd9MLnislDmeH-kJm-_-9jrDJ2Wrv5-FQ,3614
7
+ setup_ssh/render.py,sha256=cLrt8UcdO782KR6iPIETpBzyYndvO98A_MV8TLVFNwE,4349
8
+ setup_ssh/state.py,sha256=2I2A-ok4h9QNeSN2B8QdyPQhb55rWsvD7OvQLDTNL9U,6513
9
+ setup_ssh/status.py,sha256=_8w5CwOs6qcmtCO3qudQuSmNpbvLIwAwYE6tHjDBdEU,2603
10
+ setup_ssh/transport.py,sha256=EsASN0ax6cvxI4_oZz12G1MBrdiOP1nTInGYUAxNiNY,17109
11
+ setup_ssh/templates/posix.sh,sha256=fOsjl4zMf2uMt9TUog43hXvM6b2m5mLqgc7WLPn2eAA,5123
12
+ setup_ssh/templates/windows.ps1,sha256=CQePxBIY8HSKXcf8m7NyFf01SHimFgkDzSeufaR5ai0,9204
13
+ setup_ssh_cli-0.2.0.dist-info/licenses/LICENSE,sha256=ufSQzZ_p35UUknKgkk3_KbyBl15LuKgWc32RrK9_71k,1068
14
+ setup_ssh_cli-0.2.0.dist-info/METADATA,sha256=mooyhcY61yAfAVnhDlItIdfFa0XcJFb_1pgTat3wyP0,5456
15
+ setup_ssh_cli-0.2.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
16
+ setup_ssh_cli-0.2.0.dist-info/entry_points.txt,sha256=9lppZSEWwEv7WT5My3fqX4ctHWfs3TFwKIMgucSE4mU,49
17
+ setup_ssh_cli-0.2.0.dist-info/top_level.txt,sha256=QQVqA-jgb6Nk5XQ_OHmqqMc47MLh0p2kFfdmp_3QHBA,10
18
+ setup_ssh_cli-0.2.0.dist-info/RECORD,,
@@ -1,5 +1,5 @@
1
1
  Wheel-Version: 1.0
2
- Generator: setuptools (84.2.0)
2
+ Generator: setuptools (84.2.1)
3
3
  Root-Is-Purelib: true
4
4
  Tag: py3-none-any
5
5
 
@@ -1,15 +0,0 @@
1
- setup_ssh/__init__.py,sha256=mwTZzwsPpqcmV4g4W5MgAAc1-7oh7IW6HygE1oVPsYU,82
2
- setup_ssh/__main__.py,sha256=k1ocEWawweo1qCJWNFAAvyxz3tcY13dzvCenHszij30,48
3
- setup_ssh/cli.py,sha256=m7fonz-6uYOse3m96Qo-RaQFt6lTtEuf-te10Y-d0Co,9579
4
- setup_ssh/fleet.py,sha256=n1nk5-03jFdVF7NtVluP3VIPCqbOcPYwaGACFBqohx4,9833
5
- setup_ssh/render.py,sha256=rS5tTa4mO16ye5Sn-ZiK_LSeKpAX7hLgTzBg_1-bkGU,4082
6
- setup_ssh/state.py,sha256=T2q8AmA22W0fXo4u0xk-bPUTcpbPcIf-cYMcrBh5LL4,6231
7
- setup_ssh/transport.py,sha256=EsASN0ax6cvxI4_oZz12G1MBrdiOP1nTInGYUAxNiNY,17109
8
- setup_ssh/templates/posix.sh,sha256=9B9p4aUMAmOwVF7FrFKnjCIhajc27hOlWDrS5-lHLSk,4494
9
- setup_ssh/templates/windows.ps1,sha256=EYlfVhHmy8vFT7ccpsnZnI6n8YiABr7dPkMahi7fbGs,8521
10
- setup_ssh_cli-0.1.0.dist-info/licenses/LICENSE,sha256=ufSQzZ_p35UUknKgkk3_KbyBl15LuKgWc32RrK9_71k,1068
11
- setup_ssh_cli-0.1.0.dist-info/METADATA,sha256=sB6pbb1xEnSeOKlusKkA0A_fb4TQ9MKAz9-q6WyYR5k,4584
12
- setup_ssh_cli-0.1.0.dist-info/WHEEL,sha256=a-udL2m4V_6Yn8b-uKzWb12RjRxwwMo6ohYFM24tpaY,91
13
- setup_ssh_cli-0.1.0.dist-info/entry_points.txt,sha256=9lppZSEWwEv7WT5My3fqX4ctHWfs3TFwKIMgucSE4mU,49
14
- setup_ssh_cli-0.1.0.dist-info/top_level.txt,sha256=QQVqA-jgb6Nk5XQ_OHmqqMc47MLh0p2kFfdmp_3QHBA,10
15
- setup_ssh_cli-0.1.0.dist-info/RECORD,,