ssh-keyup 1.1.0__tar.gz → 1.1.1__tar.gz

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.
@@ -1,18 +1,23 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: ssh-keyup
3
- Version: 1.1.0
4
- Summary: Passwordless SSH setup for Raspberry Pi, NVIDIA Jetson, or any Linux device
3
+ Version: 1.1.1
4
+ Summary: Passwordless SSH setup and ssh-copy-id alternative for Raspberry Pi, NVIDIA Jetson or any Linux device
5
5
  Home-page: https://github.com/Kurokesu/ssh-keyup
6
6
  Author: UAB Kurokesu
7
7
  License: GPL-3.0-or-later
8
8
  Project-URL: Repository, https://github.com/Kurokesu/ssh-keyup
9
- Keywords: ssh,ssh-keys,ssh-config,ssh-copy-id,passwordless-ssh,raspberry-pi,rpi,jetson,automation,vscode,remote-ssh
10
- Classifier: Development Status :: 4 - Beta
9
+ Project-URL: Issues, https://github.com/Kurokesu/ssh-keyup/issues
10
+ Project-URL: Changelog, https://github.com/Kurokesu/ssh-keyup/releases
11
+ Keywords: ssh,ssh-keys,ssh-config,ssh-copy-id,passwordless-ssh,openssh,ed25519,raspberry-pi,rpi,jetson,iot,automation,vscode,remote-ssh,windows,linux
12
+ Classifier: Development Status :: 5 - Production/Stable
11
13
  Classifier: Environment :: Console
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Intended Audience :: System Administrators
12
16
  Classifier: Operating System :: Microsoft :: Windows
13
17
  Classifier: Operating System :: POSIX :: Linux
14
18
  Classifier: Programming Language :: Python :: 3
15
19
  Classifier: Topic :: System :: Systems Administration
20
+ Classifier: Topic :: Utilities
16
21
  Requires-Python: >=3.8
17
22
  Description-Content-Type: text/markdown
18
23
  License-File: LICENSE
