ssh-keyup 1.0.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.0.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
@@ -20,15 +25,18 @@ Dynamic: license-file
20
25
 
21
26
  # ssh-keyup
22
27
 
28
+ ![CI](https://github.com/Kurokesu/ssh-keyup/actions/workflows/ci.yml/badge.svg)
23
29
  ![PyPI](https://img.shields.io/pypi/v/ssh-keyup)
24
30
  ![Python](https://img.shields.io/badge/python-3.8%2B-brightgreen)
25
31
  ![Platform](https://img.shields.io/badge/platform-Windows%20%7C%20Linux-blue)
26
32
 
27
- 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.**
28
34
 
29
- 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?
30
36
 
31
- ![ssh-keyup demo](demo.gif)
37
+ **`ssh-keyup`** handles all three in a single interactive session.
38
+
39
+ ![ssh-keyup demo](https://raw.githubusercontent.com/Kurokesu/ssh-keyup/main/demo.gif)
32
40
 
33
41
  ## Quickstart
34
42
 
@@ -40,6 +48,11 @@ pip install ssh-keyup
40
48
  ssh-keyup # ready to use anywhere
41
49
  ```
42
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
+
43
56
  Or run directly without installing:
44
57
 
45
58
  ```bash
@@ -59,22 +72,31 @@ ssh mypi # no password, ever again
59
72
 
60
73
  Or open [VSCode Remote - SSH](https://marketplace.visualstudio.com/items?itemName=ms-vscode-remote.remote-ssh), your `~/.ssh/config` is already set up. Press `Ctrl+Shift+P`, select **Remote-SSH: Connect to Host**, pick your alias and get a full IDE on your remote device, no password:
61
74
 
62
- ![VSCode Remote SSH](demo-vscode.gif)
75
+ ![VSCode Remote SSH](https://raw.githubusercontent.com/Kurokesu/ssh-keyup/main/demo-vscode.gif)
63
76
 
64
77
  Skip the prompts by passing arguments:
65
78
 
66
79
  ```bash
67
- ssh-keyup --host 192.168.1.23 --user pi --alias mypi
80
+ ssh-keyup pi@192.168.1.23 mypi # user, host and alias in one go
68
81
  ```
69
82
 
70
83
  Or configure a whole fleet:
71
84
 
72
85
  ```bash
73
86
  for host in 192.168.1.10 192.168.1.11 192.168.1.12; do
74
- ssh-keyup --host $host
87
+ ssh-keyup pi@$host
75
88
  done
76
89
  ```
77
90
 
91
+ Flags (`--host`, `--user`, `--alias`) work too, see `ssh-keyup --help`.
92
+
93
+ List or remove entries ssh-keyup manages:
94
+
95
+ ```bash
96
+ ssh-keyup --list
97
+ ssh-keyup --remove mypi # deletes its key pair too
98
+ ```
99
+
78
100
  ## Why?
79
101
 
80
102
  ```bash
@@ -106,5 +128,5 @@ ssh-keyup
106
128
  - Detects and recovers from **host key mismatches** (common after reflashing)
107
129
  - Handles re-runs gracefully: reuses existing keys or offers regeneration, detects duplicate config entries
108
130
  - Works with any device reachable over SSH: Raspberry Pi, NVIDIA Jetson, Orange Pi, VMs, servers
109
- - **Zero dependencies**, Python 3.8+ standard library only
131
+ - **Zero Python dependencies**, standard library only. Uses system OpenSSH (`ssh`, `ssh-keygen`)
110
132
  - Installs via `pip` or runs as a single script
@@ -1,14 +1,17 @@
1
1
  # ssh-keyup
2
2
 
3
+ ![CI](https://github.com/Kurokesu/ssh-keyup/actions/workflows/ci.yml/badge.svg)
3
4
  ![PyPI](https://img.shields.io/pypi/v/ssh-keyup)
4
5
  ![Python](https://img.shields.io/badge/python-3.8%2B-brightgreen)
5
6
  ![Platform](https://img.shields.io/badge/platform-Windows%20%7C%20Linux-blue)
6
7
 
7
- 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.**
8
9
 
9
- 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?
10
11
 
11
- ![ssh-keyup demo](demo.gif)
12
+ **`ssh-keyup`** handles all three in a single interactive session.
13
+
14
+ ![ssh-keyup demo](https://raw.githubusercontent.com/Kurokesu/ssh-keyup/main/demo.gif)
12
15
 
13
16
  ## Quickstart
14
17
 
@@ -20,6 +23,11 @@ pip install ssh-keyup
20
23
  ssh-keyup # ready to use anywhere
21
24
  ```
22
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
+
23
31
  Or run directly without installing:
24
32
 
25
33
  ```bash
@@ -39,22 +47,31 @@ ssh mypi # no password, ever again
39
47
 
40
48
  Or open [VSCode Remote - SSH](https://marketplace.visualstudio.com/items?itemName=ms-vscode-remote.remote-ssh), your `~/.ssh/config` is already set up. Press `Ctrl+Shift+P`, select **Remote-SSH: Connect to Host**, pick your alias and get a full IDE on your remote device, no password:
41
49
 
42
- ![VSCode Remote SSH](demo-vscode.gif)
50
+ ![VSCode Remote SSH](https://raw.githubusercontent.com/Kurokesu/ssh-keyup/main/demo-vscode.gif)
43
51
 
44
52
  Skip the prompts by passing arguments:
45
53
 
46
54
  ```bash
47
- ssh-keyup --host 192.168.1.23 --user pi --alias mypi
55
+ ssh-keyup pi@192.168.1.23 mypi # user, host and alias in one go
48
56
  ```
49
57
 
50
58
  Or configure a whole fleet:
51
59
 
52
60
  ```bash
53
61
  for host in 192.168.1.10 192.168.1.11 192.168.1.12; do
54
- ssh-keyup --host $host
62
+ ssh-keyup pi@$host
55
63
  done
56
64
  ```
57
65
 
66
+ Flags (`--host`, `--user`, `--alias`) work too, see `ssh-keyup --help`.
67
+
68
+ List or remove entries ssh-keyup manages:
69
+
70
+ ```bash
71
+ ssh-keyup --list
72
+ ssh-keyup --remove mypi # deletes its key pair too
73
+ ```
74
+
58
75
  ## Why?
59
76
 
60
77
  ```bash
@@ -86,5 +103,5 @@ ssh-keyup
86
103
  - Detects and recovers from **host key mismatches** (common after reflashing)
87
104
  - Handles re-runs gracefully: reuses existing keys or offers regeneration, detects duplicate config entries
88
105
  - Works with any device reachable over SSH: Raspberry Pi, NVIDIA Jetson, Orange Pi, VMs, servers
89
- - **Zero dependencies**, Python 3.8+ standard library only
106
+ - **Zero Python dependencies**, standard library only. Uses system OpenSSH (`ssh`, `ssh-keygen`)
90
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.0.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
@@ -20,15 +25,18 @@ Dynamic: license-file
20
25
 
21
26
  # ssh-keyup
22
27
 
28
+ ![CI](https://github.com/Kurokesu/ssh-keyup/actions/workflows/ci.yml/badge.svg)
23
29
  ![PyPI](https://img.shields.io/pypi/v/ssh-keyup)
24
30
  ![Python](https://img.shields.io/badge/python-3.8%2B-brightgreen)
25
31
  ![Platform](https://img.shields.io/badge/platform-Windows%20%7C%20Linux-blue)
26
32
 
27
- 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.**
28
34
 
29
- 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?
30
36
 
31
- ![ssh-keyup demo](demo.gif)
37
+ **`ssh-keyup`** handles all three in a single interactive session.
38
+
39
+ ![ssh-keyup demo](https://raw.githubusercontent.com/Kurokesu/ssh-keyup/main/demo.gif)
32
40
 
33
41
  ## Quickstart
34
42
 
@@ -40,6 +48,11 @@ pip install ssh-keyup
40
48
  ssh-keyup # ready to use anywhere
41
49
  ```
42
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
+
43
56
  Or run directly without installing:
44
57
 
45
58
  ```bash
@@ -59,22 +72,31 @@ ssh mypi # no password, ever again
59
72
 
60
73
  Or open [VSCode Remote - SSH](https://marketplace.visualstudio.com/items?itemName=ms-vscode-remote.remote-ssh), your `~/.ssh/config` is already set up. Press `Ctrl+Shift+P`, select **Remote-SSH: Connect to Host**, pick your alias and get a full IDE on your remote device, no password:
61
74
 
62
- ![VSCode Remote SSH](demo-vscode.gif)
75
+ ![VSCode Remote SSH](https://raw.githubusercontent.com/Kurokesu/ssh-keyup/main/demo-vscode.gif)
63
76
 
64
77
  Skip the prompts by passing arguments:
65
78
 
66
79
  ```bash
67
- ssh-keyup --host 192.168.1.23 --user pi --alias mypi
80
+ ssh-keyup pi@192.168.1.23 mypi # user, host and alias in one go
68
81
  ```
69
82
 
70
83
  Or configure a whole fleet:
71
84
 
72
85
  ```bash
73
86
  for host in 192.168.1.10 192.168.1.11 192.168.1.12; do
74
- ssh-keyup --host $host
87
+ ssh-keyup pi@$host
75
88
  done
76
89
  ```
77
90
 
91
+ Flags (`--host`, `--user`, `--alias`) work too, see `ssh-keyup --help`.
92
+
93
+ List or remove entries ssh-keyup manages:
94
+
95
+ ```bash
96
+ ssh-keyup --list
97
+ ssh-keyup --remove mypi # deletes its key pair too
98
+ ```
99
+
78
100
  ## Why?
79
101
 
80
102
  ```bash
@@ -106,5 +128,5 @@ ssh-keyup
106
128
  - Detects and recovers from **host key mismatches** (common after reflashing)
107
129
  - Handles re-runs gracefully: reuses existing keys or offers regeneration, detects duplicate config entries
108
130
  - Works with any device reachable over SSH: Raspberry Pi, NVIDIA Jetson, Orange Pi, VMs, servers
109
- - **Zero dependencies**, Python 3.8+ standard library only
131
+ - **Zero Python dependencies**, standard library only. Uses system OpenSSH (`ssh`, `ssh-keygen`)
110
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.0.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,16 @@ 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, Tuple, Union
26
+
27
+ if sys.platform == "win32":
28
+ import ctypes
29
+ import msvcrt
30
+ else:
31
+ import termios
32
+ import tty
23
33
 
24
34
 
25
35
  class CLI:
@@ -53,29 +63,28 @@ class CLI:
53
63
  S_SUCCESS = GREEN
54
64
  S_STATUS = CYAN
55
65
 
66
+ STYLE_ATTRS = (
67
+ "BOLD", "DIM", "RESET", "GREEN", "RED", "YELLOW", "CYAN",
68
+ "HIDE_CUR", "SHOW_CUR", "S_BANNER", "S_VERSION", "S_SEPARATOR",
69
+ "S_HINT", "S_SSH_WARNING", "S_SSH_INFO", "S_SUCCESS", "S_STATUS",
70
+ )
71
+
56
72
  def __init__(self) -> None:
57
73
  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 = ""
74
+ for attr in CLI.STYLE_ATTRS:
75
+ setattr(CLI, attr, "")
64
76
 
65
77
  @staticmethod
66
78
  def enable_ansi() -> None:
67
79
  """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
80
+ if sys.platform == "win32":
81
+ # Best effort, colors just stay off if this fails
82
+ with contextlib.suppress(Exception):
83
+ k = ctypes.windll.kernel32
84
+ h = k.GetStdHandle(-11)
85
+ m = ctypes.c_ulong()
86
+ k.GetConsoleMode(h, ctypes.byref(m))
87
+ k.SetConsoleMode(h, m.value | 0x0004)
79
88
 
80
89
  @staticmethod
81
90
  def banner() -> None:
@@ -108,7 +117,7 @@ class CLI:
108
117
  @staticmethod
109
118
  def fatal(msg: str) -> None:
110
119
  """Print an error message and exit."""
111
- cli.fail(msg)
120
+ CLI.fail(msg)
112
121
  sys.exit(1)
113
122
 
114
123
  @staticmethod
@@ -142,7 +151,7 @@ class CLI:
142
151
 
143
152
  @staticmethod
144
153
  def prompt(
145
- label: str, value: Optional[str] = None, *,
154
+ label: str, value: str | None = None, *,
146
155
  hint: str = "", default: str = "",
147
156
  ) -> str:
148
157
  """Prompt for input, or display and return a pre-supplied value."""
@@ -167,7 +176,6 @@ class CLI:
167
176
  def _read_key() -> str:
168
177
  """Read a single keypress."""
169
178
  if sys.platform == "win32":
170
- import msvcrt
171
179
  ch = msvcrt.getwch()
172
180
  if ch == "\x03":
173
181
  raise KeyboardInterrupt
@@ -177,8 +185,6 @@ class CLI:
177
185
  return {"K": "left", "M": "right"}.get(msvcrt.getwch(), "")
178
186
  return "esc" if ch == "\x1b" else ch
179
187
  else:
180
- import termios
181
- import tty
182
188
  fd = sys.stdin.fileno()
183
189
  old = termios.tcgetattr(fd)
184
190
  try:
@@ -247,7 +253,7 @@ class Runner:
247
253
  """Run SSH commands natively or via Git Bash as fallback."""
248
254
 
249
255
  @staticmethod
250
- def _find_git_bash() -> Optional[str]:
256
+ def _find_git_bash() -> str | None:
251
257
  """Locate Git Bash on Windows for use as an SSH fallback."""
252
258
  git = which("git")
253
259
  if not git:
@@ -262,10 +268,10 @@ class Runner:
262
268
  def __init__(self) -> None:
263
269
  self.git_bash = Runner._find_git_bash()
264
270
  openssh = all(which(c) for c in ("ssh", "ssh-keygen"))
265
- self.mode = (
271
+ self.mode: str | None = (
266
272
  "native" if openssh
267
273
  else ("gitbash" if self.git_bash else None)
268
- ) # type: Optional[str]
274
+ )
269
275
 
270
276
  def check(self) -> None:
271
277
  """Exit with guidance if no SSH tools are available."""
@@ -281,27 +287,30 @@ class Runner:
281
287
  "sudo apt install openssh-client")
282
288
 
283
289
  def _subprocess_args(
284
- self, cmd: Union[List[str], str],
285
- ) -> Tuple[Union[List[str], str], bool]:
290
+ self, cmd: list[str] | str,
291
+ ) -> tuple[list[str] | str, bool]:
286
292
  """Prepare the command and shell flag for subprocess.run."""
287
293
  if self.mode == "native":
288
294
  return cmd, isinstance(cmd, str)
289
- assert self.git_bash
295
+ if self.git_bash is None:
296
+ raise RuntimeError("gitbash mode without Git Bash path")
290
297
  sh = (cmd if isinstance(cmd, str)
291
298
  else " ".join(shlex.quote(a) for a in cmd))
292
299
  return [self.git_bash, "-c", sh], False
293
300
 
294
- def run(self, cmd: Union[List[str], str], **kwargs) -> int:
301
+ def run(self, cmd: list[str] | str, **kwargs) -> int:
295
302
  """Run a command and return the exit code."""
296
303
  args, shell = self._subprocess_args(cmd)
297
- return subprocess.run(args, shell=shell, **kwargs).returncode
304
+ r = subprocess.run(args, shell=shell, check=False, **kwargs)
305
+ return r.returncode
298
306
 
299
307
  def run_capture(
300
- self, cmd: Union[List[str], str], **kwargs,
301
- ) -> Tuple[int, str]:
308
+ self, cmd: list[str] | str, **kwargs,
309
+ ) -> tuple[int, str]:
302
310
  """Run a command, capture stderr, return (rc, text)."""
303
311
  args, shell = self._subprocess_args(cmd)
304
- r = subprocess.run(args, shell=shell, stderr=subprocess.PIPE, **kwargs)
312
+ r = subprocess.run(args, shell=shell, check=False,
313
+ stderr=subprocess.PIPE, **kwargs)
305
314
  return r.returncode, (r.stderr or b"").decode(errors="replace")
306
315
 
307
316
 
@@ -309,9 +318,9 @@ class SSHConfig:
309
318
  """Manage ssh-keyup entries in ~/.ssh/config."""
310
319
 
311
320
  @staticmethod
312
- def _find_managed_blocks(text: str) -> Dict[str, Tuple[int, int]]:
321
+ def _find_managed_blocks(text: str) -> dict[str, tuple[int, int]]:
313
322
  """Find ssh-keyup managed blocks in SSH config text."""
314
- blocks = {} # type: Dict[str, Tuple[int, int]]
323
+ blocks: dict[str, tuple[int, int]] = {}
315
324
  for m in re.finditer(
316
325
  r"^#ssh-keyup:begin (\S+)[^\n]*\n.*?^#ssh-keyup:end \1[^\n]*\n?",
317
326
  text, re.MULTILINE | re.DOTALL,
@@ -321,7 +330,7 @@ class SSHConfig:
321
330
 
322
331
  @staticmethod
323
332
  def _has_unmanaged_host(
324
- text: str, alias: str, managed_blocks: Dict[str, Tuple[int, int]],
333
+ text: str, alias: str, managed_blocks: dict[str, tuple[int, int]],
325
334
  ) -> bool:
326
335
  """Check for a Host entry outside managed markers."""
327
336
  for m in re.finditer(r"^Host\s+(\S+)", text, re.MULTILINE):
@@ -337,8 +346,9 @@ class SSHConfig:
337
346
  alias: str, host: str, user: str, file_alias: str,
338
347
  ) -> str:
339
348
  """Build the SSH config block text for a managed host entry."""
349
+ stamp = datetime.now(timezone.utc).astimezone().date().isoformat()
340
350
  return (
341
- f"#ssh-keyup:begin {alias} {date.today().isoformat()}\n"
351
+ f"#ssh-keyup:begin {alias} {stamp}\n"
342
352
  f"Host {alias}\n"
343
353
  f" HostName {host}\n"
344
354
  f" User {user}\n"
@@ -347,7 +357,17 @@ class SSHConfig:
347
357
  )
348
358
 
349
359
  @staticmethod
350
- def check_existing(ssh_config: Path, alias: str) -> Tuple[str, bool]:
360
+ def _splice_out(text: str, span: tuple[int, int]) -> str:
361
+ """Remove a text span, collapsing surrounding blank lines."""
362
+ start, end = span
363
+ before = text[:start].rstrip("\n")
364
+ after = text[end:].lstrip("\n")
365
+ if before and after:
366
+ return before + "\n\n" + after
367
+ return before or after
368
+
369
+ @staticmethod
370
+ def check_existing(ssh_config: Path, alias: str) -> tuple[str, bool]:
351
371
  """Check for an existing alias, prompt to overwrite."""
352
372
  if not ssh_config.exists():
353
373
  return "", False
@@ -373,12 +393,83 @@ class SSHConfig:
373
393
  cli.cancel("No changes were made.")
374
394
  sys.exit(0)
375
395
 
396
+ return SSHConfig._splice_out(text, blocks[alias]), True
397
+
398
+ @staticmethod
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]]:
405
+ """Parse managed entries from SSH config text."""
406
+ entries = []
407
+ for m in re.finditer(
408
+ r"^#ssh-keyup:begin (\S+)(?: (\S+))?[^\n]*\n"
409
+ r"(.*?)^#ssh-keyup:end \1",
410
+ text, re.MULTILINE | re.DOTALL,
411
+ ):
412
+ body = m.group(3)
413
+
414
+ def field(name: str, body: str = body) -> str:
415
+ fm = re.search(rf"^\s*{name}\s+(\S+)", body, re.MULTILINE)
416
+ return fm.group(1) if fm else "?"
417
+
418
+ entries.append({
419
+ "alias": m.group(1),
420
+ "date": m.group(2) or "?",
421
+ "host": field("HostName"),
422
+ "user": field("User"),
423
+ "key": field("IdentityFile"),
424
+ })
425
+ return entries
426
+
427
+ @staticmethod
428
+ def list_entries(ssh_config: Path) -> None:
429
+ """Print managed entries as aligned columns."""
430
+ text = (ssh_config.read_text(encoding="utf-8")
431
+ if ssh_config.exists() else "")
432
+ entries = SSHConfig.collect_entries(text)
433
+ if not entries:
434
+ cli.msg("No entries managed by ssh-keyup.")
435
+ return
436
+
437
+ header = ("alias", "host", "user", "key", "added")
438
+ rows = [(e["alias"], e["host"], e["user"], e["key"], e["date"])
439
+ for e in entries]
440
+ widths = [max(len(row[i]) for row in rows + [header])
441
+ for i in range(len(header))]
442
+ cli.hint(" ".join(h.ljust(w) for h, w in zip(header, widths)))
443
+ for row in rows:
444
+ cli.msg(" ".join(v.ljust(w) for v, w in zip(row, widths)))
445
+
446
+ @staticmethod
447
+ def remove_entry(ssh_config: Path, alias: str) -> None:
448
+ """Remove a managed entry and its key pair."""
449
+ text = (ssh_config.read_text(encoding="utf-8")
450
+ if ssh_config.exists() else "")
451
+ blocks = SSHConfig._find_managed_blocks(text)
452
+ if alias not in blocks:
453
+ cli.fatal(f"No entry '{alias}' managed by ssh-keyup.")
454
+
376
455
  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
456
+ key_m = re.search(r"^\s*IdentityFile\s+(\S+)", text[start:end],
457
+ re.MULTILINE)
458
+
459
+ new_text = SSHConfig._splice_out(text, blocks[alias])
460
+ if new_text:
461
+ new_text = new_text.rstrip("\n") + "\n"
462
+ SSHConfig._atomic_write(ssh_config, new_text)
463
+ cli.msg(f"Removed '{alias}' from {ssh_config}")
464
+
465
+ if not key_m:
466
+ return
467
+ key_path = Path(key_m.group(1)).expanduser()
468
+ pub_path = Path(str(key_path) + ".pub")
469
+ if key_path.exists() or pub_path.exists():
470
+ key_path.unlink(missing_ok=True)
471
+ pub_path.unlink(missing_ok=True)
472
+ cli.msg(f"Deleted key pair {key_path.name}")
382
473
 
383
474
  @staticmethod
384
475
  def _atomic_write(ssh_config: Path, text: str) -> None:
@@ -405,11 +496,6 @@ class SSHConfig:
405
496
  text = block + "\n"
406
497
  SSHConfig._atomic_write(ssh_config, text)
407
498
 
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
499
 
414
500
  class Deployer:
415
501
  """Deploy an SSH public key to a remote host."""
@@ -426,7 +512,7 @@ class Deployer:
426
512
  and "REMOTE HOST IDENTIFICATION HAS CHANGED" not in stderr)
427
513
 
428
514
  @staticmethod
429
- def _format_host_key_info(host: str, stderr: str) -> Optional[str]:
515
+ def _format_host_key_info(host: str, stderr: str) -> str | None:
430
516
  """Parse verbose SSH stderr into native-looking host key info."""
431
517
  key_m = re.search(r"Server host key: (\S+) (\S+)", stderr)
432
518
  if not key_m:
@@ -456,7 +542,7 @@ class Deployer:
456
542
 
457
543
  @staticmethod
458
544
  def _ssh_cmd(runner: Runner, remote: str, install_cmd: str,
459
- pub_key: str, accept_new: bool = False) -> Tuple[int, str]:
545
+ pub_key: str, accept_new: bool = False) -> tuple[int, str]:
460
546
  """Run the SSH deploy command."""
461
547
  policy = "accept-new" if accept_new else "yes"
462
548
  cmd = ["ssh"]
@@ -516,7 +602,7 @@ class Deployer:
516
602
  "\nSSH connection failed. Check host and credentials."
517
603
  )
518
604
  if stderr.strip():
519
- seen = set() # type: set
605
+ seen: set[str] = set()
520
606
  for line in stderr.strip().splitlines():
521
607
  if line not in seen and not line.startswith("debug1:"):
522
608
  seen.add(line)
@@ -546,22 +632,34 @@ def is_ip(value: str) -> bool:
546
632
  return False
547
633
 
548
634
 
635
+ def split_target(target: str) -> tuple[str | None, str]:
636
+ """Split a [user@]host target into user and host."""
637
+ if "@" in target:
638
+ user, host = target.rsplit("@", 1)
639
+ return (user or None), host
640
+ return None, target
641
+
642
+
549
643
  _DESCRIPTION = (
550
644
  "Set up SSH key auth in one command.\n"
551
645
  "Generates a per-host Ed25519 key pair, deploys it\n"
552
- "to the remote host, and adds an entry to ~/.ssh/config."
646
+ "to the remote host and adds an entry to ~/.ssh/config."
553
647
  )
554
648
 
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"
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
565
663
  )
566
664
 
567
665
 
@@ -575,17 +673,48 @@ def parse_args() -> argparse.Namespace:
575
673
  )
576
674
  p.add_argument("--version", action="version",
577
675
  version=f"%(prog)s {__version__}")
676
+ p.add_argument("target", nargs="?", metavar="[user@]host",
677
+ help="remote device, e.g. pi@192.168.1.23")
678
+ p.add_argument("alias_pos", nargs="?", metavar="alias",
679
+ help="friendly name for ~/.ssh/config (default: hostname)")
578
680
  p.add_argument("--host",
579
681
  help="IP address or hostname of the remote device")
580
682
  p.add_argument("--user",
581
683
  help="login username on the remote device")
582
684
  p.add_argument("--alias",
583
685
  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."""
686
+ p.add_argument("--list", action="store_true",
687
+ help="list entries managed by ssh-keyup")
688
+ p.add_argument("--remove", metavar="ALIAS",
689
+ help="remove a managed entry from ~/.ssh/config")
690
+ args = p.parse_args()
691
+
692
+ if args.list and args.remove:
693
+ p.error("--list and --remove cannot be combined")
694
+ if ((args.list or args.remove)
695
+ and any((args.target, args.alias_pos,
696
+ args.host, args.user, args.alias))):
697
+ p.error("--list/--remove cannot be combined with setup arguments")
698
+
699
+ if args.target:
700
+ user, host = split_target(args.target)
701
+ if args.host:
702
+ p.error("host given both as positional and --host")
703
+ args.host = host
704
+ if user:
705
+ if args.user:
706
+ p.error("user given both as user@ prefix and --user")
707
+ args.user = user
708
+ if args.alias_pos:
709
+ if args.alias:
710
+ p.error("alias given both as positional and --alias")
711
+ args.alias = args.alias_pos
712
+
713
+ return args
714
+
715
+
716
+ def gather_input(args: argparse.Namespace) -> tuple[str, str, str]:
717
+ """Collect host, username and alias from args or prompts."""
589
718
  host = cli.prompt("Remote host", args.host, hint="IP or name")
590
719
  if not host:
591
720
  cli.fatal("No host provided.")
@@ -609,9 +738,7 @@ def gather_input(args: argparse.Namespace) -> Tuple[str, str, str]:
609
738
  return host, user, alias
610
739
 
611
740
 
612
- def generate_key(
613
- runner: Runner, key_path: Path, pub_path: Path, file_alias: str,
614
- ) -> None:
741
+ def generate_key(runner: Runner, key_path: Path) -> None:
615
742
  """Generate an Ed25519 key pair."""
616
743
  if runner.mode == "native":
617
744
  rc = runner.run([
@@ -619,19 +746,34 @@ def generate_key(
619
746
  ])
620
747
  else:
621
748
  rc = runner.run(
622
- f"ssh-keygen -t ed25519 -N '' -f ~/.ssh/id_ed25519_{file_alias}"
749
+ f"ssh-keygen -t ed25519 -N '' -f ~/.ssh/{key_path.name}"
623
750
  )
624
751
 
625
752
  if rc != 0:
626
753
  cli.fatal("ssh-keygen failed.")
627
754
 
628
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
+
629
763
  def main() -> None:
630
764
  """Entry point: gather input, generate keys, deploy, update config."""
631
765
  try:
632
766
  cli.enable_ansi()
633
767
  args = parse_args()
634
768
 
769
+ ssh_config = Path.home() / ".ssh" / "config"
770
+ if args.list:
771
+ SSHConfig.list_entries(ssh_config)
772
+ return
773
+ if args.remove:
774
+ SSHConfig.remove_entry(ssh_config, args.remove)
775
+ return
776
+
635
777
  cli.banner()
636
778
  cli.separator()
637
779
 
@@ -657,31 +799,32 @@ def main() -> None:
657
799
  if cli.ask_yn("Regenerate key pair?"):
658
800
  key_path.unlink(missing_ok=True)
659
801
  pub_path.unlink()
660
- generate_key(runner, key_path, pub_path, file_alias)
802
+ generate_key(runner, key_path)
661
803
  key_generated = True
662
804
  else:
663
- generate_key(runner, key_path, pub_path, file_alias)
805
+ generate_key(runner, key_path)
664
806
  key_generated = True
665
807
 
666
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}")
667
819
  if not Deployer.deploy(runner, user, host, pub_path):
668
820
  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
- )
821
+ discard_keys(key_path, pub_path)
679
822
  sys.exit(1)
680
823
 
681
824
  try:
682
825
  SSHConfig.update(ssh_config, alias, host, user, file_alias,
683
826
  config_base)
684
- except Exception as ex:
827
+ except OSError as ex:
685
828
  cli.fatal(f"Key deployed, but SSH config update failed: {ex}")
686
829
  cli.msg(f"Config updated {ssh_config}")
687
830
 
File without changes