ssh-keyup 1.0.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.
ssh_keyup.py ADDED
@@ -0,0 +1,699 @@
1
+ #!/usr/bin/env python3
2
+ # SPDX-License-Identifier: GPL-3.0-or-later
3
+ #
4
+ # ssh-keyup - Passwordless SSH setup for
5
+ # Raspberry Pi, NVIDIA Jetson, or any Linux device
6
+ #
7
+ # Copyright (c) 2026, UAB Kurokesu. All rights reserved.
8
+
9
+ __version__ = "1.0.0"
10
+
11
+ import argparse
12
+ import ipaddress
13
+ import os
14
+ import re
15
+ import shlex
16
+ import subprocess
17
+ import sys
18
+ import tempfile
19
+ from datetime import date
20
+ from pathlib import Path
21
+ from shutil import which
22
+ from typing import Dict, List, Optional, Tuple, Union
23
+
24
+
25
+ class CLI:
26
+ """Styled terminal output and interaction. All UI in one place."""
27
+
28
+ BANNER = r"""
29
+ _ _
30
+ ___ ___| |__ | | _____ _ _ _ _ _ __
31
+ / __/ __| '_ \ _____| |/ / _ \ | | | | | | '_ \
32
+ \__ \__ \ | | |_____| < __/ |_| | |_| | |_) |
33
+ |___/___/_| |_| |_|\_\___|\__, |\__,_| .__/
34
+ |___/ |_|"""
35
+
36
+ WIDTH = 48
37
+ BOLD = "\033[1m"
38
+ DIM = "\033[2m"
39
+ RESET = "\033[0m"
40
+ GREEN = "\033[32m"
41
+ RED = "\033[31m"
42
+ YELLOW = "\033[33m"
43
+ CYAN = "\033[36m"
44
+ HIDE_CUR = "\033[?25l"
45
+ SHOW_CUR = "\033[?25h"
46
+
47
+ S_BANNER = ""
48
+ S_VERSION = CYAN + BOLD
49
+ S_SEPARATOR = DIM
50
+ S_HINT = DIM
51
+ S_SSH_WARNING = YELLOW
52
+ S_SSH_INFO = DIM
53
+ S_SUCCESS = GREEN
54
+ S_STATUS = CYAN
55
+
56
+ def __init__(self) -> None:
57
+ if not sys.stdout.isatty():
58
+ CLI.BOLD = CLI.DIM = CLI.RESET = ""
59
+ CLI.GREEN = CLI.RED = CLI.YELLOW = CLI.CYAN = ""
60
+ CLI.HIDE_CUR = CLI.SHOW_CUR = ""
61
+ CLI.S_BANNER = CLI.S_VERSION = CLI.S_SEPARATOR = ""
62
+ CLI.S_HINT = CLI.S_SSH_WARNING = ""
63
+ CLI.S_SSH_INFO = CLI.S_SUCCESS = CLI.S_STATUS = ""
64
+
65
+ @staticmethod
66
+ def enable_ansi() -> None:
67
+ """Enable ANSI escape sequences on Windows 10+."""
68
+ if sys.platform != "win32":
69
+ return
70
+ try:
71
+ import ctypes
72
+ k = ctypes.windll.kernel32 # type: ignore[attr-defined]
73
+ h = k.GetStdHandle(-11)
74
+ m = ctypes.c_ulong()
75
+ k.GetConsoleMode(h, ctypes.byref(m))
76
+ k.SetConsoleMode(h, m.value | 0x0004)
77
+ except Exception:
78
+ pass
79
+
80
+ @staticmethod
81
+ def banner() -> None:
82
+ """Print the ASCII banner and version."""
83
+ print(f"{CLI.S_BANNER}{CLI.BANNER}{CLI.RESET}")
84
+ ver = ("v" + __version__).rjust(CLI.WIDTH)
85
+ print(f"{CLI.S_VERSION}{ver}{CLI.RESET}")
86
+
87
+ @staticmethod
88
+ def separator() -> None:
89
+ """Print a horizontal separator line."""
90
+ print(f"\n{CLI.S_SEPARATOR}{'-' * CLI.WIDTH}{CLI.RESET}\n")
91
+
92
+ @staticmethod
93
+ def hint(msg: str) -> None:
94
+ """Print a hint/informational message."""
95
+ print(f"{CLI.S_HINT}{msg}{CLI.RESET}")
96
+
97
+ @staticmethod
98
+ def warn(msg: str) -> None:
99
+ """Print a warning message, pip-style."""
100
+ print(f"{CLI.YELLOW}Warning:{CLI.RESET} {msg}")
101
+
102
+ @staticmethod
103
+ def fail(msg: str) -> None:
104
+ """Print an error message, pip-style."""
105
+ nl = "\n" if msg.startswith("\n") else ""
106
+ print(f"{nl}{CLI.RED}Error:{CLI.RESET} {msg.lstrip()}")
107
+
108
+ @staticmethod
109
+ def fatal(msg: str) -> None:
110
+ """Print an error message and exit."""
111
+ cli.fail(msg)
112
+ sys.exit(1)
113
+
114
+ @staticmethod
115
+ def success(msg: str) -> None:
116
+ """Print a success message."""
117
+ print(f"{CLI.S_SUCCESS}Done!{CLI.RESET} {msg}")
118
+
119
+ @staticmethod
120
+ def status(msg: str) -> None:
121
+ """Print a status/progress message."""
122
+ print(f"{CLI.S_STATUS}{msg}{CLI.RESET}")
123
+
124
+ @staticmethod
125
+ def cancel(msg: str = "") -> None:
126
+ """Print a cancellation message."""
127
+ print(f"{CLI.YELLOW}Cancelled.{CLI.RESET}", end="")
128
+ if msg:
129
+ print(f" {msg}")
130
+ else:
131
+ print()
132
+
133
+ @staticmethod
134
+ def ssh_warning(msg: str) -> None:
135
+ """Print an SSH warning line."""
136
+ print(f"{CLI.S_SSH_WARNING}{msg}{CLI.RESET}")
137
+
138
+ @staticmethod
139
+ def ssh_info(msg: str) -> None:
140
+ """Print an SSH info/detail line."""
141
+ print(f" {CLI.S_SSH_INFO}{msg}{CLI.RESET}")
142
+
143
+ @staticmethod
144
+ def prompt(
145
+ label: str, value: Optional[str] = None, *,
146
+ hint: str = "", default: str = "",
147
+ ) -> str:
148
+ """Prompt for input, or display and return a pre-supplied value."""
149
+ if value:
150
+ print(f"{label}: {value}")
151
+ return value
152
+ if default:
153
+ suffix = f" [{CLI.CYAN}{default}{CLI.RESET}]"
154
+ elif hint:
155
+ suffix = f" {CLI.S_HINT}({hint}){CLI.RESET}"
156
+ else:
157
+ suffix = ""
158
+ result = input(f"{label}{suffix}: ").strip()
159
+ return result if result else default
160
+
161
+ @staticmethod
162
+ def msg(msg: str = "") -> None:
163
+ """Print an unstyled message."""
164
+ print(msg)
165
+
166
+ @staticmethod
167
+ def _read_key() -> str:
168
+ """Read a single keypress."""
169
+ if sys.platform == "win32":
170
+ import msvcrt
171
+ ch = msvcrt.getwch()
172
+ if ch == "\x03":
173
+ raise KeyboardInterrupt
174
+ if ch in ("\r", "\n"):
175
+ return "enter"
176
+ if ch in ("\xe0", "\x00"):
177
+ return {"K": "left", "M": "right"}.get(msvcrt.getwch(), "")
178
+ return "esc" if ch == "\x1b" else ch
179
+ else:
180
+ import termios
181
+ import tty
182
+ fd = sys.stdin.fileno()
183
+ old = termios.tcgetattr(fd)
184
+ try:
185
+ tty.setraw(fd)
186
+ ch = sys.stdin.read(1)
187
+ if ch in ("\r", "\n"):
188
+ return "enter"
189
+ if ch == "\x1b":
190
+ if sys.stdin.read(1) == "[":
191
+ return {"D": "left", "C": "right"}.get(
192
+ sys.stdin.read(1), "")
193
+ return "esc"
194
+ if ch == "\x03":
195
+ raise KeyboardInterrupt
196
+ return ch
197
+ finally:
198
+ termios.tcsetattr(fd, termios.TCSADRAIN, old)
199
+
200
+ @staticmethod
201
+ def ask_yn(prompt: str, default: bool = False) -> bool:
202
+ """Interactive yes/no selector with arrow keys."""
203
+ if not sys.stdin.isatty():
204
+ return default
205
+
206
+ sel = 0 if default else 1
207
+
208
+ def _render() -> str:
209
+ yes = (f"{CLI.GREEN}{CLI.BOLD}[ Yes ]{CLI.RESET}" if sel == 0
210
+ else f"{CLI.DIM} Yes {CLI.RESET}")
211
+ no = (f"{CLI.RED}{CLI.BOLD}[ No ]{CLI.RESET}" if sel == 1
212
+ else f"{CLI.DIM} No {CLI.RESET}")
213
+ return f"\r\033[2K{prompt} {yes} {no}"
214
+
215
+ sys.stdout.write(CLI.HIDE_CUR)
216
+ sys.stdout.flush()
217
+ try:
218
+ while True:
219
+ sys.stdout.write(_render())
220
+ sys.stdout.flush()
221
+ key = CLI._read_key()
222
+ if key in ("left", "right", "y", "n"):
223
+ if key == "y":
224
+ sel = 0
225
+ elif key == "n":
226
+ sel = 1
227
+ else:
228
+ sel = 1 - sel
229
+ elif key == "enter":
230
+ sys.stdout.write(_render() + "\n")
231
+ sys.stdout.flush()
232
+ return sel == 0
233
+ elif key == "esc":
234
+ sel = 1
235
+ sys.stdout.write(_render() + "\n")
236
+ sys.stdout.flush()
237
+ return False
238
+ finally:
239
+ sys.stdout.write(CLI.SHOW_CUR)
240
+ sys.stdout.flush()
241
+
242
+
243
+ cli = CLI()
244
+
245
+
246
+ class Runner:
247
+ """Run SSH commands natively or via Git Bash as fallback."""
248
+
249
+ @staticmethod
250
+ def _find_git_bash() -> Optional[str]:
251
+ """Locate Git Bash on Windows for use as an SSH fallback."""
252
+ git = which("git")
253
+ if not git:
254
+ return None
255
+ root = Path(git).resolve().parent.parent
256
+ for name in ("git-bash.exe", "bin/bash.exe"):
257
+ p = root / name
258
+ if p.exists():
259
+ return str(p)
260
+ return None
261
+
262
+ def __init__(self) -> None:
263
+ self.git_bash = Runner._find_git_bash()
264
+ openssh = all(which(c) for c in ("ssh", "ssh-keygen"))
265
+ self.mode = (
266
+ "native" if openssh
267
+ else ("gitbash" if self.git_bash else None)
268
+ ) # type: Optional[str]
269
+
270
+ def check(self) -> None:
271
+ """Exit with guidance if no SSH tools are available."""
272
+ if self.mode:
273
+ return
274
+ if sys.platform == "win32":
275
+ cli.fatal(
276
+ "No SSH tools found. Install OpenSSH Client "
277
+ "(Settings > Optional Features) or Git for Windows")
278
+ else:
279
+ cli.fatal(
280
+ "No SSH tools found. Install with: "
281
+ "sudo apt install openssh-client")
282
+
283
+ def _subprocess_args(
284
+ self, cmd: Union[List[str], str],
285
+ ) -> Tuple[Union[List[str], str], bool]:
286
+ """Prepare the command and shell flag for subprocess.run."""
287
+ if self.mode == "native":
288
+ return cmd, isinstance(cmd, str)
289
+ assert self.git_bash
290
+ sh = (cmd if isinstance(cmd, str)
291
+ else " ".join(shlex.quote(a) for a in cmd))
292
+ return [self.git_bash, "-c", sh], False
293
+
294
+ def run(self, cmd: Union[List[str], str], **kwargs) -> int:
295
+ """Run a command and return the exit code."""
296
+ args, shell = self._subprocess_args(cmd)
297
+ return subprocess.run(args, shell=shell, **kwargs).returncode
298
+
299
+ def run_capture(
300
+ self, cmd: Union[List[str], str], **kwargs,
301
+ ) -> Tuple[int, str]:
302
+ """Run a command, capture stderr, return (rc, text)."""
303
+ args, shell = self._subprocess_args(cmd)
304
+ r = subprocess.run(args, shell=shell, stderr=subprocess.PIPE, **kwargs)
305
+ return r.returncode, (r.stderr or b"").decode(errors="replace")
306
+
307
+
308
+ class SSHConfig:
309
+ """Manage ssh-keyup entries in ~/.ssh/config."""
310
+
311
+ @staticmethod
312
+ def _find_managed_blocks(text: str) -> Dict[str, Tuple[int, int]]:
313
+ """Find ssh-keyup managed blocks in SSH config text."""
314
+ blocks = {} # type: Dict[str, Tuple[int, int]]
315
+ for m in re.finditer(
316
+ r"^#ssh-keyup:begin (\S+)[^\n]*\n.*?^#ssh-keyup:end \1[^\n]*\n?",
317
+ text, re.MULTILINE | re.DOTALL,
318
+ ):
319
+ blocks[m.group(1)] = (m.start(), m.end())
320
+ return blocks
321
+
322
+ @staticmethod
323
+ def _has_unmanaged_host(
324
+ text: str, alias: str, managed_blocks: Dict[str, Tuple[int, int]],
325
+ ) -> bool:
326
+ """Check for a Host entry outside managed markers."""
327
+ for m in re.finditer(r"^Host\s+(\S+)", text, re.MULTILINE):
328
+ if m.group(1) != alias:
329
+ continue
330
+ pos = m.start()
331
+ if not any(s <= pos < e for s, e in managed_blocks.values()):
332
+ return True
333
+ return False
334
+
335
+ @staticmethod
336
+ def _build_block(
337
+ alias: str, host: str, user: str, file_alias: str,
338
+ ) -> str:
339
+ """Build the SSH config block text for a managed host entry."""
340
+ return (
341
+ f"#ssh-keyup:begin {alias} {date.today().isoformat()}\n"
342
+ f"Host {alias}\n"
343
+ f" HostName {host}\n"
344
+ f" User {user}\n"
345
+ f" IdentityFile ~/.ssh/id_ed25519_{file_alias}\n"
346
+ f"#ssh-keyup:end {alias}\n"
347
+ )
348
+
349
+ @staticmethod
350
+ def check_existing(ssh_config: Path, alias: str) -> Tuple[str, bool]:
351
+ """Check for an existing alias, prompt to overwrite."""
352
+ if not ssh_config.exists():
353
+ return "", False
354
+
355
+ text = ssh_config.read_text(encoding="utf-8")
356
+ blocks = SSHConfig._find_managed_blocks(text)
357
+
358
+ has_unmanaged = SSHConfig._has_unmanaged_host(text, alias, blocks)
359
+ has_managed = alias in blocks
360
+
361
+ if has_unmanaged:
362
+ cli.fail(f"Host '{alias}' already exists in SSH config "
363
+ "(not managed by ssh-keyup).")
364
+ cli.msg(f"Use a different alias or remove the existing entry "
365
+ f"from {ssh_config}")
366
+ sys.exit(1)
367
+
368
+ if not has_managed:
369
+ return text, False
370
+
371
+ msg = f"'{alias}' already configured by ssh-keyup. Overwrite?"
372
+ if not cli.ask_yn(msg):
373
+ cli.cancel("No changes were made.")
374
+ sys.exit(0)
375
+
376
+ start, end = blocks[alias]
377
+ before = text[:start].rstrip("\n")
378
+ after = text[end:].lstrip("\n")
379
+ if before and after:
380
+ return before + "\n\n" + after, True
381
+ return before or after, True
382
+
383
+ @staticmethod
384
+ def _atomic_write(ssh_config: Path, text: str) -> None:
385
+ """Write text to SSH config atomically."""
386
+ fd, tmp = tempfile.mkstemp(dir=ssh_config.parent, suffix=".tmp")
387
+ try:
388
+ with os.fdopen(fd, "w", encoding="utf-8", newline="\n") as f:
389
+ f.write(text)
390
+ os.replace(tmp, ssh_config)
391
+ except BaseException:
392
+ os.unlink(tmp)
393
+ raise
394
+
395
+ @staticmethod
396
+ def update(
397
+ ssh_config: Path, alias: str, host: str, user: str,
398
+ file_alias: str, base_text: str,
399
+ ) -> None:
400
+ """Write or replace the SSH config entry."""
401
+ block = SSHConfig._build_block(alias, host, user, file_alias)
402
+ if base_text:
403
+ text = base_text.rstrip("\n") + "\n\n" + block + "\n"
404
+ else:
405
+ text = block + "\n"
406
+ SSHConfig._atomic_write(ssh_config, text)
407
+
408
+ @staticmethod
409
+ def revert(ssh_config: Path, base_text: str) -> None:
410
+ """Restore SSH config to its pre-update state."""
411
+ SSHConfig._atomic_write(ssh_config, base_text)
412
+
413
+
414
+ class Deployer:
415
+ """Deploy an SSH public key to a remote host."""
416
+
417
+ @staticmethod
418
+ def _is_host_key_changed(stderr: str) -> bool:
419
+ """Return True if stderr indicates the remote host key has changed."""
420
+ return "REMOTE HOST IDENTIFICATION HAS CHANGED" in stderr
421
+
422
+ @staticmethod
423
+ def _is_unknown_host(stderr: str) -> bool:
424
+ """Return True if stderr indicates an unknown (first-time) host."""
425
+ return ("Host key verification failed" in stderr
426
+ and "REMOTE HOST IDENTIFICATION HAS CHANGED" not in stderr)
427
+
428
+ @staticmethod
429
+ def _format_host_key_info(host: str, stderr: str) -> Optional[str]:
430
+ """Parse verbose SSH stderr into native-looking host key info."""
431
+ key_m = re.search(r"Server host key: (\S+) (\S+)", stderr)
432
+ if not key_m:
433
+ return None
434
+ key_type = key_m.group(1).replace("ssh-", "").upper()
435
+ fingerprint = key_m.group(2)
436
+ ip_m = re.search(r"Connecting to \S+ \[([^\]]+)\]", stderr)
437
+ addr = f" ({ip_m.group(1)})" if ip_m else ""
438
+ lines = [
439
+ f"The authenticity of host '{host}{addr}' can't be established.",
440
+ f"{key_type} key fingerprint is {fingerprint}.",
441
+ "This key is not known by any other names.",
442
+ ]
443
+ return "\n".join(lines)
444
+
445
+ @staticmethod
446
+ def _handle_unknown_host(host: str, stderr: str) -> bool:
447
+ """Show host key info, return True if user confirms."""
448
+ info = Deployer._format_host_key_info(host, stderr)
449
+ if info:
450
+ for line in info.splitlines():
451
+ cli.ssh_warning(line)
452
+ if not cli.ask_yn("Are you sure you want to continue connecting?"):
453
+ cli.cancel()
454
+ return False
455
+ return True
456
+
457
+ @staticmethod
458
+ def _ssh_cmd(runner: Runner, remote: str, install_cmd: str,
459
+ pub_key: str, accept_new: bool = False) -> Tuple[int, str]:
460
+ """Run the SSH deploy command."""
461
+ policy = "accept-new" if accept_new else "yes"
462
+ cmd = ["ssh"]
463
+ if not accept_new:
464
+ cmd.append("-v")
465
+ cmd.extend(["-o", f"StrictHostKeyChecking={policy}",
466
+ remote, install_cmd])
467
+ return runner.run_capture(cmd, input=pub_key.encode())
468
+
469
+ @staticmethod
470
+ def deploy(runner: Runner, user: str, host: str, pub_path: Path) -> bool:
471
+ """Deploy the public key to the remote host in a single SSH session."""
472
+ remote = f"{user}@{host}"
473
+ pub_key = pub_path.read_text(encoding="utf-8").strip()
474
+ cli.status(f"Deploying key to {user}@{host} ...")
475
+
476
+ install_cmd = (
477
+ "mkdir -p ~/.ssh && chmod 700 ~/.ssh && "
478
+ "key=$(cat) && "
479
+ "if ! grep -qF \"$key\" ~/.ssh/authorized_keys 2>/dev/null; then "
480
+ "printf '%s\\n' \"$key\" >> ~/.ssh/authorized_keys; fi && "
481
+ "chmod 600 ~/.ssh/authorized_keys"
482
+ )
483
+
484
+ rc, stderr = Deployer._ssh_cmd(runner, remote, install_cmd, pub_key)
485
+
486
+ if rc != 0 and Deployer._is_host_key_changed(stderr):
487
+ for line in stderr.strip().splitlines():
488
+ if not line.startswith("debug1:"):
489
+ cli.ssh_warning(line)
490
+ cli.msg()
491
+ if cli.ask_yn("Remove old host key and retry?"):
492
+ cli.status(f"Removing old host key for {host} ...")
493
+ runner.run(["ssh-keygen", "-R", host])
494
+ rc, stderr = Deployer._ssh_cmd(
495
+ runner, remote, install_cmd, pub_key, accept_new=True)
496
+ if rc != 0:
497
+ cli.fail(
498
+ "\nStill can't connect. Check host and credentials."
499
+ )
500
+ return False
501
+ else:
502
+ cli.msg(f"\nAborted. To fix manually:\n ssh-keygen -R {host}")
503
+ return False
504
+ elif rc != 0 and Deployer._is_unknown_host(stderr):
505
+ if not Deployer._handle_unknown_host(host, stderr):
506
+ return False
507
+ rc, stderr = Deployer._ssh_cmd(
508
+ runner, remote, install_cmd, pub_key, accept_new=True)
509
+ if rc != 0:
510
+ cli.fail(
511
+ "\nSSH connection failed. Check host and credentials."
512
+ )
513
+ return False
514
+ elif rc != 0:
515
+ cli.fail(
516
+ "\nSSH connection failed. Check host and credentials."
517
+ )
518
+ if stderr.strip():
519
+ seen = set() # type: set
520
+ for line in stderr.strip().splitlines():
521
+ if line not in seen and not line.startswith("debug1:"):
522
+ seen.add(line)
523
+ cli.ssh_info(line)
524
+ return False
525
+
526
+ return True
527
+
528
+
529
+ def sanitize_alias(name: str, quiet: bool = False) -> str:
530
+ """Replace non-alphanumeric characters (except - and _) with dashes."""
531
+ clean = "".join(
532
+ c if c.isalnum() or c in "-_" else "-"
533
+ for c in name
534
+ ) or "host"
535
+ if not quiet and clean != name:
536
+ cli.hint(f"(sanitized to: {clean})")
537
+ return clean
538
+
539
+
540
+ def is_ip(value: str) -> bool:
541
+ """Return True if the value is a valid IPv4 or IPv6 address."""
542
+ try:
543
+ ipaddress.ip_address(value)
544
+ return True
545
+ except ValueError:
546
+ return False
547
+
548
+
549
+ _DESCRIPTION = (
550
+ "Set up SSH key auth in one command.\n"
551
+ "Generates a per-host Ed25519 key pair, deploys it\n"
552
+ "to the remote host, and adds an entry to ~/.ssh/config."
553
+ )
554
+
555
+ _EPILOG = (
556
+ "examples:\n"
557
+ " ssh-keyup"
558
+ " interactive mode\n"
559
+ " ssh-keyup --host 192.168.1.23 --user pi"
560
+ " with IP address\n"
561
+ " ssh-keyup --host rpi-5 --user trinity"
562
+ " with hostname\n"
563
+ " ssh-keyup --host rpi-5 --user pi --alias mypi"
564
+ " custom alias"
565
+ )
566
+
567
+
568
+ def parse_args() -> argparse.Namespace:
569
+ """Parse command-line arguments."""
570
+ p = argparse.ArgumentParser(
571
+ prog="ssh-keyup",
572
+ description=_DESCRIPTION,
573
+ epilog=_EPILOG,
574
+ formatter_class=argparse.RawDescriptionHelpFormatter,
575
+ )
576
+ p.add_argument("--version", action="version",
577
+ version=f"%(prog)s {__version__}")
578
+ p.add_argument("--host",
579
+ help="IP address or hostname of the remote device")
580
+ p.add_argument("--user",
581
+ help="login username on the remote device")
582
+ p.add_argument("--alias",
583
+ help="friendly name for ~/.ssh/config (default: hostname)")
584
+ return p.parse_args()
585
+
586
+
587
+ def gather_input(args: argparse.Namespace) -> Tuple[str, str, str]:
588
+ """Collect host, username, and alias from args or prompts."""
589
+ host = cli.prompt("Remote host", args.host, hint="IP or name")
590
+ if not host:
591
+ cli.fatal("No host provided.")
592
+
593
+ user = cli.prompt("Username", args.user)
594
+ if not user:
595
+ cli.fatal("No username provided.")
596
+
597
+ if args.alias:
598
+ alias = cli.prompt("Alias", args.alias)
599
+ elif is_ip(host):
600
+ alias = cli.prompt("Alias")
601
+ if not alias:
602
+ cli.fatal("No alias provided.")
603
+ else:
604
+ raw = host[:-6] if host.endswith(".local") else host
605
+ alias = cli.prompt("Alias", default=sanitize_alias(raw, quiet=True))
606
+
607
+ alias = sanitize_alias(alias)
608
+
609
+ return host, user, alias
610
+
611
+
612
+ def generate_key(
613
+ runner: Runner, key_path: Path, pub_path: Path, file_alias: str,
614
+ ) -> None:
615
+ """Generate an Ed25519 key pair."""
616
+ if runner.mode == "native":
617
+ rc = runner.run([
618
+ "ssh-keygen", "-t", "ed25519", "-N", "", "-f", str(key_path),
619
+ ])
620
+ else:
621
+ rc = runner.run(
622
+ f"ssh-keygen -t ed25519 -N '' -f ~/.ssh/id_ed25519_{file_alias}"
623
+ )
624
+
625
+ if rc != 0:
626
+ cli.fatal("ssh-keygen failed.")
627
+
628
+
629
+ def main() -> None:
630
+ """Entry point: gather input, generate keys, deploy, update config."""
631
+ try:
632
+ cli.enable_ansi()
633
+ args = parse_args()
634
+
635
+ cli.banner()
636
+ cli.separator()
637
+
638
+ host, user, alias = gather_input(args)
639
+ file_alias = alias.replace("-", "_")
640
+
641
+ cli.separator()
642
+
643
+ ssh_dir = Path.home() / ".ssh"
644
+ ssh_config = ssh_dir / "config"
645
+ config_base, overwriting = SSHConfig.check_existing(ssh_config, alias)
646
+
647
+ runner = Runner()
648
+ runner.check()
649
+ ssh_dir.mkdir(parents=True, exist_ok=True)
650
+
651
+ key_path = ssh_dir / f"id_ed25519_{file_alias}"
652
+ pub_path = ssh_dir / f"id_ed25519_{file_alias}.pub"
653
+
654
+ key_generated = False
655
+ if pub_path.exists():
656
+ cli.msg(f"Key pair exists {pub_path}")
657
+ if cli.ask_yn("Regenerate key pair?"):
658
+ key_path.unlink(missing_ok=True)
659
+ pub_path.unlink()
660
+ generate_key(runner, key_path, pub_path, file_alias)
661
+ key_generated = True
662
+ else:
663
+ generate_key(runner, key_path, pub_path, file_alias)
664
+ key_generated = True
665
+
666
+ cli.separator()
667
+ if not Deployer.deploy(runner, user, host, pub_path):
668
+ if key_generated:
669
+ cli.status("Cleaning up generated key pair...")
670
+ key_path.unlink(missing_ok=True)
671
+ pub_path.unlink(missing_ok=True)
672
+ if overwriting:
673
+ try:
674
+ SSHConfig.revert(ssh_config, config_base)
675
+ except Exception as ex:
676
+ cli.fail(
677
+ f"SSH config cleanup failed: {ex}"
678
+ )
679
+ sys.exit(1)
680
+
681
+ try:
682
+ SSHConfig.update(ssh_config, alias, host, user, file_alias,
683
+ config_base)
684
+ except Exception as ex:
685
+ cli.fatal(f"Key deployed, but SSH config update failed: {ex}")
686
+ cli.msg(f"Config updated {ssh_config}")
687
+
688
+ cli.separator()
689
+ cli.success(f"SSH key deployed for '{alias}'.\n")
690
+ except KeyboardInterrupt:
691
+ sys.stdout.write(CLI.SHOW_CUR)
692
+ sys.stdout.flush()
693
+ cli.msg()
694
+ cli.cancel()
695
+ sys.exit(130)
696
+
697
+
698
+ if __name__ == "__main__":
699
+ main()