ssh-keyup 1.2.0__tar.gz → 1.3.0__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,14 +1,14 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: ssh-keyup
3
- Version: 1.2.0
4
- Summary: Passwordless SSH setup and ssh-copy-id alternative for Raspberry Pi, NVIDIA Jetson or any Linux device
3
+ Version: 1.3.0
4
+ Summary: Passwordless SSH setup and ssh-copy-id alternative for any Linux or RouterOS device, such as Raspberry Pi, NVIDIA Jetson or MikroTik routers
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
9
  Project-URL: Issues, https://github.com/Kurokesu/ssh-keyup/issues
10
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
11
+ Keywords: ssh,ssh-keys,ssh-config,ssh-copy-id,passwordless-ssh,openssh,ed25519,raspberry-pi,rpi,jetson,mikrotik,routeros,iot,automation,vscode,remote-ssh,windows,linux
12
12
  Classifier: Development Status :: 5 - Production/Stable
13
13
  Classifier: Environment :: Console
14
14
  Classifier: Intended Audience :: Developers
@@ -16,6 +16,7 @@ Classifier: Intended Audience :: System Administrators
16
16
  Classifier: Operating System :: Microsoft :: Windows
17
17
  Classifier: Operating System :: POSIX :: Linux
18
18
  Classifier: Programming Language :: Python :: 3
19
+ Classifier: Topic :: System :: Networking
19
20
  Classifier: Topic :: System :: Systems Administration
20
21
  Classifier: Topic :: Utilities
21
22
  Requires-Python: >=3.8
