setup-ssh-cli 0.1.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 ADDED
@@ -0,0 +1,3 @@
1
+ """Manage a small, cross-platform group of SSH devices."""
2
+
3
+ __version__ = "0.1.0"
setup_ssh/__main__.py ADDED
@@ -0,0 +1,3 @@
1
+ from .cli import main
2
+
3
+ raise SystemExit(main())
setup_ssh/cli.py ADDED
@@ -0,0 +1,216 @@
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import getpass
5
+ import socket
6
+ import sys
7
+ from pathlib import Path
8
+
9
+ import paramiko
10
+
11
+ from . import __version__
12
+ from .fleet import Check, Fleet
13
+ from .state import Device, Inventory, SetupError, default_path
14
+ from .transport import (
15
+ Connector,
16
+ current_account_matches,
17
+ diagnostics,
18
+ doctor_instructions,
19
+ local_platform,
20
+ )
21
+
22
+
23
+ def confirm(message: str, default: bool = False) -> bool:
24
+ suffix = " [Y/n]: " if default else " [y/N]: "
25
+ answer = input(message + suffix).strip().lower()
26
+ return default if not answer else answer in {"yes", "y"}
27
+
28
+
29
+ def prompt(label: str, default: str = "") -> str:
30
+ value = input(label + (f" [{default}]" if default else "") + ": ").strip()
31
+ return value or default
32
+
33
+
34
+ def ask_device(inventory: Inventory, *, local: bool = False, args=None) -> Device:
35
+ def value(name: str, label: str, default: str = "") -> str:
36
+ supplied = getattr(args, name, None)
37
+ return str(supplied) if supplied is not None else prompt(label, default)
38
+
39
+ platform_name = (
40
+ local_platform() if local else value("os", "OS (auto/linux/macos/windows)", "auto")
41
+ )
42
+ device = Device(
43
+ name=value("name", "Device name", socket.gethostname().split(".")[0] if local else ""),
44
+ host=value("host", "Address reachable by every device (LAN or NetBird IP/hostname)"),
45
+ user=value("user", "Username", getpass.getuser() if local else ""),
46
+ port=int(value("port", "SSH port", "22")),
47
+ platform=platform_name,
48
+ local=local,
49
+ )
50
+ if local and not current_account_matches(device.user):
51
+ raise SetupError("Use the current account for this computer.")
52
+ inventory.add(device)
53
+ return device
54
+
55
+
56
+ def make_parser() -> argparse.ArgumentParser:
57
+ parser = argparse.ArgumentParser(
58
+ prog="setup-ssh",
59
+ description="Set up SSH between Linux, Windows, and macOS devices over LAN or NetBird.",
60
+ )
61
+ parser.add_argument("--version", action="version", version=__version__)
62
+ parser.add_argument("--config", type=Path, default=default_path(), help="Inventory JSON path")
63
+ parser.add_argument(
64
+ "--timeout", type=int, default=10, help="Connection timeout in seconds (default: 10)"
65
+ )
66
+ parser.add_argument("--batch", action="store_true", help="No password or host-trust prompts")
67
+ commands = parser.add_subparsers(dest="command", required=True)
68
+ commands.add_parser("init", help="Guided enrollment and setup for a new group")
69
+ add = commands.add_parser("add", help="Enroll a device, then synchronize the group")
70
+ add.add_argument("--name")
71
+ add.add_argument("--host", help="LAN or NetBird address")
72
+ add.add_argument("--user")
73
+ add.add_argument("--port", type=int)
74
+ add.add_argument("--os", choices=["auto", "linux", "macos", "windows"])
75
+ add.add_argument("--local", action="store_true", help="This is the current computer/account")
76
+ add.add_argument("--no-sync", action="store_true", help="Save the device and set up later")
77
+ sync = commands.add_parser("sync", help="Reconcile keys and aliases, then test every direction")
78
+ sync.add_argument(
79
+ "--skip-offline",
80
+ action="store_true",
81
+ help="Update and check reachable devices; keep offline devices enrolled for later",
82
+ )
83
+ sync.add_argument("--no-check", action="store_true", help="Skip connection tests")
84
+ sync.add_argument(
85
+ "--dry-run", action="store_true", help="Show the saved plan without connecting"
86
+ )
87
+ commands.add_parser("check", help="Test all connection directions without editing SSH files")
88
+ commands.add_parser("list", help="List enrolled devices")
89
+ commands.add_parser("plan", help="Show the saved plan without connecting or modifying files")
90
+ remove = commands.add_parser("remove", help="Remove a device and revoke its key on peers")
91
+ remove.add_argument("name")
92
+ doctor = commands.add_parser(
93
+ "doctor", help="Show prerequisites and SSH server setup instructions"
94
+ )
95
+ doctor.add_argument("--os", choices=["linux", "macos", "windows"])
96
+ return parser
97
+
98
+
99
+ def show_plan(inventory: Inventory) -> None:
100
+ print("All-to-all SSH access for these accounts:")
101
+ for device in inventory.devices:
102
+ kind = "this computer" if device.local else device.platform
103
+ print(f" {device.name:16} {device.user}@{device.host}:{device.port} ({kind})")
104
+ count = len(inventory.devices)
105
+ print(f"{count} devices; {count * (count - 1)} connection directions.")
106
+ print(f"Dedicated key per device: ~/.ssh/setup-ssh/{inventory.group_id}/id_ed25519")
107
+ print("New keys have no passphrase, allowing unattended SSH. Private keys stay on each device.")
108
+ print("Sync merges managed entries, preserves unrelated entries, and tests each direction.")
109
+
110
+
111
+ def report(checks: list[Check]) -> int:
112
+ failures = sum(not check.ok for check in checks)
113
+ if checks:
114
+ print(f"\n{len(checks) - failures}/{len(checks)} SSH connections passed.")
115
+ return 1 if failures else 0
116
+
117
+
118
+ def main(argv: list[str] | None = None) -> int:
119
+ parser = make_parser()
120
+ args = parser.parse_args(argv)
121
+ if not 1 <= args.timeout <= 300:
122
+ parser.error("--timeout must be between 1 and 300 seconds")
123
+ try:
124
+ if args.command == "doctor":
125
+ print("\n".join(diagnostics()))
126
+ print("\n" + doctor_instructions(args.os or local_platform()))
127
+ print(
128
+ "\nNetBird: peers must be connected, and access policies must allow your SSH TCP "
129
+ "port in both directions. This tool uses the OS OpenSSH server over NetBird. "
130
+ "NetBird's built-in SSH server uses a separate authentication flow."
131
+ )
132
+ return 0
133
+ path = args.config.expanduser().absolute()
134
+ inventory = Inventory.load(path)
135
+ if args.command == "list":
136
+ if not inventory.devices:
137
+ print("No devices yet. Run setup-ssh init.")
138
+ else:
139
+ for device in inventory.devices:
140
+ state = "key collected" if device.public_key else "not set up"
141
+ print(
142
+ f"{device.name:16} {device.user}@{device.host}:{device.port} "
143
+ f"{device.platform:8} {state}"
144
+ + (" (this computer)" if device.local else "")
145
+ )
146
+ print(f"Inventory: {path}")
147
+ return 0
148
+ if args.command == "plan" or (args.command == "sync" and args.dry_run):
149
+ show_plan(inventory)
150
+ return 0
151
+ connector = Connector(
152
+ inventory,
153
+ timeout=args.timeout,
154
+ batch=args.batch,
155
+ confirm=confirm,
156
+ save=lambda: inventory.save(path),
157
+ )
158
+ fleet = Fleet(inventory, path, connector)
159
+ if args.command == "init":
160
+ if args.batch:
161
+ raise SetupError(
162
+ "init is interactive. Use add with explicit options and --no-sync for batch enrollment."
163
+ )
164
+ if inventory.devices:
165
+ raise SetupError("This group already has devices. Use add or sync.")
166
+ print("Use LAN or NetBird addresses that every enrolled device can reach.")
167
+ if confirm("Include this computer?", default=True):
168
+ ask_device(inventory, local=True)
169
+ fleet.save()
170
+ while True:
171
+ print("\nAdd a device:")
172
+ ask_device(inventory)
173
+ fleet.save()
174
+ if not confirm("Add another device?"):
175
+ break
176
+ show_plan(inventory)
177
+ return report(fleet.sync()) if len(inventory.devices) >= 2 else 0
178
+ if args.command == "add":
179
+ if args.batch and not all((args.name, args.host, args.user)):
180
+ raise SetupError("Batch enrollment requires --name, --host, and --user.")
181
+ if args.batch:
182
+ args.os = args.os or "auto"
183
+ args.port = 22 if args.port is None else args.port
184
+ device = ask_device(inventory, local=args.local, args=args)
185
+ fleet.save()
186
+ print(f"Saved {device.name} in {path}.")
187
+ if args.no_sync or len(inventory.devices) < 2:
188
+ print("Run setup-ssh sync when the group is ready.")
189
+ return 0
190
+ show_plan(inventory)
191
+ return report(fleet.sync())
192
+ if args.command == "sync":
193
+ show_plan(inventory)
194
+ checks = fleet.sync(check=not args.no_check, skip_offline=args.skip_offline)
195
+ if args.no_check:
196
+ command = "sync --skip-offline" if args.skip_offline else "check"
197
+ print(f"SSH configuration updated. Run setup-ssh {command} to verify connections.")
198
+ return report(checks)
199
+ if args.command == "check":
200
+ return report(fleet.check())
201
+ if args.command == "remove":
202
+ device = inventory.find(args.name)
203
+ errors = fleet.remove(device)
204
+ for error in errors:
205
+ print(f" {error}", file=sys.stderr)
206
+ return 1 if errors else 0
207
+ except KeyboardInterrupt:
208
+ print("\nStopped. Saved enrollment is retained; rerun sync to resume.", file=sys.stderr)
209
+ return 130
210
+ except EOFError:
211
+ print("Input ended. For unattended runs use --batch.", file=sys.stderr)
212
+ return 1
213
+ except (SetupError, OSError, ValueError, paramiko.SSHException) as exc:
214
+ print(f"Error: {exc}", file=sys.stderr)
215
+ return 1
216
+ return 0
setup_ssh/fleet.py ADDED
@@ -0,0 +1,228 @@
1
+ """Reconcile the group, retaining public state so interrupted runs can resume."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Callable
6
+ from dataclasses import dataclass, replace
7
+ from pathlib import Path
8
+
9
+ import paramiko
10
+
11
+ from .render import script
12
+ from .state import Device, Inventory, SetupError, validate_key
13
+ from .transport import Connector, DeviceUnavailableError, Session
14
+
15
+
16
+ @dataclass
17
+ class Check:
18
+ source: str
19
+ destination: str
20
+ ok: bool
21
+ detail: str = ""
22
+
23
+
24
+ class Fleet:
25
+ def __init__(
26
+ self,
27
+ inventory: Inventory,
28
+ path: Path,
29
+ connector: Connector,
30
+ output: Callable[[str], None] = print,
31
+ ):
32
+ self.inventory = inventory
33
+ self.path = path
34
+ self.connector = connector
35
+ self.output = output
36
+
37
+ def save(self) -> None:
38
+ self.inventory.save(self.path)
39
+
40
+ def connect_all(self, *, skip_offline: bool = False) -> dict[str, Session]:
41
+ sessions = {}
42
+ errors = []
43
+ try:
44
+ for device in sorted(self.inventory.devices, key=lambda item: not item.local):
45
+ self.output(
46
+ f"Connecting to {device.name} ({device.user}@{device.host}:{device.port})…"
47
+ )
48
+ try:
49
+ sessions[device.id] = self.connector.open(device)
50
+ except DeviceUnavailableError as exc:
51
+ if skip_offline:
52
+ self.output(f"Skipping offline {device.name}: {exc}")
53
+ else:
54
+ errors.append(str(exc))
55
+ except SetupError as exc:
56
+ errors.append(str(exc))
57
+ if errors:
58
+ raise SetupError("Cannot reach the complete group:\n " + "\n ".join(errors))
59
+ if not sessions:
60
+ raise SetupError("No devices are reachable; nothing was updated.")
61
+ return sessions
62
+ except BaseException:
63
+ for session in sessions.values():
64
+ session.close()
65
+ raise
66
+
67
+ def sync(self, *, check: bool = True, skip_offline: bool = False) -> list[Check]:
68
+ if not self.inventory.devices:
69
+ raise SetupError("No devices are enrolled. Run setup-ssh init or add first.")
70
+ sessions = self.connect_all(skip_offline=skip_offline)
71
+ try:
72
+ available = [device for device in self.inventory.devices if device.id in sessions]
73
+ # Collect reachable peers' keys before changing anyone's authorization list.
74
+ for device in available:
75
+ self.output(f"Preparing {device.name}'s dedicated key…")
76
+ result = sessions[device.id].run(script(self.inventory, device, "prepare"))
77
+ if result.code:
78
+ raise SetupError(
79
+ f"{device.name}: {result.stderr.strip() or result.stdout.strip()}"
80
+ )
81
+ values = [
82
+ line[14:]
83
+ for line in result.stdout.splitlines()
84
+ if line.startswith("SETUP_SSH_KEY=")
85
+ ]
86
+ if len(values) != 1:
87
+ raise SetupError(f"{device.name}: did not return a public key.")
88
+ public = validate_key(values[0])
89
+ if device.public_key and device.public_key != public:
90
+ raise SetupError(
91
+ f"{device.name}'s managed key changed. Restore its original key, "
92
+ "or remove and re-add the device to replace it."
93
+ )
94
+ device.public_key = public
95
+ self.save()
96
+ # Keep saved keys and aliases for initialized offline peers. An offline
97
+ # peer without keys stays enrolled, but cannot participate until a later sync.
98
+ configured = self.inventory
99
+ if skip_offline:
100
+ configured = replace(
101
+ self.inventory,
102
+ devices=[d for d in self.inventory.devices if d.public_key and d.host_key],
103
+ )
104
+ errors = []
105
+ for device in available:
106
+ self.output(f"Updating keys and SSH aliases on {device.name}…")
107
+ result = sessions[device.id].run(script(configured, device, "apply"))
108
+ if result.code:
109
+ errors.append(
110
+ f"{device.name}: {result.stderr.strip() or result.stdout.strip()}"
111
+ )
112
+ if errors:
113
+ raise SetupError(
114
+ "Some updates failed; successful updates are retained. Fix these and rerun sync:\n "
115
+ + "\n ".join(errors)
116
+ )
117
+ self.save()
118
+ skipped = [
119
+ device.name for device in self.inventory.devices if device.id not in sessions
120
+ ]
121
+ if skipped:
122
+ self.output(
123
+ f"Updated {len(available)}/{len(self.inventory.devices)} devices. "
124
+ f"Still pending: {', '.join(skipped)}. Run sync when they are online. "
125
+ "Connection checks cover only the available devices."
126
+ )
127
+ return self.check_sessions(sessions) if check else []
128
+ finally:
129
+ for session in sessions.values():
130
+ session.close()
131
+
132
+ def check_sessions(self, sessions: dict[str, Session]) -> list[Check]:
133
+ checks = []
134
+ available = [device for device in self.inventory.devices if device.id in sessions]
135
+ for source in available:
136
+ for destination in available:
137
+ if source.id == destination.id:
138
+ 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)
159
+ checks.append(check)
160
+ self.output(f" {source.name} -> {destination.name}: {'OK' if ok else 'FAILED'}")
161
+ if detail:
162
+ self.output(f" {detail}")
163
+ return checks
164
+
165
+ def check(self) -> list[Check]:
166
+ if len(self.inventory.devices) < 2:
167
+ raise SetupError("Add at least two devices first.")
168
+ if any(not device.public_key or not device.host_key for device in self.inventory.devices):
169
+ raise SetupError("The group has not completed setup. Run setup-ssh sync first.")
170
+ sessions = self.connect_all()
171
+ try:
172
+ return self.check_sessions(sessions)
173
+ finally:
174
+ for session in sessions.values():
175
+ session.close()
176
+
177
+ def remove(self, device: Device) -> list[str]:
178
+ # Save revocation intent first: a future sync must never reauthorize this device.
179
+ self.inventory.devices.remove(device)
180
+ self.save()
181
+ if device.public_key is None:
182
+ self.output(f"Removed {device.name}; it had no distributed managed key.")
183
+ return []
184
+ sessions = {}
185
+ errors = []
186
+ try:
187
+ for survivor in self.inventory.devices:
188
+ try:
189
+ sessions[survivor.id] = self.connector.open(survivor)
190
+ except SetupError as exc:
191
+ errors.append(str(exc))
192
+ # Incomplete enrollment never distributed any key if none were collected.
193
+ ready = all(d.public_key and d.host_key for d in self.inventory.devices)
194
+ for survivor in self.inventory.devices:
195
+ session = sessions.get(survivor.id)
196
+ if session is None:
197
+ continue
198
+ if not ready:
199
+ errors.append(f"{survivor.name}: incomplete setup; run sync to reconcile it.")
200
+ continue
201
+ result = session.run(script(self.inventory, survivor, "apply"))
202
+ if result.code:
203
+ errors.append(
204
+ f"{survivor.name}: {result.stderr.strip() or result.stdout.strip()}"
205
+ )
206
+ else:
207
+ self.output(f"Revoked {device.name} on {survivor.name}.")
208
+ try:
209
+ session = self.connector.open(device)
210
+ try:
211
+ result = session.run(script(self.inventory, device, "remove"))
212
+ if result.code:
213
+ self.output(f"Could not clean {device.name}: {result.stderr.strip()}")
214
+ else:
215
+ self.output(f"Removed the group's entries from {device.name}.")
216
+ finally:
217
+ session.close()
218
+ except SetupError as exc:
219
+ self.output(f"Removed device could not be cleaned: {exc}")
220
+ if errors:
221
+ self.output(
222
+ "The device is removed from the inventory. Revocation is incomplete on some "
223
+ "peers; run sync when they are reachable."
224
+ )
225
+ return errors
226
+ finally:
227
+ for session in sessions.values():
228
+ session.close()
setup_ssh/render.py ADDED
@@ -0,0 +1,106 @@
1
+ """Render only public data into OS-native scripts; no remote Python required."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import base64
6
+ import json
7
+ from importlib.resources import files
8
+
9
+ from .state import Device, Inventory, SetupError
10
+
11
+
12
+ def group_path(inventory: Inventory) -> str:
13
+ return f"~/.ssh/setup-ssh/{inventory.group_id}"
14
+
15
+
16
+ def host_alias(inventory: Inventory, device: Device) -> str:
17
+ return f"setup-ssh-{inventory.group_id}-{device.id}"
18
+
19
+
20
+ def quoted(value: str) -> str:
21
+ # OpenSSH double-quoted tokens (including domain\\user on Windows).
22
+ return '"' + value.replace("\\", "\\\\").replace('"', '\\"') + '"'
23
+
24
+
25
+ def ssh_config(inventory: Inventory, source: Device) -> str:
26
+ root = group_path(inventory)
27
+ lines = ["# Generated by setup-ssh; edit the inventory, then run sync."]
28
+ for destination in inventory.devices:
29
+ if source.id == destination.id:
30
+ continue
31
+ algorithm = (destination.host_key or {}).get("type", "ssh-ed25519")
32
+ if algorithm == "ssh-rsa":
33
+ algorithm = "rsa-sha2-512,rsa-sha2-256"
34
+ lines.extend(
35
+ [
36
+ f"Host {destination.name}",
37
+ f" HostName {destination.host.replace('%', '%%')}",
38
+ f" User {quoted(destination.user)}",
39
+ f" Port {destination.port}",
40
+ f" IdentityFile {quoted(root + '/id_ed25519')}",
41
+ " IdentitiesOnly yes",
42
+ " ForwardAgent no",
43
+ " StrictHostKeyChecking yes",
44
+ f" UserKnownHostsFile {quoted(root + '/known_hosts')}",
45
+ f" HostKeyAlias {host_alias(inventory, destination)}",
46
+ f" HostKeyAlgorithms {algorithm}",
47
+ "",
48
+ ]
49
+ )
50
+ lines.append("Host *\n")
51
+ return "\n".join(lines)
52
+
53
+
54
+ def known_hosts(inventory: Inventory) -> str:
55
+ lines = []
56
+ for device in inventory.devices:
57
+ if device.host_key is None:
58
+ raise SetupError(f"{device.name} has no verified SSH host key. Run sync first.")
59
+ lines.append(
60
+ f"{host_alias(inventory, device)} {device.host_key['type']} {device.host_key['data']}"
61
+ )
62
+ return "\n".join(lines) + "\n"
63
+
64
+
65
+ def authorized_keys(inventory: Inventory, source: Device) -> str:
66
+ lines = []
67
+ for device in inventory.devices:
68
+ if device.id == source.id:
69
+ continue
70
+ if device.public_key is None:
71
+ raise SetupError(f"{device.name} has no managed public key. Run sync first.")
72
+ lines.append(f"{device.public_key} setup-ssh:{inventory.group_id}:{device.id}")
73
+ return "\n".join(lines) + ("\n" if lines else "")
74
+
75
+
76
+ def script(
77
+ inventory: Inventory,
78
+ device: Device,
79
+ action: str,
80
+ *,
81
+ destination: Device | None = None,
82
+ timeout: int = 10,
83
+ ) -> str:
84
+ if action not in {"prepare", "apply", "remove", "check"}:
85
+ raise ValueError(f"Unknown action: {action}")
86
+ payload = {
87
+ "group": inventory.group_id,
88
+ "device": device.id,
89
+ "action": action,
90
+ "timeout": timeout,
91
+ "destination": destination.name if destination else "",
92
+ "config": ssh_config(inventory, device) if action == "apply" else "",
93
+ "known_hosts": known_hosts(inventory) if action == "apply" else "",
94
+ "authorized_keys": authorized_keys(inventory, device) if action == "apply" else "",
95
+ }
96
+ if device.platform == "windows":
97
+ encoded = base64.b64encode(json.dumps(payload).encode()).decode()
98
+ template = files("setup_ssh").joinpath("templates/windows.ps1").read_text("utf-8")
99
+ return template.replace("__PAYLOAD__", encoded)
100
+ # The shell template decodes each value independently; no jq/Python dependency.
101
+ encoded_values = []
102
+ for key, value in payload.items():
103
+ encoded = base64.b64encode(str(value).encode()).decode()
104
+ encoded_values.append(f"{key.upper()}=$(decode '{encoded}')")
105
+ template = files("setup_ssh").joinpath("templates/posix.sh").read_text("utf-8")
106
+ return template.replace("__PAYLOAD__", "\n".join(encoded_values))