sshcnfgr 0.1.0b1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- sshcnfgr/__init__.py +5 -0
- sshcnfgr/cli.py +182 -0
- sshcnfgr/dedup.py +363 -0
- sshcnfgr/dedup_screen.py +466 -0
- sshcnfgr/generator.py +83 -0
- sshcnfgr/gui/__init__.py +29 -0
- sshcnfgr/gui/dedup_dialog.py +462 -0
- sshcnfgr/gui/main_window.py +1225 -0
- sshcnfgr/identities.py +95 -0
- sshcnfgr/importer.py +152 -0
- sshcnfgr/logging_conf.py +45 -0
- sshcnfgr/model.py +231 -0
- sshcnfgr/paths.py +37 -0
- sshcnfgr/settings.py +87 -0
- sshcnfgr/store.py +222 -0
- sshcnfgr/tui.py +471 -0
- sshcnfgr/tui.tcss +105 -0
- sshcnfgr-0.1.0b1.dist-info/METADATA +205 -0
- sshcnfgr-0.1.0b1.dist-info/RECORD +22 -0
- sshcnfgr-0.1.0b1.dist-info/WHEEL +4 -0
- sshcnfgr-0.1.0b1.dist-info/entry_points.txt +2 -0
- sshcnfgr-0.1.0b1.dist-info/licenses/LICENSE +21 -0
sshcnfgr/store.py
ADDED
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import shutil
|
|
4
|
+
import tomllib
|
|
5
|
+
from datetime import datetime
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
import tomli_w
|
|
9
|
+
|
|
10
|
+
from .model import HostDatabase, HostEntry, HostGroup, IdentityProfile
|
|
11
|
+
from .paths import (
|
|
12
|
+
DB_PATH,
|
|
13
|
+
LEGACY_DB_PATH,
|
|
14
|
+
SSH_DIR,
|
|
15
|
+
ensure_private_dir,
|
|
16
|
+
set_private_permissions,
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def create_backup(path: Path) -> Path | None:
|
|
21
|
+
"""Erstellt vor dem Ueberschreiben ein Zeitstempel-Backup einer vorhandenen Datei."""
|
|
22
|
+
if not path.exists():
|
|
23
|
+
return None
|
|
24
|
+
|
|
25
|
+
timestamp = datetime.now().strftime("%Y%m%d-%H%M%S")
|
|
26
|
+
backup_path = path.with_name(f"{path.name}.bak.{timestamp}")
|
|
27
|
+
counter = 1
|
|
28
|
+
while backup_path.exists():
|
|
29
|
+
backup_path = path.with_name(f"{path.name}.bak.{timestamp}-{counter}")
|
|
30
|
+
counter += 1
|
|
31
|
+
|
|
32
|
+
shutil.copy2(path, backup_path)
|
|
33
|
+
set_private_permissions(backup_path)
|
|
34
|
+
return backup_path
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _host_to_dict(host: HostEntry) -> dict[str, object]:
|
|
38
|
+
payload: dict[str, object] = {
|
|
39
|
+
"id": host.id,
|
|
40
|
+
"name": host.name,
|
|
41
|
+
"enabled": host.enabled,
|
|
42
|
+
"host_name": host.host_name,
|
|
43
|
+
"groups": host.groups,
|
|
44
|
+
"tags": host.tags,
|
|
45
|
+
"extra_options": host.extra_options,
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
# tomli-w serialisiert kein None, daher optionale Felder nur bei Wert schreiben.
|
|
49
|
+
if host.user is not None:
|
|
50
|
+
payload["user"] = host.user
|
|
51
|
+
if host.port is not None:
|
|
52
|
+
payload["port"] = host.port
|
|
53
|
+
if host.identity is not None:
|
|
54
|
+
payload["identity"] = host.identity
|
|
55
|
+
if host.identity_file is not None:
|
|
56
|
+
payload["identity_file"] = host.identity_file
|
|
57
|
+
|
|
58
|
+
return payload
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _group_to_dict(group: HostGroup) -> dict[str, object]:
|
|
62
|
+
payload: dict[str, object] = {"name": group.name}
|
|
63
|
+
if group.description:
|
|
64
|
+
payload["description"] = group.description
|
|
65
|
+
if group.identity:
|
|
66
|
+
payload["identity"] = group.identity
|
|
67
|
+
return payload
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _identity_to_dict(identity: IdentityProfile) -> dict[str, object]:
|
|
71
|
+
payload: dict[str, object] = {
|
|
72
|
+
"name": identity.name,
|
|
73
|
+
"identity_file": identity.identity_file,
|
|
74
|
+
"source": identity.source,
|
|
75
|
+
"enabled": identity.enabled,
|
|
76
|
+
}
|
|
77
|
+
if identity.public_key_file:
|
|
78
|
+
payload["public_key_file"] = identity.public_key_file
|
|
79
|
+
if identity.public_key_preview:
|
|
80
|
+
payload["public_key_preview"] = identity.public_key_preview
|
|
81
|
+
return payload
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _host_from_dict(data: dict[str, object]) -> HostEntry:
|
|
85
|
+
return HostEntry(
|
|
86
|
+
id=str(data.get("id", "")) or HostEntry().id,
|
|
87
|
+
name=str(data.get("name", "")),
|
|
88
|
+
enabled=bool(data.get("enabled", True)),
|
|
89
|
+
host_name=str(data.get("host_name", "")),
|
|
90
|
+
user=str(data["user"]) if data.get("user") is not None else None,
|
|
91
|
+
port=int(data["port"]) if data.get("port") is not None else None,
|
|
92
|
+
identity=str(data["identity"]) if data.get("identity") is not None else None,
|
|
93
|
+
identity_file=str(data["identity_file"]) if data.get("identity_file") is not None else None,
|
|
94
|
+
groups=[str(group) for group in (data.get("groups") or [])],
|
|
95
|
+
tags=[str(tag) for tag in (data.get("tags") or [])],
|
|
96
|
+
extra_options={
|
|
97
|
+
str(k): str(v) for k, v in (data.get("extra_options") or {}).items() # type: ignore[arg-type]
|
|
98
|
+
},
|
|
99
|
+
)
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def _group_from_dict(data: dict[str, object]) -> HostGroup:
|
|
103
|
+
return HostGroup(
|
|
104
|
+
name=str(data.get("name", "")),
|
|
105
|
+
description=str(data.get("description", "")) if data.get("description") else "",
|
|
106
|
+
identity=str(data.get("identity", "")) if data.get("identity") else None,
|
|
107
|
+
)
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def _identity_from_dict(data: dict[str, object]) -> IdentityProfile:
|
|
111
|
+
return IdentityProfile(
|
|
112
|
+
name=str(data.get("name", "")),
|
|
113
|
+
identity_file=str(data.get("identity_file", "")),
|
|
114
|
+
source=str(data.get("source", "manual")),
|
|
115
|
+
public_key_file=str(data.get("public_key_file", ""))
|
|
116
|
+
if data.get("public_key_file")
|
|
117
|
+
else None,
|
|
118
|
+
public_key_preview=str(data.get("public_key_preview", ""))
|
|
119
|
+
if data.get("public_key_preview")
|
|
120
|
+
else None,
|
|
121
|
+
enabled=bool(data.get("enabled", True)),
|
|
122
|
+
)
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def load_database(path: Path | None = None) -> HostDatabase:
|
|
126
|
+
target = path if path is not None else DB_PATH
|
|
127
|
+
if not target.exists():
|
|
128
|
+
# Nahtlose Migration: falls ~/.ssh/sshcnfgr.toml noch fehlt, aber die alte
|
|
129
|
+
# ~/.config/sshcnfgr/hosts.toml vorhanden ist, diese einmalig als Quelle laden.
|
|
130
|
+
if path is None and LEGACY_DB_PATH.exists():
|
|
131
|
+
target = LEGACY_DB_PATH
|
|
132
|
+
else:
|
|
133
|
+
return HostDatabase()
|
|
134
|
+
|
|
135
|
+
raw = tomllib.loads(target.read_text(encoding="utf-8"))
|
|
136
|
+
group_items = raw.get("groups", [])
|
|
137
|
+
identity_items = raw.get("identities", [])
|
|
138
|
+
global_options_raw = raw.get("global_options", {})
|
|
139
|
+
host_items = raw.get("hosts", [])
|
|
140
|
+
ui_raw = raw.get("ui", {})
|
|
141
|
+
|
|
142
|
+
global_options: dict[str, str] = {}
|
|
143
|
+
if isinstance(global_options_raw, dict):
|
|
144
|
+
global_options = {str(k): str(v) for k, v in global_options_raw.items()}
|
|
145
|
+
|
|
146
|
+
ui: dict[str, str | bool] = {}
|
|
147
|
+
if isinstance(ui_raw, dict):
|
|
148
|
+
for k, v in ui_raw.items():
|
|
149
|
+
if isinstance(v, (str, bool)):
|
|
150
|
+
ui[str(k)] = v
|
|
151
|
+
|
|
152
|
+
groups: list[HostGroup] = []
|
|
153
|
+
for item in group_items:
|
|
154
|
+
if isinstance(item, dict):
|
|
155
|
+
group = _group_from_dict(item)
|
|
156
|
+
if group.name:
|
|
157
|
+
groups.append(group)
|
|
158
|
+
|
|
159
|
+
identities: list[IdentityProfile] = []
|
|
160
|
+
for item in identity_items:
|
|
161
|
+
if isinstance(item, dict):
|
|
162
|
+
identity = _identity_from_dict(item)
|
|
163
|
+
if identity.name and identity.identity_file:
|
|
164
|
+
identities.append(identity)
|
|
165
|
+
|
|
166
|
+
hosts: list[HostEntry] = []
|
|
167
|
+
for item in host_items:
|
|
168
|
+
if isinstance(item, dict):
|
|
169
|
+
hosts.append(_host_from_dict(item))
|
|
170
|
+
|
|
171
|
+
# Rueckwaertskompatibilitaet: existierende TOML ohne [[groups]]
|
|
172
|
+
# wird automatisch mit referenzierten Gruppen aufgefuellt.
|
|
173
|
+
db = HostDatabase(
|
|
174
|
+
groups=groups,
|
|
175
|
+
identities=identities,
|
|
176
|
+
global_options=global_options,
|
|
177
|
+
hosts=hosts,
|
|
178
|
+
ui=ui,
|
|
179
|
+
)
|
|
180
|
+
referenced_groups = sorted({group for host in hosts for group in host.groups})
|
|
181
|
+
db.ensure_groups(referenced_groups)
|
|
182
|
+
|
|
183
|
+
return db
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def _read_existing_ui(path: Path) -> dict[str, str | bool]:
|
|
187
|
+
if not path.exists():
|
|
188
|
+
return {}
|
|
189
|
+
try:
|
|
190
|
+
raw = tomllib.loads(path.read_text(encoding="utf-8"))
|
|
191
|
+
except (OSError, tomllib.TOMLDecodeError):
|
|
192
|
+
return {}
|
|
193
|
+
ui_raw = raw.get("ui", {})
|
|
194
|
+
if not isinstance(ui_raw, dict):
|
|
195
|
+
return {}
|
|
196
|
+
return {str(k): v for k, v in ui_raw.items() if isinstance(v, (str, bool))}
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def save_database(db: HostDatabase, path: Path = DB_PATH, *, backup: bool = True) -> None:
|
|
200
|
+
if path.parent == SSH_DIR:
|
|
201
|
+
ensure_private_dir(path.parent)
|
|
202
|
+
else:
|
|
203
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
204
|
+
|
|
205
|
+
ui_section = db.ui if db.ui else _read_existing_ui(path)
|
|
206
|
+
|
|
207
|
+
if backup:
|
|
208
|
+
create_backup(path)
|
|
209
|
+
|
|
210
|
+
payload: dict[str, object] = {
|
|
211
|
+
"groups": [_group_to_dict(group) for group in db.sorted_groups()],
|
|
212
|
+
"identities": [_identity_to_dict(identity) for identity in db.sorted_identities()],
|
|
213
|
+
"global_options": db.global_options,
|
|
214
|
+
"hosts": [_host_to_dict(host) for host in db.sorted_hosts()],
|
|
215
|
+
}
|
|
216
|
+
if ui_section:
|
|
217
|
+
payload["ui"] = ui_section
|
|
218
|
+
|
|
219
|
+
tmp_path = path.with_name(path.name + ".tmp")
|
|
220
|
+
tmp_path.write_text(tomli_w.dumps(payload), encoding="utf-8")
|
|
221
|
+
set_private_permissions(tmp_path)
|
|
222
|
+
tmp_path.replace(path)
|
sshcnfgr/tui.py
ADDED
|
@@ -0,0 +1,471 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import copy
|
|
4
|
+
|
|
5
|
+
from rich.text import Text
|
|
6
|
+
from textual.app import App, ComposeResult
|
|
7
|
+
from textual.containers import Horizontal, Vertical, VerticalScroll
|
|
8
|
+
from textual.widgets import Button, Checkbox, DataTable, Footer, Header, Input, Label, Static
|
|
9
|
+
|
|
10
|
+
from .dedup_screen import DuplicateReviewScreen
|
|
11
|
+
from .generator import write_generated_config
|
|
12
|
+
from .identities import discover_ssh_identities, merge_discovered_identities
|
|
13
|
+
from .model import HostDatabase, HostEntry
|
|
14
|
+
from .settings import (
|
|
15
|
+
DEFAULT_DARK_THEME,
|
|
16
|
+
DEFAULT_LIGHT_THEME,
|
|
17
|
+
load_ui_theme_name,
|
|
18
|
+
save_ui_theme_name,
|
|
19
|
+
)
|
|
20
|
+
from .store import load_database, save_database
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class SSHCnfgrApp(App[None]):
|
|
24
|
+
"""Textual-App zur Verwaltung von SSH-Hosts aus einer TOML-Datenbasis.
|
|
25
|
+
|
|
26
|
+
Die App haelt einen In-Memory-Stand (self.db), zeigt diesen in der Tabelle an
|
|
27
|
+
und synchronisiert ueber Buttons/Hotkeys in die Datei.
|
|
28
|
+
"""
|
|
29
|
+
|
|
30
|
+
CSS_PATH = "tui.tcss"
|
|
31
|
+
TITLE = "SSHCnfgr"
|
|
32
|
+
SUB_TITLE = "SSH-Hosts mit TOML verwalten"
|
|
33
|
+
|
|
34
|
+
# Keybindings werden automatisch im Footer angezeigt und auf action_* gemappt.
|
|
35
|
+
BINDINGS = [
|
|
36
|
+
("ctrl+s", "save", "Speichern"),
|
|
37
|
+
("ctrl+g", "generate", "Generieren"),
|
|
38
|
+
("ctrl+n", "new_host", "Neu"),
|
|
39
|
+
("ctrl+d", "delete_host", "Loeschen"),
|
|
40
|
+
("ctrl+u", "open_dedup", "Dubletten"),
|
|
41
|
+
("ctrl+t", "toggle_theme", "Thema"),
|
|
42
|
+
("q", "quit", "Beenden"),
|
|
43
|
+
]
|
|
44
|
+
|
|
45
|
+
def __init__(self) -> None:
|
|
46
|
+
super().__init__()
|
|
47
|
+
# In-Memory-DB wird beim Mount aus TOML geladen.
|
|
48
|
+
self.db = HostDatabase()
|
|
49
|
+
# Referenz auf aktuell ausgewaehlten Host (ID aus dem Datenmodell).
|
|
50
|
+
self.selected_host_id: str | None = None
|
|
51
|
+
# Name der in der Identity-Tabelle selektierten Identity.
|
|
52
|
+
self.selected_identity_name: str | None = None
|
|
53
|
+
|
|
54
|
+
def compose(self) -> ComposeResult:
|
|
55
|
+
"""Deklariert das UI-Layout.
|
|
56
|
+
|
|
57
|
+
Links: Host-Liste + Listenaktionen.
|
|
58
|
+
Rechts: Detailformular + Aktionen fuer Speichern/Generieren.
|
|
59
|
+
"""
|
|
60
|
+
yield Header(show_clock=True)
|
|
61
|
+
with Horizontal(id="body"):
|
|
62
|
+
with Vertical(id="left"):
|
|
63
|
+
yield Label("Hosts")
|
|
64
|
+
yield DataTable(id="hosts_table", cursor_type="row")
|
|
65
|
+
with Horizontal(id="list_actions"):
|
|
66
|
+
yield Button("Neu", id="btn_new", variant="primary")
|
|
67
|
+
yield Button("Loeschen", id="btn_delete", variant="error")
|
|
68
|
+
yield Button("Toggle Aktiv", id="btn_toggle")
|
|
69
|
+
yield Button("Dubletten", id="btn_dedup", variant="warning")
|
|
70
|
+
yield Label("Identities")
|
|
71
|
+
yield DataTable(id="identities_table", cursor_type="row")
|
|
72
|
+
with Horizontal(id="identity_actions"):
|
|
73
|
+
yield Button("Scan ~/.ssh", id="btn_scan_identities")
|
|
74
|
+
yield Button("Use Selected", id="btn_use_identity")
|
|
75
|
+
yield Button("Toggle Enabled", id="btn_toggle_identity")
|
|
76
|
+
with VerticalScroll(id="right"):
|
|
77
|
+
yield Label("Host Details")
|
|
78
|
+
yield Input(placeholder="Alias (Host)", id="name")
|
|
79
|
+
yield Input(placeholder="HostName", id="host_name")
|
|
80
|
+
yield Input(placeholder="User", id="user")
|
|
81
|
+
yield Input(placeholder="Port", id="port")
|
|
82
|
+
yield Input(placeholder="Identity Profile (Name)", id="identity")
|
|
83
|
+
yield Input(placeholder="IdentityFile", id="identity_file")
|
|
84
|
+
yield Input(placeholder="Groups (csv), z. B. prod,db", id="groups")
|
|
85
|
+
yield Checkbox("Aktiv", id="enabled", value=True)
|
|
86
|
+
with Horizontal(id="detail_actions"):
|
|
87
|
+
yield Button("Speichern", id="btn_save", variant="success")
|
|
88
|
+
yield Button("Generate", id="btn_generate", variant="warning")
|
|
89
|
+
yield Label("Gruppen-Identity")
|
|
90
|
+
yield Input(placeholder="Group Name", id="group_identity_target")
|
|
91
|
+
with Horizontal(id="group_identity_actions"):
|
|
92
|
+
yield Button("Assign Selected Identity to Group", id="btn_set_group_identity")
|
|
93
|
+
yield Static("", id="status")
|
|
94
|
+
yield Footer()
|
|
95
|
+
|
|
96
|
+
def on_mount(self) -> None:
|
|
97
|
+
"""Lifecycle-Hook nach dem Aufbau des Widget-Baums.
|
|
98
|
+
|
|
99
|
+
Hier laden wir Daten aus der TOML-Datei und initialisieren die Tabelle.
|
|
100
|
+
"""
|
|
101
|
+
# Gespeichertes Textual-Theme aus app.toml laden und auf die App anwenden.
|
|
102
|
+
self.theme = load_ui_theme_name()
|
|
103
|
+
|
|
104
|
+
self.db = load_database()
|
|
105
|
+
hosts_table = self.query_one("#hosts_table", DataTable)
|
|
106
|
+
hosts_table.add_columns("Host", "HostName", "User", "Port", "Identity", "Aktiv")
|
|
107
|
+
identities_table = self.query_one("#identities_table", DataTable)
|
|
108
|
+
identities_table.add_columns("Name", "IdentityFile", "Public", "Source", "Enabled")
|
|
109
|
+
self._refresh_table()
|
|
110
|
+
self._refresh_identities_table()
|
|
111
|
+
self._set_status(f"Bereit | Theme: {self.theme}")
|
|
112
|
+
|
|
113
|
+
def _set_status(self, message: str) -> None:
|
|
114
|
+
"""Schreibt eine kurze Rueckmeldung in die Statuszeile."""
|
|
115
|
+
self.query_one("#status", Static).update(message)
|
|
116
|
+
|
|
117
|
+
def _refresh_table(self) -> None:
|
|
118
|
+
"""Rendert die aktuelle In-Memory-DB in die DataTable.
|
|
119
|
+
|
|
120
|
+
Die Row-Key wird auf host.id gesetzt, damit die Auswahl spaeter eindeutig
|
|
121
|
+
zurueck auf das Objekt im Modell gemappt werden kann.
|
|
122
|
+
"""
|
|
123
|
+
table = self.query_one("#hosts_table", DataTable)
|
|
124
|
+
table.clear(columns=False)
|
|
125
|
+
|
|
126
|
+
for host in self.db.sorted_hosts():
|
|
127
|
+
identity_cell = self._identity_table_cell(host)
|
|
128
|
+
port_cell = self._port_table_cell(host)
|
|
129
|
+
table.add_row(
|
|
130
|
+
host.name,
|
|
131
|
+
host.host_name,
|
|
132
|
+
host.user or "",
|
|
133
|
+
port_cell,
|
|
134
|
+
identity_cell,
|
|
135
|
+
"yes" if host.enabled else "no",
|
|
136
|
+
key=host.id,
|
|
137
|
+
)
|
|
138
|
+
|
|
139
|
+
def _identity_table_cell(self, host: HostEntry) -> Text:
|
|
140
|
+
"""Gibt den Identity-Wert fuer die Tabelle zurueck.
|
|
141
|
+
|
|
142
|
+
Ist der Wert indirekt (z. B. via Host *), wird er gedimmt angezeigt.
|
|
143
|
+
"""
|
|
144
|
+
if host.identity_file:
|
|
145
|
+
return Text(host.identity_file)
|
|
146
|
+
if host.identity:
|
|
147
|
+
return Text(host.identity)
|
|
148
|
+
|
|
149
|
+
resolved = self.db.resolve_identity_file(host)
|
|
150
|
+
if resolved:
|
|
151
|
+
return Text(resolved, style="dim")
|
|
152
|
+
|
|
153
|
+
identity_agent = self.db.resolve_identity_agent(host)
|
|
154
|
+
if identity_agent:
|
|
155
|
+
return Text(f"agent:{identity_agent}", style="dim")
|
|
156
|
+
return Text("")
|
|
157
|
+
|
|
158
|
+
def _port_table_cell(self, host: HostEntry) -> Text:
|
|
159
|
+
"""Zeigt Port explizit oder effektiv (Default 22) an.
|
|
160
|
+
|
|
161
|
+
Effektive, aber nicht explizit gesetzte Werte werden gedimmt angezeigt.
|
|
162
|
+
"""
|
|
163
|
+
if host.port is not None:
|
|
164
|
+
return Text(str(host.port))
|
|
165
|
+
return Text(str(self.db.resolve_port(host)), style="dim")
|
|
166
|
+
|
|
167
|
+
def _refresh_identities_table(self) -> None:
|
|
168
|
+
table = self.query_one("#identities_table", DataTable)
|
|
169
|
+
table.clear(columns=False)
|
|
170
|
+
|
|
171
|
+
for identity in self.db.sorted_identities():
|
|
172
|
+
table.add_row(
|
|
173
|
+
identity.name,
|
|
174
|
+
identity.identity_file,
|
|
175
|
+
identity.public_key_preview or "",
|
|
176
|
+
identity.source,
|
|
177
|
+
"yes" if identity.enabled else "no",
|
|
178
|
+
key=identity.name,
|
|
179
|
+
)
|
|
180
|
+
|
|
181
|
+
def _get_selected_host(self) -> HostEntry | None:
|
|
182
|
+
"""Liefert den aktuell ausgewaehlten Host oder None."""
|
|
183
|
+
if not self.selected_host_id:
|
|
184
|
+
return None
|
|
185
|
+
return self.db.get_by_id(self.selected_host_id)
|
|
186
|
+
|
|
187
|
+
def _load_selected_into_form(self, host: HostEntry) -> None:
|
|
188
|
+
"""Spiegelt ein Host-Objekt in die Formularfelder."""
|
|
189
|
+
self.query_one("#name", Input).value = host.name
|
|
190
|
+
self.query_one("#host_name", Input).value = host.host_name
|
|
191
|
+
self.query_one("#user", Input).value = host.user or ""
|
|
192
|
+
self.query_one("#port", Input).value = str(host.port or "")
|
|
193
|
+
self.query_one("#identity", Input).value = host.identity or ""
|
|
194
|
+
self.query_one("#identity_file", Input).value = host.identity_file or ""
|
|
195
|
+
self.query_one("#groups", Input).value = ",".join(host.groups)
|
|
196
|
+
self.query_one("#enabled", Checkbox).value = host.enabled
|
|
197
|
+
|
|
198
|
+
def _read_form(self) -> tuple[HostEntry, list[str]]:
|
|
199
|
+
"""Liest UI-Felder ein und baut daraus einen Host-Kandidaten.
|
|
200
|
+
|
|
201
|
+
Bei selektiertem Host wird eine Kopie als Basis genommen, damit nicht im
|
|
202
|
+
Formular abgebildete Felder (tags, extra_options) erhalten bleiben. Das
|
|
203
|
+
Modellobjekt in self.db wird hier bewusst nicht veraendert; das Commit
|
|
204
|
+
passiert erst nach erfolgreicher Validierung in action_save.
|
|
205
|
+
"""
|
|
206
|
+
selected = self._get_selected_host()
|
|
207
|
+
host = copy.deepcopy(selected) if selected is not None else HostEntry()
|
|
208
|
+
|
|
209
|
+
host.name = self.query_one("#name", Input).value.strip()
|
|
210
|
+
host.host_name = self.query_one("#host_name", Input).value.strip()
|
|
211
|
+
host.user = self.query_one("#user", Input).value.strip() or None
|
|
212
|
+
|
|
213
|
+
errors: list[str] = []
|
|
214
|
+
port_raw = self.query_one("#port", Input).value.strip()
|
|
215
|
+
if port_raw:
|
|
216
|
+
try:
|
|
217
|
+
host.port = int(port_raw)
|
|
218
|
+
except ValueError:
|
|
219
|
+
errors.append(f"port ist keine Zahl: {port_raw}")
|
|
220
|
+
else:
|
|
221
|
+
host.port = None
|
|
222
|
+
|
|
223
|
+
host.identity = self.query_one("#identity", Input).value.strip() or None
|
|
224
|
+
host.identity_file = self.query_one("#identity_file", Input).value.strip() or None
|
|
225
|
+
groups_raw = self.query_one("#groups", Input).value.strip()
|
|
226
|
+
host.groups = [item.strip() for item in groups_raw.split(",") if item.strip()]
|
|
227
|
+
host.enabled = self.query_one("#enabled", Checkbox).value
|
|
228
|
+
|
|
229
|
+
errors.extend(host.validate())
|
|
230
|
+
return host, errors
|
|
231
|
+
|
|
232
|
+
def on_data_table_row_selected(self, event: DataTable.RowSelected) -> None:
|
|
233
|
+
"""Event-Handler: Klick/Enter auf eine Tabellenzeile.
|
|
234
|
+
|
|
235
|
+
Holt die Row-Key-ID aus dem Event, sucht das Modellobjekt und fuellt das
|
|
236
|
+
Detailformular auf der rechten Seite.
|
|
237
|
+
"""
|
|
238
|
+
table_id = event.data_table.id
|
|
239
|
+
row_key = event.row_key
|
|
240
|
+
|
|
241
|
+
if table_id == "hosts_table":
|
|
242
|
+
host_id = str(getattr(row_key, "value", row_key))
|
|
243
|
+
host = self.db.get_by_id(host_id)
|
|
244
|
+
if host is None:
|
|
245
|
+
return
|
|
246
|
+
self.selected_host_id = host.id
|
|
247
|
+
self._load_selected_into_form(host)
|
|
248
|
+
self._set_status(f"Ausgewaehlt: {host.name}")
|
|
249
|
+
return
|
|
250
|
+
|
|
251
|
+
if table_id == "identities_table":
|
|
252
|
+
identity_name = str(getattr(row_key, "value", row_key))
|
|
253
|
+
self.selected_identity_name = identity_name
|
|
254
|
+
self._set_status(f"Identity ausgewaehlt: {identity_name}")
|
|
255
|
+
|
|
256
|
+
def on_button_pressed(self, event: Button.Pressed) -> None:
|
|
257
|
+
"""Zentraler Dispatcher fuer alle Button-Klicks."""
|
|
258
|
+
if event.button.id == "btn_new":
|
|
259
|
+
self.action_new_host()
|
|
260
|
+
elif event.button.id == "btn_delete":
|
|
261
|
+
self.action_delete_host()
|
|
262
|
+
elif event.button.id == "btn_toggle":
|
|
263
|
+
host = self._get_selected_host()
|
|
264
|
+
if host is None:
|
|
265
|
+
self._set_status("Kein Host ausgewaehlt")
|
|
266
|
+
return
|
|
267
|
+
host.enabled = not host.enabled
|
|
268
|
+
self.query_one("#enabled", Checkbox).value = host.enabled
|
|
269
|
+
save_database(self.db)
|
|
270
|
+
self._refresh_table()
|
|
271
|
+
self._set_status(f"Host {host.name} aktiv={host.enabled}")
|
|
272
|
+
elif event.button.id == "btn_dedup":
|
|
273
|
+
self.action_open_dedup()
|
|
274
|
+
elif event.button.id == "btn_save":
|
|
275
|
+
self.action_save()
|
|
276
|
+
elif event.button.id == "btn_generate":
|
|
277
|
+
self.action_generate()
|
|
278
|
+
elif event.button.id == "btn_scan_identities":
|
|
279
|
+
self.action_scan_identities()
|
|
280
|
+
elif event.button.id == "btn_use_identity":
|
|
281
|
+
self.action_use_selected_identity()
|
|
282
|
+
elif event.button.id == "btn_toggle_identity":
|
|
283
|
+
self.action_toggle_identity_enabled()
|
|
284
|
+
elif event.button.id == "btn_set_group_identity":
|
|
285
|
+
self.action_set_group_identity()
|
|
286
|
+
|
|
287
|
+
def action_new_host(self) -> None:
|
|
288
|
+
"""Setzt das Formular auf 'neuer Datensatz'."""
|
|
289
|
+
self.selected_host_id = None
|
|
290
|
+
self.query_one("#name", Input).value = ""
|
|
291
|
+
self.query_one("#host_name", Input).value = ""
|
|
292
|
+
self.query_one("#user", Input).value = ""
|
|
293
|
+
self.query_one("#port", Input).value = ""
|
|
294
|
+
self.query_one("#identity", Input).value = ""
|
|
295
|
+
self.query_one("#identity_file", Input).value = ""
|
|
296
|
+
self.query_one("#groups", Input).value = ""
|
|
297
|
+
self.query_one("#enabled", Checkbox).value = True
|
|
298
|
+
self._set_status("Neuer Host: Felder ausfuellen und Speichern")
|
|
299
|
+
|
|
300
|
+
def action_delete_host(self) -> None:
|
|
301
|
+
"""Loescht den selektierten Host direkt aus DB und Datei."""
|
|
302
|
+
host = self._get_selected_host()
|
|
303
|
+
if host is None:
|
|
304
|
+
self._set_status("Kein Host ausgewaehlt")
|
|
305
|
+
return
|
|
306
|
+
|
|
307
|
+
self.db.hosts = [h for h in self.db.hosts if h.id != host.id]
|
|
308
|
+
self.action_new_host()
|
|
309
|
+
self._refresh_table()
|
|
310
|
+
save_database(self.db)
|
|
311
|
+
self._set_status(f"Host geloescht: {host.name}")
|
|
312
|
+
|
|
313
|
+
def action_save(self) -> None:
|
|
314
|
+
"""Validiert Formular/DB auf einer Kopie und speichert erst bei Erfolg.
|
|
315
|
+
|
|
316
|
+
So bleibt die In-Memory-DB bei Validierungsfehlern unveraendert und
|
|
317
|
+
die App haengt nicht in einem kaputten Zwischenzustand fest.
|
|
318
|
+
"""
|
|
319
|
+
candidate, errors = self._read_form()
|
|
320
|
+
if errors:
|
|
321
|
+
self._set_status("; ".join(errors))
|
|
322
|
+
return
|
|
323
|
+
|
|
324
|
+
candidate_db = copy.deepcopy(self.db)
|
|
325
|
+
existing = candidate_db.get_by_id(candidate.id)
|
|
326
|
+
if existing is None:
|
|
327
|
+
candidate_db.hosts.append(candidate)
|
|
328
|
+
else:
|
|
329
|
+
candidate_db.hosts[candidate_db.hosts.index(existing)] = candidate
|
|
330
|
+
candidate_db.ensure_groups(candidate.groups)
|
|
331
|
+
|
|
332
|
+
db_errors = candidate_db.validate()
|
|
333
|
+
if db_errors:
|
|
334
|
+
self._set_status("; ".join(db_errors))
|
|
335
|
+
return
|
|
336
|
+
|
|
337
|
+
self.db = candidate_db
|
|
338
|
+
if self.selected_host_id is None:
|
|
339
|
+
self.selected_host_id = candidate.id
|
|
340
|
+
|
|
341
|
+
save_database(self.db)
|
|
342
|
+
self._refresh_table()
|
|
343
|
+
self._refresh_identities_table()
|
|
344
|
+
self._set_status(f"Gespeichert: {candidate.name}")
|
|
345
|
+
|
|
346
|
+
def action_open_dedup(self) -> None:
|
|
347
|
+
"""Oeffnet die Dubletten-Ansicht zum interaktiven Zusammenfuehren."""
|
|
348
|
+
self.push_screen(DuplicateReviewScreen(self.db), self._on_dedup_closed)
|
|
349
|
+
|
|
350
|
+
def _on_dedup_closed(self, updated_db: HostDatabase | None) -> None:
|
|
351
|
+
"""Uebernimmt Aenderungen aus der Dubletten-Ansicht in die Hauptansicht."""
|
|
352
|
+
if updated_db is None:
|
|
353
|
+
return
|
|
354
|
+
|
|
355
|
+
self.db = updated_db
|
|
356
|
+
selected = self._get_selected_host()
|
|
357
|
+
if selected is None:
|
|
358
|
+
self.action_new_host()
|
|
359
|
+
else:
|
|
360
|
+
self._load_selected_into_form(selected)
|
|
361
|
+
|
|
362
|
+
self._refresh_table()
|
|
363
|
+
self._refresh_identities_table()
|
|
364
|
+
self._set_status("Dubletten-Aenderungen uebernommen")
|
|
365
|
+
|
|
366
|
+
def action_generate(self) -> None:
|
|
367
|
+
"""Erzeugt aus der aktuellen DB die OpenSSH-Ausgabedatei."""
|
|
368
|
+
db_errors = self.db.validate()
|
|
369
|
+
if db_errors:
|
|
370
|
+
self._set_status("; ".join(db_errors))
|
|
371
|
+
return
|
|
372
|
+
|
|
373
|
+
try:
|
|
374
|
+
target = write_generated_config(self.db)
|
|
375
|
+
except OSError as exc:
|
|
376
|
+
self._set_status(f"Fehler beim Generieren: {exc}")
|
|
377
|
+
return
|
|
378
|
+
self._set_status(f"Generiert: {target}")
|
|
379
|
+
|
|
380
|
+
def action_toggle_theme(self) -> None:
|
|
381
|
+
"""Schaltet zwischen Hell/Dunkel und speichert die Auswahl dauerhaft."""
|
|
382
|
+
self.theme = (
|
|
383
|
+
DEFAULT_LIGHT_THEME
|
|
384
|
+
if self.theme != DEFAULT_LIGHT_THEME
|
|
385
|
+
else DEFAULT_DARK_THEME
|
|
386
|
+
)
|
|
387
|
+
self.db.ui = {
|
|
388
|
+
"theme": self.theme,
|
|
389
|
+
"dark": self.theme != DEFAULT_LIGHT_THEME,
|
|
390
|
+
}
|
|
391
|
+
save_ui_theme_name(self.theme)
|
|
392
|
+
self._set_status(f"Theme gespeichert: {self.theme}")
|
|
393
|
+
|
|
394
|
+
def action_scan_identities(self) -> None:
|
|
395
|
+
"""Liest Keys aus ~/.ssh ein und merged sie in die Datenbank."""
|
|
396
|
+
discovered = discover_ssh_identities()
|
|
397
|
+
candidate_db = copy.deepcopy(self.db)
|
|
398
|
+
created, updated = merge_discovered_identities(candidate_db, discovered)
|
|
399
|
+
|
|
400
|
+
db_errors = candidate_db.validate()
|
|
401
|
+
if db_errors:
|
|
402
|
+
self._set_status("; ".join(db_errors))
|
|
403
|
+
return
|
|
404
|
+
|
|
405
|
+
self.db = candidate_db
|
|
406
|
+
save_database(self.db)
|
|
407
|
+
self._refresh_table()
|
|
408
|
+
self._refresh_identities_table()
|
|
409
|
+
self._set_status(
|
|
410
|
+
f"Identity-Scan: gefunden={len(discovered)} neu={created} aktualisiert={updated}"
|
|
411
|
+
)
|
|
412
|
+
|
|
413
|
+
def action_use_selected_identity(self) -> None:
|
|
414
|
+
"""Uebernimmt die gewaehlte Identity in das Host-Formular."""
|
|
415
|
+
if not self.selected_identity_name:
|
|
416
|
+
self._set_status("Keine Identity ausgewaehlt")
|
|
417
|
+
return
|
|
418
|
+
self.query_one("#identity", Input).value = self.selected_identity_name
|
|
419
|
+
self._set_status(f"Identity gesetzt im Formular: {self.selected_identity_name}")
|
|
420
|
+
|
|
421
|
+
def action_toggle_identity_enabled(self) -> None:
|
|
422
|
+
"""Aktiviert/deaktiviert die selektierte Identity."""
|
|
423
|
+
if not self.selected_identity_name:
|
|
424
|
+
self._set_status("Keine Identity ausgewaehlt")
|
|
425
|
+
return
|
|
426
|
+
|
|
427
|
+
identity = self.db.get_identity_by_name(self.selected_identity_name)
|
|
428
|
+
if identity is None:
|
|
429
|
+
self._set_status("Identity nicht gefunden")
|
|
430
|
+
return
|
|
431
|
+
|
|
432
|
+
identity.enabled = not identity.enabled
|
|
433
|
+
save_database(self.db)
|
|
434
|
+
self._refresh_table()
|
|
435
|
+
self._refresh_identities_table()
|
|
436
|
+
self._set_status(f"Identity {identity.name} enabled={identity.enabled}")
|
|
437
|
+
|
|
438
|
+
def action_set_group_identity(self) -> None:
|
|
439
|
+
"""Weist die selektierte Identity einer Gruppe als Default zu."""
|
|
440
|
+
if not self.selected_identity_name:
|
|
441
|
+
self._set_status("Keine Identity ausgewaehlt")
|
|
442
|
+
return
|
|
443
|
+
|
|
444
|
+
group_name = self.query_one("#group_identity_target", Input).value.strip()
|
|
445
|
+
if not group_name:
|
|
446
|
+
self._set_status("Bitte Group Name eintragen")
|
|
447
|
+
return
|
|
448
|
+
|
|
449
|
+
candidate_db = copy.deepcopy(self.db)
|
|
450
|
+
candidate_db.ensure_groups([group_name])
|
|
451
|
+
group = candidate_db.get_group_by_name(group_name)
|
|
452
|
+
if group is None:
|
|
453
|
+
self._set_status("Gruppe konnte nicht erstellt werden")
|
|
454
|
+
return
|
|
455
|
+
|
|
456
|
+
group.identity = self.selected_identity_name
|
|
457
|
+
|
|
458
|
+
db_errors = candidate_db.validate()
|
|
459
|
+
if db_errors:
|
|
460
|
+
self._set_status("; ".join(db_errors))
|
|
461
|
+
return
|
|
462
|
+
|
|
463
|
+
self.db = candidate_db
|
|
464
|
+
save_database(self.db)
|
|
465
|
+
self._refresh_table()
|
|
466
|
+
self._set_status(f"Group {group.name} -> Identity {self.selected_identity_name}")
|
|
467
|
+
|
|
468
|
+
|
|
469
|
+
def run_tui() -> None:
|
|
470
|
+
"""Startpunkt fuer CLI-Command 'sshcnfgr tui'."""
|
|
471
|
+
SSHCnfgrApp().run()
|