@@ -30,7 +31,7 @@ Dynamic: license-file
30
31
  ![Python](https://img.shields.io/badge/python-3.8%2B-brightgreen)
31
32
  ![Platform](https://img.shields.io/badge/platform-Windows%20%7C%20Linux-blue)
32
33
 
33
- **Set up passwordless SSH on Raspberry Pi, NVIDIA Jetson or any Linux device in one command.**
34
+ **Set up passwordless SSH in one command on any Linux or RouterOS device, such as Raspberry Pi, NVIDIA Jetson or MikroTik routers.**
34
35
 
35
36
  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
 
@@ -78,10 +79,12 @@ ssh mypi # no password, ever again
78
79
  ### Skip prompts
79
80
 
80
81
  ```bash
81
- ssh-keyup pi@192.168.1.23 mypi # user, host and alias in one go
82
+ ssh-keyup pi@192.168.1.23 mypi # user, host and alias in one go
83
+ ssh-keyup pi@192.168.1.23:2222 mypi # non-default SSH port
84
+ ssh-keyup admin@192.168.88.1 router # RouterOS, detected automatically
82
85
  ```
83
86
 
84
- Flags (`--host`, `--user`, `--alias`) work too, see `ssh-keyup --help`.
87
+ Flags (`--host`, `--user`, `--alias`, `--port`, `--os`) work too, see `ssh-keyup --help`
85
88
 
86
89
  ### Set up a fleet
87
90
 
@@ -113,7 +116,7 @@ ssh-keyup --remove mypi # deletes its key pair too
113
116
  flowchart LR
114
117
  run["ssh-keyup"] --> check["check connection"]
115
118
  check --> gen["generate ed25519 key<br/>~/.ssh/id_ed25519_mypi"]
116
- gen --> deploy["deploy public key<br/>target: ~/.ssh/authorized_keys"]
119
+ gen --> deploy["deploy public key<br/>~/.ssh/authorized_keys<br/>or /user/ssh-keys on RouterOS"]
117
120
  deploy --> config["update ssh config<br/>~/.ssh/config"]
118
121
  ```
119
122
 
@@ -125,6 +128,7 @@ flowchart LR
125
128
  - Deploys in a **single SSH session**, one password prompt total
126
129
  - Adds a named entry to `~/.ssh/config`, works instantly with `ssh <alias>` and VSCode Remote SSH
127
130
  - Checks host is **reachable** first, so typos surface before keys exist
131
+ - Detects **RouterOS** and imports the key its way
128
132
  - Recovers from **host key mismatches** after a reflash
129
133
  - **Entry management**, list or retire devices without leaving stale keys behind
130
134
  - **Zero dependencies**, standard library plus system OpenSSH
@@ -145,11 +149,12 @@ Works once. Same key lands on every device, `~/.ssh` keeps default permissions t
145
149
 
146
150
  ### Why not ssh-copy-id?
147
151
 
148
- `ssh-copy-id` appends a key to `authorized_keys` and stops there. Windows OpenSSH does not ship it at all.
152
+ `ssh-copy-id` appends a key to `authorized_keys` and stops there. Windows OpenSSH does not ship it at all and RouterOS has no `authorized_keys` to append to.
149
153
 
150
154
  | | ssh-keyup | ssh-copy-id |
151
155
  |---|:---:|:---:|
152
156
  | Works on Windows OpenSSH | yes | no |
157
+ | Works with RouterOS | yes | no |
153
158
  | Ed25519 key per device | yes | no |
154
159
  | Sets `authorized_keys` permissions | yes | yes |
155
160
  | Writes `~/.ssh/config` alias | yes | no |
@@ -174,8 +179,24 @@ Run `ssh-keyup` again. It detects a changed key, shows new fingerprint for confi
174
179
 
175
180
  ### Does `--remove` clean up entries on the device?
176
181
 
177
- No. It deletes local key pair and `~/.ssh/config` entry. Line in the device's `authorized_keys` stays until removed there.
182
+ No. It deletes local key pair and `~/.ssh/config` entry. Line in the device's `authorized_keys` (or `/user/ssh-keys` entry on RouterOS) stays until removed there.
178
183
 
179
184
  ### What devices are supported?
180
185
 
181
- Anything reachable over SSH: Raspberry Pi, NVIDIA Jetson, Orange Pi, VMs, servers.
186
+ Any Linux device reachable over SSH: Raspberry Pi, NVIDIA Jetson, Orange Pi, VMs, servers. Any RouterOS 7.12 or newer device, MikroTik routers or CHR alike, is detected from SSH banner and gets its own key import, `--os routeros` forces it.
187
+
188
+ ### How do I add an SSH key to a MikroTik router from Windows?
189
+
190
+ By hand on RouterOS 7:
191
+
192
+ ```powershell
193
+ ssh-keygen -t ed25519
194
+ scp $env:USERPROFILE\.ssh\id_ed25519.pub admin@192.168.88.1:
195
+ ssh admin@192.168.88.1 "/user/ssh-keys/import public-key-file=id_ed25519.pub user=admin"
196
+ ```
197
+
198
+ Works, with two password prompts and the default key shared across devices again. `ssh-keyup admin@192.168.88.1 router` does it in one session with one prompt, RouterOS is detected from SSH banner. Login user needs `policy` permission (`full` group has it) and firmware 7.12 or newer, older RouterOS rejects Ed25519 keys with `unable to load key file (wrong format or bad passphrase)`.
199
+
200
+ ### Why does RouterOS refuse my password over SSH after adding a key?
201
+
202
+ That is the default: once a user has a key, RouterOS stops accepting that user's password over SSH. WinBox and WebFig are unaffected, and password SSH can be turned back on under `/ip/ssh`.
@@ -5,7 +5,7 @@
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 in one command on any Linux or RouterOS device, such as Raspberry Pi, NVIDIA Jetson or MikroTik routers.**
9
9
 
10
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
11
 
@@ -53,10 +53,12 @@ ssh mypi # no password, ever again
53
53
  ### Skip prompts
54
54
 
55
55
  ```bash
56
- ssh-keyup pi@192.168.1.23 mypi # user, host and alias in one go
56
+ ssh-keyup pi@192.168.1.23 mypi # user, host and alias in one go
57
+ ssh-keyup pi@192.168.1.23:2222 mypi # non-default SSH port
58
+ ssh-keyup admin@192.168.88.1 router # RouterOS, detected automatically
57
59
  ```
58
60
 
59
- Flags (`--host`, `--user`, `--alias`) work too, see `ssh-keyup --help`.
61
+ Flags (`--host`, `--user`, `--alias`, `--port`, `--os`) work too, see `ssh-keyup --help`
60
62
 
61
63
  ### Set up a fleet
62
64
 
@@ -88,7 +90,7 @@ ssh-keyup --remove mypi # deletes its key pair too
88
90
  flowchart LR
89
91
  run["ssh-keyup"] --> check["check connection"]
90
92
  check --> gen["generate ed25519 key<br/>~/.ssh/id_ed25519_mypi"]
91
- gen --> deploy["deploy public key<br/>target: ~/.ssh/authorized_keys"]
93
+ gen --> deploy["deploy public key<br/>~/.ssh/authorized_keys<br/>or /user/ssh-keys on RouterOS"]
92
94
  deploy --> config["update ssh config<br/>~/.ssh/config"]
93
95
  ```
94
96
 
@@ -100,6 +102,7 @@ flowchart LR
100
102
  - Deploys in a **single SSH session**, one password prompt total
101
103
  - Adds a named entry to `~/.ssh/config`, works instantly with `ssh <alias>` and VSCode Remote SSH
102
104
  - Checks host is **reachable** first, so typos surface before keys exist
105
+ - Detects **RouterOS** and imports the key its way
103
106
  - Recovers from **host key mismatches** after a reflash
104
107
  - **Entry management**, list or retire devices without leaving stale keys behind
105
108
  - **Zero dependencies**, standard library plus system OpenSSH
@@ -120,11 +123,12 @@ Works once. Same key lands on every device, `~/.ssh` keeps default permissions t
120
123
 
121
124
  ### Why not ssh-copy-id?
122
125
 
123
- `ssh-copy-id` appends a key to `authorized_keys` and stops there. Windows OpenSSH does not ship it at all.
126
+ `ssh-copy-id` appends a key to `authorized_keys` and stops there. Windows OpenSSH does not ship it at all and RouterOS has no `authorized_keys` to append to.
124
127
 
125
128
  | | ssh-keyup | ssh-copy-id |
126
129
  |---|:---:|:---:|
127
130
  | Works on Windows OpenSSH | yes | no |
131
+ | Works with RouterOS | yes | no |
128
132
  | Ed25519 key per device | yes | no |
129
133
  | Sets `authorized_keys` permissions | yes | yes |
130
134
  | Writes `~/.ssh/config` alias | yes | no |
@@ -149,8 +153,24 @@ Run `ssh-keyup` again. It detects a changed key, shows new fingerprint for confi
149
153
 
150
154
  ### Does `--remove` clean up entries on the device?
151
155
 
152
- No. It deletes local key pair and `~/.ssh/config` entry. Line in the device's `authorized_keys` stays until removed there.
156
+ No. It deletes local key pair and `~/.ssh/config` entry. Line in the device's `authorized_keys` (or `/user/ssh-keys` entry on RouterOS) stays until removed there.
153
157
 
154
158
  ### What devices are supported?
155
159
 
156
- Anything reachable over SSH: Raspberry Pi, NVIDIA Jetson, Orange Pi, VMs, servers.
160
+ Any Linux device reachable over SSH: Raspberry Pi, NVIDIA Jetson, Orange Pi, VMs, servers. Any RouterOS 7.12 or newer device, MikroTik routers or CHR alike, is detected from SSH banner and gets its own key import, `--os routeros` forces it.
161
+
162
+ ### How do I add an SSH key to a MikroTik router from Windows?
163
+
164
+ By hand on RouterOS 7:
165
+
166
+ ```powershell
167
+ ssh-keygen -t ed25519
168
+ scp $env:USERPROFILE\.ssh\id_ed25519.pub admin@192.168.88.1:
169
+ ssh admin@192.168.88.1 "/user/ssh-keys/import public-key-file=id_ed25519.pub user=admin"
170
+ ```
171
+
172
+ Works, with two password prompts and the default key shared across devices again. `ssh-keyup admin@192.168.88.1 router` does it in one session with one prompt, RouterOS is detected from SSH banner. Login user needs `policy` permission (`full` group has it) and firmware 7.12 or newer, older RouterOS rejects Ed25519 keys with `unable to load key file (wrong format or bad passphrase)`.
173
+
174
+ ### Why does RouterOS refuse my password over SSH after adding a key?
175
+
176
+ That is the default: once a user has a key, RouterOS stops accepting that user's password over SSH. WinBox and WebFig are unaffected, and password SSH can be turned back on under `/ip/ssh`.
@@ -1,7 +1,7 @@
1
1
  [metadata]
2
2
  name = ssh-keyup
3
3
  version = attr: ssh_keyup.__version__
4
- description = Passwordless SSH setup and ssh-copy-id alternative for Raspberry Pi, NVIDIA Jetson or any Linux device
4
+ description = Passwordless SSH setup and ssh-copy-id alternative for any Linux or RouterOS device, such as Raspberry Pi, NVIDIA Jetson or MikroTik routers
5
5
  long_description = file: README.md
6
6
  long_description_content_type = text/markdown
7
7
  author = UAB Kurokesu
@@ -12,7 +12,7 @@ project_urls =
12
12
  Repository = https://github.com/Kurokesu/ssh-keyup
13
13
  Issues = https://github.com/Kurokesu/ssh-keyup/issues
14
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
15
+ keywords = ssh, ssh-keys, ssh-config, ssh-copy-id, passwordless-ssh, openssh, ed25519, raspberry-pi, rpi, jetson, mikrotik, routeros, iot, automation, vscode, remote-ssh, windows, linux
16
16
  classifiers =
17
17
  Development Status :: 5 - Production/Stable
18
18
  Environment :: Console
@@ -21,6 +21,7 @@ classifiers =
21
21
  Operating System :: Microsoft :: Windows
22
22
  Operating System :: POSIX :: Linux
23
23
  Programming Language :: Python :: 3
24
+ Topic :: System :: Networking
24
25
  Topic :: System :: Systems Administration
25
26
  Topic :: Utilities
26
27
 
@@ -1,14 +1,14 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: ssh-keyup
3
- Version: 1.2.0
4
- Summary: Passwordless SSH setup and ssh-copy-id alternative for Raspberry Pi, NVIDIA Jetson or any Linux device
3
+ Version: 1.3.0
4
+ Summary: Passwordless SSH setup and ssh-copy-id alternative for any Linux or RouterOS device, such as Raspberry Pi, NVIDIA Jetson or MikroTik routers
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
9
  Project-URL: Issues, https://github.com/Kurokesu/ssh-keyup/issues
10
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
11
+ Keywords: ssh,ssh-keys,ssh-config,ssh-copy-id,passwordless-ssh,openssh,ed25519,raspberry-pi,rpi,jetson,mikrotik,routeros,iot,automation,vscode,remote-ssh,windows,linux
12
12
  Classifier: Development Status :: 5 - Production/Stable
13
13
  Classifier: Environment :: Console
14
14
  Classifier: Intended Audience :: Developers
@@ -16,6 +16,7 @@ Classifier: Intended Audience :: System Administrators
16
16
  Classifier: Operating System :: Microsoft :: Windows
17
17
  Classifier: Operating System :: POSIX :: Linux
18
18
  Classifier: Programming Language :: Python :: 3
19
+ Classifier: Topic :: System :: Networking
19
20
  Classifier: Topic :: System :: Systems Administration
20
21
  Classifier: Topic :: Utilities
21
22
  Requires-Python: >=3.8
@@ -30,7 +31,7 @@ Dynamic: license-file
30
31
  ![Python](https://img.shields.io/badge/python-3.8%2B-brightgreen)
31
32
  ![Platform](https://img.shields.io/badge/platform-Windows%20%7C%20Linux-blue)
32
33
 
33
- **Set up passwordless SSH on Raspberry Pi, NVIDIA Jetson or any Linux device in one command.**
34
+ **Set up passwordless SSH in one command on any Linux or RouterOS device, such as Raspberry Pi, NVIDIA Jetson or MikroTik routers.**
34
35
 
35
36
  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
 
@@ -78,10 +79,12 @@ ssh mypi # no password, ever again
78
79
  ### Skip prompts
79
80
 
80
81
  ```bash
81
- ssh-keyup pi@192.168.1.23 mypi # user, host and alias in one go
82
+ ssh-keyup pi@192.168.1.23 mypi # user, host and alias in one go
83
+ ssh-keyup pi@192.168.1.23:2222 mypi # non-default SSH port
84
+ ssh-keyup admin@192.168.88.1 router # RouterOS, detected automatically
82
85
  ```
83
86
 
84
- Flags (`--host`, `--user`, `--alias`) work too, see `ssh-keyup --help`.
87
+ Flags (`--host`, `--user`, `--alias`, `--port`, `--os`) work too, see `ssh-keyup --help`
85
88
 
86
89
  ### Set up a fleet
87
90
 
@@ -113,7 +116,7 @@ ssh-keyup --remove mypi # deletes its key pair too
113
116
  flowchart LR
114
117
  run["ssh-keyup"] --> check["check connection"]
115
118
  check --> gen["generate ed25519 key<br/>~/.ssh/id_ed25519_mypi"]
116
- gen --> deploy["deploy public key<br/>target: ~/.ssh/authorized_keys"]
119
+ gen --> deploy["deploy public key<br/>~/.ssh/authorized_keys<br/>or /user/ssh-keys on RouterOS"]
117
120
  deploy --> config["update ssh config<br/>~/.ssh/config"]
118
121
  ```
119
122
 
@@ -125,6 +128,7 @@ flowchart LR
125
128
  - Deploys in a **single SSH session**, one password prompt total
126
129
  - Adds a named entry to `~/.ssh/config`, works instantly with `ssh <alias>` and VSCode Remote SSH
127
130
  - Checks host is **reachable** first, so typos surface before keys exist
131
+ - Detects **RouterOS** and imports the key its way
128
132
  - Recovers from **host key mismatches** after a reflash
129
133
  - **Entry management**, list or retire devices without leaving stale keys behind
130
134
  - **Zero dependencies**, standard library plus system OpenSSH
@@ -145,11 +149,12 @@ Works once. Same key lands on every device, `~/.ssh` keeps default permissions t
145
149
 
146
150
  ### Why not ssh-copy-id?
147
151
 
148
- `ssh-copy-id` appends a key to `authorized_keys` and stops there. Windows OpenSSH does not ship it at all.
152
+ `ssh-copy-id` appends a key to `authorized_keys` and stops there. Windows OpenSSH does not ship it at all and RouterOS has no `authorized_keys` to append to.
149
153
 
150
154
  | | ssh-keyup | ssh-copy-id |
151
155
  |---|:---:|:---:|
152
156
  | Works on Windows OpenSSH | yes | no |
157
+ | Works with RouterOS | yes | no |
153
158
  | Ed25519 key per device | yes | no |
154
159
  | Sets `authorized_keys` permissions | yes | yes |
155
160
  | Writes `~/.ssh/config` alias | yes | no |
@@ -174,8 +179,24 @@ Run `ssh-keyup` again. It detects a changed key, shows new fingerprint for confi
174
179
 
175
180
  ### Does `--remove` clean up entries on the device?
176
181
 
177
- No. It deletes local key pair and `~/.ssh/config` entry. Line in the device's `authorized_keys` stays until removed there.
182
+ No. It deletes local key pair and `~/.ssh/config` entry. Line in the device's `authorized_keys` (or `/user/ssh-keys` entry on RouterOS) stays until removed there.
178
183
 
179
184
  ### What devices are supported?
180
185
 
181
- Anything reachable over SSH: Raspberry Pi, NVIDIA Jetson, Orange Pi, VMs, servers.
186
+ Any Linux device reachable over SSH: Raspberry Pi, NVIDIA Jetson, Orange Pi, VMs, servers. Any RouterOS 7.12 or newer device, MikroTik routers or CHR alike, is detected from SSH banner and gets its own key import, `--os routeros` forces it.
187
+
188
+ ### How do I add an SSH key to a MikroTik router from Windows?
189
+
190
+ By hand on RouterOS 7:
191
+
192
+ ```powershell
193
+ ssh-keygen -t ed25519
194
+ scp $env:USERPROFILE\.ssh\id_ed25519.pub admin@192.168.88.1:
195
+ ssh admin@192.168.88.1 "/user/ssh-keys/import public-key-file=id_ed25519.pub user=admin"
196
+ ```
197
+
198
+ Works, with two password prompts and the default key shared across devices again. `ssh-keyup admin@192.168.88.1 router` does it in one session with one prompt, RouterOS is detected from SSH banner. Login user needs `policy` permission (`full` group has it) and firmware 7.12 or newer, older RouterOS rejects Ed25519 keys with `unable to load key file (wrong format or bad passphrase)`.
199
+
200
+ ### Why does RouterOS refuse my password over SSH after adding a key?
201
+
202
+ That is the default: once a user has a key, RouterOS stops accepting that user's password over SSH. WinBox and WebFig are unaffected, and password SSH can be turned back on under `/ip/ssh`.
@@ -2,17 +2,19 @@
2
2
  # SPDX-License-Identifier: GPL-3.0-or-later
3
3
  #
4
4
  # ssh-keyup - Passwordless SSH setup for
5
- # Raspberry Pi, NVIDIA Jetson, or any Linux device
5
+ # Raspberry Pi, NVIDIA Jetson, RouterOS or any Linux device
6
6
  #
7
7
  # Copyright (c) 2026, UAB Kurokesu. All rights reserved.
8
8
 
9
9
  # Makes modern annotation syntax runtime safe on Python 3.8
10
10
  from __future__ import annotations
11
11
 
12
- __version__ = "1.2.0"
12
+ __version__ = "1.3.0"
13
13
 
14
14
  import argparse
15
+ import base64
15
16
  import contextlib
17
+ import hashlib
16
18
  import ipaddress
17
19
  import os
18
20
  import re
@@ -22,6 +24,7 @@ import subprocess
22
24
  import sys
23
25
  import tempfile
24
26
  from datetime import datetime, timezone
27
+ from enum import Enum
25
28
  from pathlib import Path
26
29
  from shutil import which
27
30
 
@@ -33,7 +36,50 @@ else:
33
36
  import tty
34
37
 
35
38
  SSH_PORT = 22
39
+ MAX_PORT = 65535
36
40
  CONNECT_TIMEOUT = 3.0
41
+ BANNER_TIMEOUT = 1.0
42
+
43
+
44
+ class TargetOS(Enum):
45
+ """Device families that need their own key install command."""
46
+
47
+ LINUX = "linux"
48
+ ROUTEROS = "routeros"
49
+
50
+ @property
51
+ def label(self) -> str:
52
+ return {"linux": "Linux", "routeros": "RouterOS"}[self.value]
53
+
54
+
55
+ BANNER_MARKERS = {"ROSSSH": TargetOS.ROUTEROS}
56
+
57
+
58
+ def os_from_banner(banner: str) -> TargetOS:
59
+ """Map an SSH identification string to a target OS, Linux by default."""
60
+ for marker, target_os in BANNER_MARKERS.items():
61
+ if marker in banner:
62
+ return target_os
63
+ return TargetOS.LINUX
64
+
65
+
66
+ def os_from_ssh_verbose(stderr: str) -> TargetOS:
67
+ """Same detection from ssh -v output, which echoes the remote banner."""
68
+ m = re.search(r"remote software version (\S+)", stderr)
69
+ return os_from_banner(m.group(1)) if m else TargetOS.LINUX
70
+
71
+
72
+ def key_fingerprint(pub_key: str) -> str:
73
+ """SHA256 fingerprint of a public key line, padded as RouterOS shows it.
74
+
75
+ Empty for a malformed line, the device then rejects the key itself.
76
+ """
77
+ try:
78
+ blob = base64.b64decode(pub_key.split()[1], validate=True)
79
+ except (IndexError, ValueError):
80
+ return ""
81
+ digest = base64.b64encode(hashlib.sha256(blob).digest()).decode()
82
+ return f"SHA256:{digest}"
37
83
 
38
84
 
39
85
  class CLI:
@@ -323,11 +369,16 @@ class Runner:
323
369
  def run_capture(
324
370
  self, cmd: list[str] | str, **kwargs,
325
371
  ) -> tuple[int, str]:
326
- """Run a command, capture stderr, return (rc, text)."""
372
+ """Run command, capture both streams, return (rc, text).
373
+
374
+ stderr comes first, then stdout. Devices differ in which stream
375
+ their console errors use, RouterOS writes them to stdout.
376
+ """
327
377
  args, shell = self._subprocess_args(cmd)
328
378
  r = subprocess.run(args, shell=shell, check=False,
329
- stderr=subprocess.PIPE, **kwargs)
330
- return r.returncode, (r.stderr or b"").decode(errors="replace")
379
+ capture_output=True, **kwargs)
380
+ text = (r.stderr or b"") + (r.stdout or b"")
381
+ return r.returncode, text.decode(errors="replace")
331
382
 
332
383
  def run_stdout(
333
384
  self, cmd: list[str] | str, **kwargs,
@@ -568,39 +619,120 @@ class Deployer:
568
619
  return False
569
620
  return True
570
621
 
622
+ # ssh -v chatter that is not an error and not remote output
623
+ _SSH_NOISE = ("debug1:", "OpenSSH_", "Authenticated to ",
624
+ "Transferred: ", "Bytes per second: ",
625
+ "Warning: Permanently added")
626
+
627
+ @staticmethod
628
+ def _is_authenticated(stderr: str) -> bool:
629
+ """Return True if verbose stderr shows login succeeded."""
630
+ return "Authenticated to " in stderr
631
+
632
+ @staticmethod
633
+ def _error_lines(stderr: str) -> list[str]:
634
+ """Keep ssh errors and remote output, drop -v chatter and repeats."""
635
+ seen: set[str] = set()
636
+ lines = []
637
+ for line in stderr.strip().splitlines():
638
+ if (not line.strip() or line.startswith(Deployer._SSH_NOISE)
639
+ or line in seen):
640
+ continue
641
+ seen.add(line)
642
+ lines.append(line)
643
+ return lines
644
+
645
+ @staticmethod
646
+ def _report_failure(stderr: str, target_os: TargetOS) -> None:
647
+ """Explain failed deploy, a remote error is not a login error."""
648
+ if Deployer._is_authenticated(stderr):
649
+ cli.fail("\nLogged in, but install command failed on device.")
650
+ else:
651
+ cli.fail("\nSSH connection failed. Check host and credentials.")
652
+ for line in Deployer._error_lines(stderr):
653
+ cli.ssh_info(line)
654
+ if target_os is not TargetOS.ROUTEROS:
655
+ return
656
+ if "unable to load key" in stderr:
657
+ cli.hint("Ed25519 keys need RouterOS 7.12 or newer.")
658
+ elif "not enough permissions" in stderr:
659
+ cli.hint("User needs the policy permission, "
660
+ "the full group has it.")
661
+
662
+ @staticmethod
663
+ def _succeeded(rc: int, output: str, target_os: TargetOS) -> bool:
664
+ """Judge install by exit status, plus remote output on RouterOS.
665
+
666
+ RouterOS reports errors as text with exit status 0 and a working
667
+ install prints nothing, so any remote output means failure there.
668
+ """
669
+ if rc != 0:
670
+ return False
671
+ if target_os is TargetOS.ROUTEROS:
672
+ return not Deployer._error_lines(output)
673
+ return True
674
+
675
+ @staticmethod
676
+ def _install_command(target_os: TargetOS, user: str,
677
+ pub_key: str) -> tuple[str, bytes]:
678
+ """Return remote install command and what to feed its stdin.
679
+
680
+ RouterOS console runs whatever arrives on stdin, so it gets none.
681
+ """
682
+ if target_os is TargetOS.LINUX:
683
+ cmd = (
684
+ "mkdir -p ~/.ssh && chmod 700 ~/.ssh && "
685
+ "key=$(cat) && "
686
+ "if ! grep -qF \"$key\" ~/.ssh/authorized_keys 2>/dev/null; "
687
+ "then printf '%s\\n' \"$key\" >> ~/.ssh/authorized_keys; fi "
688
+ "&& chmod 600 ~/.ssh/authorized_keys"
689
+ )
690
+ return cmd, pub_key.encode()
691
+ elif target_os is TargetOS.ROUTEROS:
692
+ # Pre-7.20 firmware lacks fingerprint, n stays 0 and add runs.
693
+ # Add sits outside on-error so its message is not swallowed.
694
+ fp = key_fingerprint(pub_key)
695
+ cmd = (
696
+ ":local n 0; "
697
+ ":do { :set n [:len [/user/ssh-keys/find where "
698
+ f'user="{user}" and fingerprint="{fp}"]] }} on-error={{}}; '
699
+ ":if ($n = 0) do={ "
700
+ f'/user/ssh-keys/add user="{user}" key="{pub_key}" }}'
701
+ )
702
+ return cmd, b""
703
+ else:
704
+ raise ValueError(f"unhandled target OS {target_os}")
705
+
571
706
  @staticmethod
572
707
  def _ssh_cmd(runner: Runner, remote: str, install_cmd: str,
573
- pub_key: str, accept_new: bool = False,
708
+ stdin: bytes, accept_new: bool = False,
574
709
  port: int = SSH_PORT) -> tuple[int, str]:
575
- """Run the SSH deploy command."""
710
+ """Run SSH deploy command, verbose so failures can be explained."""
576
711
  policy = "accept-new" if accept_new else "yes"
577
- cmd = ["ssh"]
578
- if not accept_new:
579
- cmd.append("-v")
712
+ cmd = ["ssh", "-v"]
580
713
  if port != SSH_PORT:
581
714
  cmd.extend(["-p", str(port)])
582
715
  cmd.extend(["-o", f"StrictHostKeyChecking={policy}",
583
716
  remote, install_cmd])
584
- return runner.run_capture(cmd, input=pub_key.encode())
717
+ return runner.run_capture(cmd, input=stdin)
585
718
 
586
719
  @staticmethod
587
720
  def deploy(runner: Runner, user: str, host: str, pub_path: Path,
588
- port: int = SSH_PORT) -> bool:
589
- """Deploy the public key to the remote host in a single SSH session."""
721
+ port: int = SSH_PORT,
722
+ target_os: TargetOS = TargetOS.LINUX) -> TargetOS | None:
723
+ """Deploy public key in a single SSH session.
724
+
725
+ Return target OS the key landed on, None on failure. Differs
726
+ from the one passed in when fallback detection kicked in.
727
+ """
590
728
  remote = f"{user}@{host}"
591
729
  pub_key = pub_path.read_text(encoding="utf-8").strip()
592
730
  shown = remote if port == SSH_PORT else f"{remote}:{port}"
593
731
  cli.status(f"Deploying key to {shown} ...")
594
732
 
595
- install_cmd = (
596
- "mkdir -p ~/.ssh && chmod 700 ~/.ssh && "
597
- "key=$(cat) && "
598
- "if ! grep -qF \"$key\" ~/.ssh/authorized_keys 2>/dev/null; then "
599
- "printf '%s\\n' \"$key\" >> ~/.ssh/authorized_keys; fi && "
600
- "chmod 600 ~/.ssh/authorized_keys"
601
- )
602
-
603
- rc, stderr = Deployer._ssh_cmd(runner, remote, install_cmd, pub_key,
733
+ install_cmd, stdin = Deployer._install_command(target_os, user,
734
+ pub_key)
735
+ rc, stderr = Deployer._ssh_cmd(runner, remote, install_cmd, stdin,
604
736
  port=port)
605
737
 
606
738
  if rc != 0 and Deployer._is_host_key_changed(stderr):
@@ -608,46 +740,40 @@ class Deployer:
608
740
  if not line.startswith("debug1:"):
609
741
  cli.ssh_warning(line)
610
742
  cli.msg()
611
- if cli.ask_yn("Remove old host key and retry?"):
612
- cli.status(f"Removing old host key for {host} ...")
613
- # Non-default ports are keyed as [host]:port in known_hosts
614
- known = host if port == SSH_PORT else f"[{host}]:{port}"
615
- runner.run(["ssh-keygen", "-R", known])
616
- rc, stderr = Deployer._ssh_cmd(
617
- runner, remote, install_cmd, pub_key, accept_new=True,
618
- port=port)
619
- if rc != 0:
620
- cli.fail(
621
- "\nStill can't connect. Check host and credentials."
622
- )
623
- return False
624
- else:
743
+ if not cli.ask_yn("Remove old host key and retry?"):
625
744
  cli.msg(f"\nAborted. To fix manually:\n ssh-keygen -R {host}")
626
- return False
745
+ return None
746
+ cli.status(f"Removing old host key for {host} ...")
747
+ # Non-default ports are keyed as [host]:port in known_hosts
748
+ known = host if port == SSH_PORT else f"[{host}]:{port}"
749
+ runner.run(["ssh-keygen", "-R", known])
750
+ rc, stderr = Deployer._ssh_cmd(
751
+ runner, remote, install_cmd, stdin, accept_new=True,
752
+ port=port)
627
753
  elif rc != 0 and Deployer._is_unknown_host(stderr):
628
754
  if not Deployer._handle_unknown_host(host, stderr):
629
- return False
755
+ return None
630
756
  rc, stderr = Deployer._ssh_cmd(
631
- runner, remote, install_cmd, pub_key, accept_new=True,
757
+ runner, remote, install_cmd, stdin, accept_new=True,
632
758
  port=port)
633
- if rc != 0:
634
- cli.fail(
635
- "\nSSH connection failed. Check host and credentials."
636
- )
637
- return False
638
- elif rc != 0:
639
- cli.fail(
640
- "\nSSH connection failed. Check host and credentials."
641
- )
642
- if stderr.strip():
643
- seen: set[str] = set()
644
- for line in stderr.strip().splitlines():
645
- if line not in seen and not line.startswith("debug1:"):
646
- seen.add(line)
647
- cli.ssh_info(line)
648
- return False
649
759
 
650
- return True
760
+ # Banner read missed or skipped, ssh -v still names the remote
761
+ if (rc != 0 and target_os is TargetOS.LINUX
762
+ and Deployer._is_authenticated(stderr)):
763
+ detected = os_from_ssh_verbose(stderr)
764
+ if detected is not target_os:
765
+ cli.hint(f"{detected.label} detected, retrying")
766
+ target_os = detected
767
+ install_cmd, stdin = Deployer._install_command(
768
+ target_os, user, pub_key)
769
+ rc, stderr = Deployer._ssh_cmd(
770
+ runner, remote, install_cmd, stdin, accept_new=True,
771
+ port=port)
772
+
773
+ if not Deployer._succeeded(rc, stderr, target_os):
774
+ Deployer._report_failure(stderr, target_os)
775
+ return None
776
+ return target_os
651
777
 
652
778
 
653
779
  def sanitize_alias(name: str, quiet: bool = False) -> str:
@@ -678,48 +804,92 @@ def split_target(target: str) -> tuple[str | None, str]:
678
804
  return None, target
679
805
 
680
806
 
681
- def probe_port(host: str, port: int) -> tuple[str, str] | None:
682
- """Try a TCP connect, return (reason, detail) on failure."""
807
+ def split_host_port(host: str) -> tuple[str, int | None]:
808
+ """Split host[:port], IPv6 literals need brackets to carry a port."""
809
+ if host.startswith("["):
810
+ inner, sep, rest = host[1:].partition("]")
811
+ if not sep or (rest and not rest.startswith(":")):
812
+ raise ValueError(f"Invalid host '{host}'.")
813
+ if not rest:
814
+ return inner, None
815
+ host, port_text = inner, rest[1:]
816
+ elif host.count(":") == 1:
817
+ host, _, port_text = host.partition(":")
818
+ else:
819
+ return host, None
820
+ if not port_text.isdigit() or not 1 <= int(port_text) <= MAX_PORT:
821
+ raise ValueError(f"Invalid port '{port_text}'.")
822
+ return host, int(port_text)
823
+
824
+
825
+ def read_banner(sock: socket.socket) -> str:
826
+ """Read server identification line, empty if none arrives in time."""
827
+ sock.settimeout(BANNER_TIMEOUT)
683
828
  try:
684
- with socket.create_connection((host, port), CONNECT_TIMEOUT):
685
- return None
829
+ data = sock.recv(256)
830
+ except OSError:
831
+ return ""
832
+ for line in data.decode(errors="replace").splitlines():
833
+ if line.startswith("SSH-"):
834
+ return line.strip()
835
+ return ""
836
+
837
+
838
+ def probe_port(host: str, port: int) -> tuple[str, tuple[str, str] | None]:
839
+ """Try a TCP connect and read the SSH banner.
840
+
841
+ Return (banner, None) on success, ("", (reason, detail)) on failure.
842
+ """
843
+ try:
844
+ with socket.create_connection((host, port), CONNECT_TIMEOUT) as sock:
845
+ return read_banner(sock), None
686
846
  except socket.gaierror:
687
- return (f"Could not resolve hostname '{host}'.",
688
- "Check spelling or use an IP address instead.")
847
+ return "", (f"Could not resolve hostname '{host}'.",
848
+ "Check spelling or use an IP address instead.")
689
849
  except ConnectionRefusedError:
690
- return (f"Connection refused by {host} on port {port}.",
691
- "Host is up but no SSH server is listening.")
850
+ return "", (f"Connection refused by {host} on port {port}.",
851
+ "Host is up but no SSH server is listening.")
692
852
  except socket.timeout:
693
- return (f"No response from {host} on port {port}.",
694
- "Device may be off or on a different network.")
853
+ return "", (f"No response from {host} on port {port}.",
854
+ "Device may be off or on a different network.")
695
855
  except OSError as ex:
696
- return f"Cannot reach {host}.", str(ex)
856
+ return "", (f"Cannot reach {host}.", str(ex))
697
857
 
698
858
 
699
- def resolve_ssh_target(runner: Runner, host: str) -> tuple[str, int] | None:
700
- """Resolve host through ssh config, return effective (hostname, port)."""
701
- rc, out = runner.run_stdout(["ssh", "-G", host],
702
- stderr=subprocess.DEVNULL)
859
+ def resolve_ssh_target(
860
+ runner: Runner, host: str, port: int | None = None,
861
+ ) -> tuple[str, int] | None:
862
+ """Resolve host through ssh config, return effective (hostname, port).
863
+
864
+ Explicit port goes to ssh as -p, so command line beats config the
865
+ same way it does for ssh itself.
866
+ """
867
+ cmd = ["ssh", "-G"]
868
+ if port:
869
+ cmd.extend(["-p", str(port)])
870
+ rc, out = runner.run_stdout(cmd + [host], stderr=subprocess.DEVNULL)
703
871
  if rc != 0:
704
872
  return None
705
- hostname, port = None, None
873
+ hostname, found = None, None
706
874
  for line in out.splitlines():
707
875
  key, _, value = line.partition(" ")
708
876
  if key == "hostname":
709
877
  hostname = value.strip()
710
878
  elif key == "port":
711
879
  with contextlib.suppress(ValueError):
712
- port = int(value)
880
+ found = int(value)
713
881
  if not hostname:
714
882
  return None
715
- return hostname, port or SSH_PORT
883
+ return hostname, found or port or SSH_PORT
716
884
 
717
885
 
718
- def resolve_host(runner: Runner, host: str) -> tuple[str, int]:
886
+ def resolve_host(
887
+ runner: Runner, host: str, port: int | None = None,
888
+ ) -> tuple[str, int]:
719
889
  """Resolve a typed host through ssh config to (hostname, port)."""
720
- target = resolve_ssh_target(runner, host)
890
+ target = resolve_ssh_target(runner, host, port)
721
891
  if not target:
722
- return host, SSH_PORT
892
+ return host, port or SSH_PORT
723
893
 
724
894
  rhost, rport = target
725
895
  if rhost.lower() != host.lower():
@@ -728,13 +898,16 @@ def resolve_host(runner: Runner, host: str) -> tuple[str, int]:
728
898
  return rhost, rport
729
899
 
730
900
 
731
- def check_reachable(host: str, port: int = SSH_PORT) -> None:
732
- """Probe SSH port. On failure explain why and offer to continue."""
901
+ def check_reachable(host: str, port: int = SSH_PORT) -> str:
902
+ """Probe SSH port and return its banner.
903
+
904
+ On failure explain why and offer to continue, banner is then empty.
905
+ """
733
906
  cli.status("Checking connection ... ", end="")
734
- failure = probe_port(host, port)
907
+ banner, failure = probe_port(host, port)
735
908
  if failure is None:
736
909
  cli.ok()
737
- return
910
+ return banner
738
911
 
739
912
  cli.failed()
740
913
  cli.warn(failure[0])
@@ -743,6 +916,7 @@ def check_reachable(host: str, port: int = SSH_PORT) -> None:
743
916
  if not cli.ask_yn("Continue anyway?"):
744
917
  cli.cancel()
745
918
  sys.exit(0)
919
+ return ""
746
920
 
747
921
 
748
922
  _DESCRIPTION = (
@@ -755,6 +929,8 @@ _EXAMPLES = [
755
929
  ("ssh-keyup", "interactive mode"),
756
930
  ("ssh-keyup pi@192.168.1.23 mypi", "user, host and alias"),
757
931
  ("ssh-keyup trinity@rpi-5.local", "alias defaults to rpi-5"),
932
+ ("ssh-keyup pi@192.168.1.23:2222 mypi", "non-default SSH port"),
933
+ ("ssh-keyup admin@192.168.88.1 router", "RouterOS, detected"),
758
934
  ("ssh-keyup 192.168.1.23", "prompts for username and alias"),
759
935
  ("ssh-keyup --host rpi-5 --user pi --alias mypi", "flags work too"),
760
936
  ("ssh-keyup --list", "show managed entries"),
@@ -788,6 +964,10 @@ def parse_args() -> argparse.Namespace:
788
964
  help="login username on the remote device")
789
965
  p.add_argument("--alias",
790
966
  help="friendly name for ~/.ssh/config (default: hostname)")
967
+ p.add_argument("--port", type=int, metavar="PORT",
968
+ help="SSH port of the remote device (default: 22)")
969
+ p.add_argument("--os", choices=[o.value for o in TargetOS],
970
+ help="target OS, detected from SSH banner by default")
791
971
  p.add_argument("--list", action="store_true",
792
972
  help="list entries managed by ssh-keyup")
793
973
  p.add_argument("--remove", metavar="ALIAS",
@@ -797,9 +977,11 @@ def parse_args() -> argparse.Namespace:
797
977
  if args.list and args.remove:
798
978
  p.error("--list and --remove cannot be combined")
799
979
  if ((args.list or args.remove)
800
- and any((args.target, args.alias_pos,
801
- args.host, args.user, args.alias))):
980
+ and any((args.target, args.alias_pos, args.host, args.user,
981
+ args.alias, args.port, args.os))):
802
982
  p.error("--list/--remove cannot be combined with setup arguments")
983
+ if args.port is not None and not 1 <= args.port <= MAX_PORT:
984
+ p.error(f"invalid port {args.port}")
803
985
 
804
986
  if args.target:
805
987
  user, host = split_target(args.target)
@@ -820,14 +1002,26 @@ def parse_args() -> argparse.Namespace:
820
1002
 
821
1003
  def gather_input(
822
1004
  args: argparse.Namespace, runner: Runner,
823
- ) -> tuple[str, str, str, int]:
824
- """Collect host, username, alias and port from args or prompts."""
1005
+ ) -> tuple[str, str, str, int, TargetOS]:
1006
+ """Collect host, user, alias, port and target OS from args or prompts."""
825
1007
  typed = cli.prompt("Remote host", args.host, hint="IP or name")
826
1008
  if not typed:
827
1009
  cli.fatal("No host provided.")
828
-
829
- host, port = resolve_host(runner, typed)
830
- check_reachable(host, port)
1010
+ try:
1011
+ typed, typed_port = split_host_port(typed)
1012
+ except ValueError as ex:
1013
+ cli.fatal(str(ex))
1014
+ if typed_port and args.port and typed_port != args.port:
1015
+ cli.fatal("Port given both in host and as --port.")
1016
+
1017
+ host, port = resolve_host(runner, typed, typed_port or args.port)
1018
+ banner = check_reachable(host, port)
1019
+ if args.os:
1020
+ target_os = TargetOS(args.os)
1021
+ else:
1022
+ target_os = os_from_banner(banner)
1023
+ if target_os is not TargetOS.LINUX:
1024
+ cli.hint(f"{target_os.label} detected")
831
1025
 
832
1026
  user = cli.prompt("Username", args.user)
833
1027
  if not user:
@@ -845,7 +1039,7 @@ def gather_input(
845
1039
 
846
1040
  alias = sanitize_alias(alias)
847
1041
 
848
- return host, user, alias, port
1042
+ return host, user, alias, port, target_os
849
1043
 
850
1044
 
851
1045
  def generate_key(runner: Runner, key_path: Path) -> None:
@@ -890,7 +1084,7 @@ def main() -> None:
890
1084
  runner = Runner()
891
1085
  runner.check()
892
1086
 
893
- host, user, alias, port = gather_input(args, runner)
1087
+ host, user, alias, port, target_os = gather_input(args, runner)
894
1088
  file_alias = alias.replace("-", "_")
895
1089
 
896
1090
  cli.separator()
@@ -928,13 +1122,14 @@ def main() -> None:
928
1122
  if key_generated:
929
1123
  discard_keys(key_path, pub_path)
930
1124
  cli.fatal(f"SSH config update failed: {ex}")
931
- deployed = Deployer.deploy(runner, user, host, pub_path, port)
1125
+ deployed = Deployer.deploy(runner, user, host, pub_path, port,
1126
+ target_os)
932
1127
  except KeyboardInterrupt:
933
1128
  if key_generated:
934
1129
  cli.msg()
935
1130
  discard_keys(key_path, pub_path)
936
1131
  raise
937
- if not deployed:
1132
+ if deployed is None:
938
1133
  if key_generated:
939
1134
  discard_keys(key_path, pub_path)
940
1135
  sys.exit(1)
@@ -947,7 +1142,11 @@ def main() -> None:
947
1142
  cli.msg(f"Config updated {ssh_config}")
948
1143
 
949
1144
  cli.separator()
950
- cli.success(f"SSH key deployed for '{alias}'.\n")
1145
+ cli.success(f"SSH key deployed for '{alias}'.")
1146
+ if deployed is TargetOS.ROUTEROS:
1147
+ cli.hint(f"By default RouterOS turns off password SSH login for "
1148
+ f"{user} once a key exists (WinBox, WebFig unaffected).")
1149
+ cli.msg()
951
1150
  except KeyboardInterrupt:
952
1151
  sys.stdout.write(CLI.SHOW_CUR)
953
1152
  sys.stdout.flush()
File without changes
File without changes