@@ -25,9 +30,11 @@ Dynamic: license-file
25
30
  ![Python](https://img.shields.io/badge/python-3.8%2B-brightgreen)
26
31
  ![Platform](https://img.shields.io/badge/platform-Windows%20%7C%20Linux-blue)
27
32
 
28
- Set up passwordless SSH on Raspberry Pi, NVIDIA Jetson or any Linux device in one command.
33
+ **Set up passwordless SSH on Raspberry Pi, NVIDIA Jetson or any Linux device in one command.**
29
34
 
30
- Tired of juggling `ssh-keygen`, `ssh-copy-id` (missing on Windows) and `~/.ssh/config` edits every time you set up a new device? `ssh-keyup` handles all three in a single interactive session.
35
+ Tired of juggling `ssh-keygen`, `ssh-copy-id` (missing on Windows) and `~/.ssh/config` edits every time you set up a new device?
36
+
37
+ **`ssh-keyup`** handles all three in a single interactive session.
31
38
 
32
39
  ![ssh-keyup demo](https://raw.githubusercontent.com/Kurokesu/ssh-keyup/main/demo.gif)
33
40
 
@@ -41,6 +48,11 @@ pip install ssh-keyup
41
48
  ssh-keyup # ready to use anywhere
42
49
  ```
43
50
 
51
+ > [!TIP]
52
+ > If `ssh-keyup` is missing or runs an old version after install, the new
53
+ > script sits in a folder outside PATH (pip warns about this). Add that folder
54
+ > to PATH or use [pipx](https://pipx.pypa.io/): `pipx install ssh-keyup`.
55
+
44
56
  Or run directly without installing:
45
57
 
46
58
  ```bash
@@ -116,5 +128,5 @@ ssh-keyup
116
128
  - Detects and recovers from **host key mismatches** (common after reflashing)
117
129
  - Handles re-runs gracefully: reuses existing keys or offers regeneration, detects duplicate config entries
118
130
  - Works with any device reachable over SSH: Raspberry Pi, NVIDIA Jetson, Orange Pi, VMs, servers
119
- - **Zero dependencies**, Python 3.8+ standard library only
131
+ - **Zero Python dependencies**, standard library only. Uses system OpenSSH (`ssh`, `ssh-keygen`)
120
132
  - Installs via `pip` or runs as a single script
@@ -5,9 +5,11 @@
5
5
  ![Python](https://img.shields.io/badge/python-3.8%2B-brightgreen)
6
6
  ![Platform](https://img.shields.io/badge/platform-Windows%20%7C%20Linux-blue)
7
7
 
8
- Set up passwordless SSH on Raspberry Pi, NVIDIA Jetson or any Linux device in one command.
8
+ **Set up passwordless SSH on Raspberry Pi, NVIDIA Jetson or any Linux device in one command.**
9
9
 
10
- Tired of juggling `ssh-keygen`, `ssh-copy-id` (missing on Windows) and `~/.ssh/config` edits every time you set up a new device? `ssh-keyup` handles all three in a single interactive session.
10
+ Tired of juggling `ssh-keygen`, `ssh-copy-id` (missing on Windows) and `~/.ssh/config` edits every time you set up a new device?
11
+
12
+ **`ssh-keyup`** handles all three in a single interactive session.
11
13
 
12
14
  ![ssh-keyup demo](https://raw.githubusercontent.com/Kurokesu/ssh-keyup/main/demo.gif)
13
15
 
@@ -21,6 +23,11 @@ pip install ssh-keyup
21
23
  ssh-keyup # ready to use anywhere
22
24
  ```
23
25
 
26
+ > [!TIP]
27
+ > If `ssh-keyup` is missing or runs an old version after install, the new
28
+ > script sits in a folder outside PATH (pip warns about this). Add that folder
29
+ > to PATH or use [pipx](https://pipx.pypa.io/): `pipx install ssh-keyup`.
30
+
24
31
  Or run directly without installing:
25
32
 
26
33
  ```bash
@@ -96,5 +103,5 @@ ssh-keyup
96
103
  - Detects and recovers from **host key mismatches** (common after reflashing)
97
104
  - Handles re-runs gracefully: reuses existing keys or offers regeneration, detects duplicate config entries
98
105
  - Works with any device reachable over SSH: Raspberry Pi, NVIDIA Jetson, Orange Pi, VMs, servers
99
- - **Zero dependencies**, Python 3.8+ standard library only
106
+ - **Zero Python dependencies**, standard library only. Uses system OpenSSH (`ssh`, `ssh-keygen`)
100
107
  - Installs via `pip` or runs as a single script
@@ -5,3 +5,5 @@ build-backend = "setuptools.build_meta"
5
5
  # tool tables are ignored by setuptools, safe next to setup.cfg metadata
6
6
  [tool.ruff]
7
7
  line-length = 79
8
+ # match python_requires, keeps fixes runtime safe on old Pythons
9
+ target-version = "py38"
@@ -1,7 +1,7 @@
1
1
  [metadata]
2
2
  name = ssh-keyup
3
3
  version = attr: ssh_keyup.__version__
4
- description = Passwordless SSH setup for Raspberry Pi, NVIDIA Jetson, or any Linux device
4
+ description = Passwordless SSH setup and ssh-copy-id alternative for Raspberry Pi, NVIDIA Jetson or any Linux device
5
5
  long_description = file: README.md
6
6
  long_description_content_type = text/markdown
7
7
  author = UAB Kurokesu
@@ -10,14 +10,19 @@ license_files = LICENSE
10
10
  url = https://github.com/Kurokesu/ssh-keyup
11
11
  project_urls =
12
12
  Repository = https://github.com/Kurokesu/ssh-keyup
13
- keywords = ssh, ssh-keys, ssh-config, ssh-copy-id, passwordless-ssh, raspberry-pi, rpi, jetson, automation, vscode, remote-ssh
13
+ Issues = https://github.com/Kurokesu/ssh-keyup/issues
14
+ Changelog = https://github.com/Kurokesu/ssh-keyup/releases
15
+ keywords = ssh, ssh-keys, ssh-config, ssh-copy-id, passwordless-ssh, openssh, ed25519, raspberry-pi, rpi, jetson, iot, automation, vscode, remote-ssh, windows, linux
14
16
  classifiers =
15
- Development Status :: 4 - Beta
17
+ Development Status :: 5 - Production/Stable
16
18
  Environment :: Console
19
+ Intended Audience :: Developers
20
+ Intended Audience :: System Administrators
17
21
  Operating System :: Microsoft :: Windows
18
22
  Operating System :: POSIX :: Linux
19
23
  Programming Language :: Python :: 3
20
24
  Topic :: System :: Systems Administration
25
+ Topic :: Utilities
21
26
 
22
27
  [options]
23
28
  py_modules = ssh_keyup
@@ -1,18 +1,23 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: ssh-keyup
3
- Version: 1.1.0
4
- Summary: Passwordless SSH setup for Raspberry Pi, NVIDIA Jetson, or any Linux device
3
+ Version: 1.1.1
4
+ Summary: Passwordless SSH setup and ssh-copy-id alternative for Raspberry Pi, NVIDIA Jetson or any Linux device
5
5
  Home-page: https://github.com/Kurokesu/ssh-keyup
6
6
  Author: UAB Kurokesu
7
7
  License: GPL-3.0-or-later
8
8
  Project-URL: Repository, https://github.com/Kurokesu/ssh-keyup
9
- Keywords: ssh,ssh-keys,ssh-config,ssh-copy-id,passwordless-ssh,raspberry-pi,rpi,jetson,automation,vscode,remote-ssh
10
- Classifier: Development Status :: 4 - Beta
9
+ Project-URL: Issues, https://github.com/Kurokesu/ssh-keyup/issues
10
+ Project-URL: Changelog, https://github.com/Kurokesu/ssh-keyup/releases
11
+ Keywords: ssh,ssh-keys,ssh-config,ssh-copy-id,passwordless-ssh,openssh,ed25519,raspberry-pi,rpi,jetson,iot,automation,vscode,remote-ssh,windows,linux
12
+ Classifier: Development Status :: 5 - Production/Stable
11
13
  Classifier: Environment :: Console
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Intended Audience :: System Administrators
12
16
  Classifier: Operating System :: Microsoft :: Windows
13
17
  Classifier: Operating System :: POSIX :: Linux
14
18
  Classifier: Programming Language :: Python :: 3
15
19
  Classifier: Topic :: System :: Systems Administration
20
+ Classifier: Topic :: Utilities
16
21
  Requires-Python: >=3.8
17
22
  Description-Content-Type: text/markdown
18
23
  License-File: LICENSE
@@ -25,9 +30,11 @@ Dynamic: license-file
25
30
  ![Python](https://img.shields.io/badge/python-3.8%2B-brightgreen)
26
31
  ![Platform](https://img.shields.io/badge/platform-Windows%20%7C%20Linux-blue)
27
32
 
28
- Set up passwordless SSH on Raspberry Pi, NVIDIA Jetson or any Linux device in one command.
33
+ **Set up passwordless SSH on Raspberry Pi, NVIDIA Jetson or any Linux device in one command.**
29
34
 
30
- Tired of juggling `ssh-keygen`, `ssh-copy-id` (missing on Windows) and `~/.ssh/config` edits every time you set up a new device? `ssh-keyup` handles all three in a single interactive session.
35
+ Tired of juggling `ssh-keygen`, `ssh-copy-id` (missing on Windows) and `~/.ssh/config` edits every time you set up a new device?
36
+
37
+ **`ssh-keyup`** handles all three in a single interactive session.
31
38
 
32
39
  ![ssh-keyup demo](https://raw.githubusercontent.com/Kurokesu/ssh-keyup/main/demo.gif)
33
40
 
@@ -41,6 +48,11 @@ pip install ssh-keyup
41
48
  ssh-keyup # ready to use anywhere
42
49
  ```
43
50
 
51
+ > [!TIP]
52
+ > If `ssh-keyup` is missing or runs an old version after install, the new
53
+ > script sits in a folder outside PATH (pip warns about this). Add that folder
54
+ > to PATH or use [pipx](https://pipx.pypa.io/): `pipx install ssh-keyup`.
55
+
44
56
  Or run directly without installing:
45
57
 
46
58
  ```bash
@@ -116,5 +128,5 @@ ssh-keyup
116
128
  - Detects and recovers from **host key mismatches** (common after reflashing)
117
129
  - Handles re-runs gracefully: reuses existing keys or offers regeneration, detects duplicate config entries
118
130
  - Works with any device reachable over SSH: Raspberry Pi, NVIDIA Jetson, Orange Pi, VMs, servers
119
- - **Zero dependencies**, Python 3.8+ standard library only
131
+ - **Zero Python dependencies**, standard library only. Uses system OpenSSH (`ssh`, `ssh-keygen`)
120
132
  - Installs via `pip` or runs as a single script
@@ -6,9 +6,13 @@
6
6
  #
7
7
  # Copyright (c) 2026, UAB Kurokesu. All rights reserved.
8
8
 
9
- __version__ = "1.1.0"
9
+ # Makes modern annotation syntax runtime safe on Python 3.8
10
+ from __future__ import annotations
11
+
12
+ __version__ = "1.1.1"
10
13
 
11
14
  import argparse
15
+ import contextlib
12
16
  import ipaddress
13
17
  import os
14
18
  import re
@@ -16,10 +20,9 @@ import shlex
16
20
  import subprocess
17
21
  import sys
18
22
  import tempfile
19
- from datetime import date
23
+ from datetime import datetime, timezone
20
24
  from pathlib import Path
21
25
  from shutil import which
22
- from typing import Dict, List, Optional, Set, Tuple, Union
23
26
 
24
27
  if sys.platform == "win32":
25
28
  import ctypes
@@ -75,14 +78,13 @@ class CLI:
75
78
  def enable_ansi() -> None:
76
79
  """Enable ANSI escape sequences on Windows 10+."""
77
80
  if sys.platform == "win32":
78
- try:
81
+ # Best effort, colors just stay off if this fails
82
+ with contextlib.suppress(Exception):
79
83
  k = ctypes.windll.kernel32
80
84
  h = k.GetStdHandle(-11)
81
85
  m = ctypes.c_ulong()
82
86
  k.GetConsoleMode(h, ctypes.byref(m))
83
87
  k.SetConsoleMode(h, m.value | 0x0004)
84
- except Exception:
85
- pass
86
88
 
87
89
  @staticmethod
88
90
  def banner() -> None:
@@ -149,7 +151,7 @@ class CLI:
149
151
 
150
152
  @staticmethod
151
153
  def prompt(
152
- label: str, value: Optional[str] = None, *,
154
+ label: str, value: str | None = None, *,
153
155
  hint: str = "", default: str = "",
154
156
  ) -> str:
155
157
  """Prompt for input, or display and return a pre-supplied value."""
@@ -251,7 +253,7 @@ class Runner:
251
253
  """Run SSH commands natively or via Git Bash as fallback."""
252
254
 
253
255
  @staticmethod
254
- def _find_git_bash() -> Optional[str]:
256
+ def _find_git_bash() -> str | None:
255
257
  """Locate Git Bash on Windows for use as an SSH fallback."""
256
258
  git = which("git")
257
259
  if not git:
@@ -266,7 +268,7 @@ class Runner:
266
268
  def __init__(self) -> None:
267
269
  self.git_bash = Runner._find_git_bash()
268
270
  openssh = all(which(c) for c in ("ssh", "ssh-keygen"))
269
- self.mode: Optional[str] = (
271
+ self.mode: str | None = (
270
272
  "native" if openssh
271
273
  else ("gitbash" if self.git_bash else None)
272
274
  )
@@ -285,8 +287,8 @@ class Runner:
285
287
  "sudo apt install openssh-client")
286
288
 
287
289
  def _subprocess_args(
288
- self, cmd: Union[List[str], str],
289
- ) -> Tuple[Union[List[str], str], bool]:
290
+ self, cmd: list[str] | str,
291
+ ) -> tuple[list[str] | str, bool]:
290
292
  """Prepare the command and shell flag for subprocess.run."""
291
293
  if self.mode == "native":
292
294
  return cmd, isinstance(cmd, str)
@@ -296,17 +298,19 @@ class Runner:
296
298
  else " ".join(shlex.quote(a) for a in cmd))
297
299
  return [self.git_bash, "-c", sh], False
298
300
 
299
- def run(self, cmd: Union[List[str], str], **kwargs) -> int:
301
+ def run(self, cmd: list[str] | str, **kwargs) -> int:
300
302
  """Run a command and return the exit code."""
301
303
  args, shell = self._subprocess_args(cmd)
302
- return subprocess.run(args, shell=shell, **kwargs).returncode
304
+ r = subprocess.run(args, shell=shell, check=False, **kwargs)
305
+ return r.returncode
303
306
 
304
307
  def run_capture(
305
- self, cmd: Union[List[str], str], **kwargs,
306
- ) -> Tuple[int, str]:
308
+ self, cmd: list[str] | str, **kwargs,
309
+ ) -> tuple[int, str]:
307
310
  """Run a command, capture stderr, return (rc, text)."""
308
311
  args, shell = self._subprocess_args(cmd)
309
- r = subprocess.run(args, shell=shell, stderr=subprocess.PIPE, **kwargs)
312
+ r = subprocess.run(args, shell=shell, check=False,
313
+ stderr=subprocess.PIPE, **kwargs)
310
314
  return r.returncode, (r.stderr or b"").decode(errors="replace")
311
315
 
312
316
 
@@ -314,9 +318,9 @@ class SSHConfig:
314
318
  """Manage ssh-keyup entries in ~/.ssh/config."""
315
319
 
316
320
  @staticmethod
317
- def _find_managed_blocks(text: str) -> Dict[str, Tuple[int, int]]:
321
+ def _find_managed_blocks(text: str) -> dict[str, tuple[int, int]]:
318
322
  """Find ssh-keyup managed blocks in SSH config text."""
319
- blocks: Dict[str, Tuple[int, int]] = {}
323
+ blocks: dict[str, tuple[int, int]] = {}
320
324
  for m in re.finditer(
321
325
  r"^#ssh-keyup:begin (\S+)[^\n]*\n.*?^#ssh-keyup:end \1[^\n]*\n?",
322
326
  text, re.MULTILINE | re.DOTALL,
@@ -326,7 +330,7 @@ class SSHConfig:
326
330
 
327
331
  @staticmethod
328
332
  def _has_unmanaged_host(
329
- text: str, alias: str, managed_blocks: Dict[str, Tuple[int, int]],
333
+ text: str, alias: str, managed_blocks: dict[str, tuple[int, int]],
330
334
  ) -> bool:
331
335
  """Check for a Host entry outside managed markers."""
332
336
  for m in re.finditer(r"^Host\s+(\S+)", text, re.MULTILINE):
@@ -342,8 +346,9 @@ class SSHConfig:
342
346
  alias: str, host: str, user: str, file_alias: str,
343
347
  ) -> str:
344
348
  """Build the SSH config block text for a managed host entry."""
349
+ stamp = datetime.now(timezone.utc).astimezone().date().isoformat()
345
350
  return (
346
- f"#ssh-keyup:begin {alias} {date.today().isoformat()}\n"
351
+ f"#ssh-keyup:begin {alias} {stamp}\n"
347
352
  f"Host {alias}\n"
348
353
  f" HostName {host}\n"
349
354
  f" User {user}\n"
@@ -352,7 +357,7 @@ class SSHConfig:
352
357
  )
353
358
 
354
359
  @staticmethod
355
- def _splice_out(text: str, span: Tuple[int, int]) -> str:
360
+ def _splice_out(text: str, span: tuple[int, int]) -> str:
356
361
  """Remove a text span, collapsing surrounding blank lines."""
357
362
  start, end = span
358
363
  before = text[:start].rstrip("\n")
@@ -362,7 +367,7 @@ class SSHConfig:
362
367
  return before or after
363
368
 
364
369
  @staticmethod
365
- def check_existing(ssh_config: Path, alias: str) -> Tuple[str, bool]:
370
+ def check_existing(ssh_config: Path, alias: str) -> tuple[str, bool]:
366
371
  """Check for an existing alias, prompt to overwrite."""
367
372
  if not ssh_config.exists():
368
373
  return "", False
@@ -391,7 +396,12 @@ class SSHConfig:
391
396
  return SSHConfig._splice_out(text, blocks[alias]), True
392
397
 
393
398
  @staticmethod
394
- def collect_entries(text: str) -> List[Dict[str, str]]:
399
+ def remove_stale(ssh_config: Path, base_text: str) -> None:
400
+ """Write config with the overwritten entry spliced out."""
401
+ SSHConfig._atomic_write(ssh_config, base_text)
402
+
403
+ @staticmethod
404
+ def collect_entries(text: str) -> list[dict[str, str]]:
395
405
  """Parse managed entries from SSH config text."""
396
406
  entries = []
397
407
  for m in re.finditer(
@@ -401,7 +411,7 @@ class SSHConfig:
401
411
  ):
402
412
  body = m.group(3)
403
413
 
404
- def field(name: str) -> str:
414
+ def field(name: str, body: str = body) -> str:
405
415
  fm = re.search(rf"^\s*{name}\s+(\S+)", body, re.MULTILINE)
406
416
  return fm.group(1) if fm else "?"
407
417
 
@@ -486,11 +496,6 @@ class SSHConfig:
486
496
  text = block + "\n"
487
497
  SSHConfig._atomic_write(ssh_config, text)
488
498
 
489
- @staticmethod
490
- def revert(ssh_config: Path, base_text: str) -> None:
491
- """Restore SSH config to its pre-update state."""
492
- SSHConfig._atomic_write(ssh_config, base_text)
493
-
494
499
 
495
500
  class Deployer:
496
501
  """Deploy an SSH public key to a remote host."""
@@ -507,7 +512,7 @@ class Deployer:
507
512
  and "REMOTE HOST IDENTIFICATION HAS CHANGED" not in stderr)
508
513
 
509
514
  @staticmethod
510
- def _format_host_key_info(host: str, stderr: str) -> Optional[str]:
515
+ def _format_host_key_info(host: str, stderr: str) -> str | None:
511
516
  """Parse verbose SSH stderr into native-looking host key info."""
512
517
  key_m = re.search(r"Server host key: (\S+) (\S+)", stderr)
513
518
  if not key_m:
@@ -537,7 +542,7 @@ class Deployer:
537
542
 
538
543
  @staticmethod
539
544
  def _ssh_cmd(runner: Runner, remote: str, install_cmd: str,
540
- pub_key: str, accept_new: bool = False) -> Tuple[int, str]:
545
+ pub_key: str, accept_new: bool = False) -> tuple[int, str]:
541
546
  """Run the SSH deploy command."""
542
547
  policy = "accept-new" if accept_new else "yes"
543
548
  cmd = ["ssh"]
@@ -597,7 +602,7 @@ class Deployer:
597
602
  "\nSSH connection failed. Check host and credentials."
598
603
  )
599
604
  if stderr.strip():
600
- seen: Set[str] = set()
605
+ seen: set[str] = set()
601
606
  for line in stderr.strip().splitlines():
602
607
  if line not in seen and not line.startswith("debug1:"):
603
608
  seen.add(line)
@@ -627,7 +632,7 @@ def is_ip(value: str) -> bool:
627
632
  return False
628
633
 
629
634
 
630
- def split_target(target: str) -> Tuple[Optional[str], str]:
635
+ def split_target(target: str) -> tuple[str | None, str]:
631
636
  """Split a [user@]host target into user and host."""
632
637
  if "@" in target:
633
638
  user, host = target.rsplit("@", 1)
@@ -638,24 +643,23 @@ def split_target(target: str) -> Tuple[Optional[str], str]:
638
643
  _DESCRIPTION = (
639
644
  "Set up SSH key auth in one command.\n"
640
645
  "Generates a per-host Ed25519 key pair, deploys it\n"
641
- "to the remote host, and adds an entry to ~/.ssh/config."
646
+ "to the remote host and adds an entry to ~/.ssh/config."
642
647
  )
643
648
 
644
- _EPILOG = (
645
- "examples:\n"
646
- " ssh-keyup"
647
- " interactive mode\n"
648
- " ssh-keyup pi@192.168.1.23 mypi"
649
- " user, host and alias\n"
650
- " ssh-keyup trinity@rpi-5.local"
651
- " alias defaults to rpi-5\n"
652
- " ssh-keyup 192.168.1.23"
653
- " prompts for username and alias\n"
654
- " ssh-keyup --host rpi-5 --user pi --alias mypi\n"
655
- " ssh-keyup --list"
656
- " show managed entries\n"
657
- " ssh-keyup --remove mypi"
658
- " delete a managed entry"
649
+ _EXAMPLES = [
650
+ ("ssh-keyup", "interactive mode"),
651
+ ("ssh-keyup pi@192.168.1.23 mypi", "user, host and alias"),
652
+ ("ssh-keyup trinity@rpi-5.local", "alias defaults to rpi-5"),
653
+ ("ssh-keyup 192.168.1.23", "prompts for username and alias"),
654
+ ("ssh-keyup --host rpi-5 --user pi --alias mypi", "flags work too"),
655
+ ("ssh-keyup --list", "show managed entries"),
656
+ ("ssh-keyup --remove mypi", "delete a managed entry"),
657
+ ]
658
+
659
+ _CMD_WIDTH = max(len(cmd) for cmd, _ in _EXAMPLES) + 2
660
+
661
+ _EPILOG = "examples:\n" + "\n".join(
662
+ f" {cmd.ljust(_CMD_WIDTH)}{desc}" for cmd, desc in _EXAMPLES
659
663
  )
660
664
 
661
665
 
@@ -709,8 +713,8 @@ def parse_args() -> argparse.Namespace:
709
713
  return args
710
714
 
711
715
 
712
- def gather_input(args: argparse.Namespace) -> Tuple[str, str, str]:
713
- """Collect host, username, and alias from args or prompts."""
716
+ def gather_input(args: argparse.Namespace) -> tuple[str, str, str]:
717
+ """Collect host, username and alias from args or prompts."""
714
718
  host = cli.prompt("Remote host", args.host, hint="IP or name")
715
719
  if not host:
716
720
  cli.fatal("No host provided.")
@@ -749,6 +753,13 @@ def generate_key(runner: Runner, key_path: Path) -> None:
749
753
  cli.fatal("ssh-keygen failed.")
750
754
 
751
755
 
756
+ def discard_keys(key_path: Path, pub_path: Path) -> None:
757
+ """Delete a key pair generated during a failed run."""
758
+ cli.status("Cleaning up generated key pair...")
759
+ key_path.unlink(missing_ok=True)
760
+ pub_path.unlink(missing_ok=True)
761
+
762
+
752
763
  def main() -> None:
753
764
  """Entry point: gather input, generate keys, deploy, update config."""
754
765
  try:
@@ -795,24 +806,25 @@ def main() -> None:
795
806
  key_generated = True
796
807
 
797
808
  cli.separator()
809
+ # Remove stale entry now, otherwise deploy's ssh would resolve
810
+ # the typed host through its old HostName. Stays removed on
811
+ # deploy failure, user chose to overwrite.
812
+ if overwriting:
813
+ try:
814
+ SSHConfig.remove_stale(ssh_config, config_base)
815
+ except OSError as ex:
816
+ if key_generated:
817
+ discard_keys(key_path, pub_path)
818
+ cli.fatal(f"SSH config update failed: {ex}")
798
819
  if not Deployer.deploy(runner, user, host, pub_path):
799
820
  if key_generated:
800
- cli.status("Cleaning up generated key pair...")
801
- key_path.unlink(missing_ok=True)
802
- pub_path.unlink(missing_ok=True)
803
- if overwriting:
804
- try:
805
- SSHConfig.revert(ssh_config, config_base)
806
- except Exception as ex:
807
- cli.fail(
808
- f"SSH config cleanup failed: {ex}"
809
- )
821
+ discard_keys(key_path, pub_path)
810
822
  sys.exit(1)
811
823
 
812
824
  try:
813
825
  SSHConfig.update(ssh_config, alias, host, user, file_alias,
814
826
  config_base)
815
- except Exception as ex:
827
+ except OSError as ex:
816
828
  cli.fatal(f"Key deployed, but SSH config update failed: {ex}")
817
829
  cli.msg(f"Config updated {ssh_config}")
818
830
 
File without changes