-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconfig_manager.py
More file actions
316 lines (275 loc) · 9.24 KB
/
Copy pathconfig_manager.py
File metadata and controls
316 lines (275 loc) · 9.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
"""
config_manager.py - Gestione profili sessioni e impostazioni globali PCM
"""
import json
import os
# Import lazy: crypto_manager potrebbe non avere cryptography installato
def _crypto():
try:
import crypto_manager
return crypto_manager
except ImportError:
return None
# Percorsi ancorati alla cartella di config_manager.py (indipendente dalla CWD)
_HERE = os.path.dirname(os.path.abspath(__file__))
SESSIONS_FILE = os.path.join(_HERE, "connections.json")
SETTINGS_FILE = os.path.join(_HERE, "pcm_settings.json")
# ---------------------------------------------------------------------------
# Sessioni
# ---------------------------------------------------------------------------
def load_profiles() -> dict:
"""
Carica i profili da connections.json.
Se la cifratura è attiva decifra automaticamente user/password.
Se il file non esiste lo crea con le sessioni di esempio
e imposta il flag primo_avvio in settings.
"""
first_run = not os.path.exists(SESSIONS_FILE)
if first_run:
_create_default_sessions()
# Segnala il primo avvio a PCM.py tramite settings
s = load_settings()
s.setdefault("crypto", {})["primo_avvio"] = True
save_settings(s)
try:
with open(SESSIONS_FILE, "r", encoding="utf-8") as f:
profili = json.load(f)
except (json.JSONDecodeError, Exception) as e:
print(f"[config] Errore lettura sessioni: {e}")
return {}
# Decifratura trasparente
cm = _crypto()
if cm and cm.is_enabled():
profili = {nome: cm.decrypt_profile(p) for nome, p in profili.items()}
return profili
def save_profiles(profiles: dict) -> bool:
"""
Salva i profili su connections.json.
Se la cifratura è attiva e sbloccata, cifra automaticamente user/password
prima di scrivere su disco.
"""
# Cifratura trasparente
cm = _crypto()
if cm and cm.is_enabled() and cm.is_unlocked():
to_save = {nome: cm.encrypt_profile(p) for nome, p in profiles.items()}
else:
to_save = profiles
try:
with open(SESSIONS_FILE, "w", encoding="utf-8") as f:
json.dump(to_save, f, indent=4, ensure_ascii=False)
return True
except Exception as e:
print(f"[config] Errore salvataggio sessioni: {e}")
return False
def _create_default_sessions():
default = {
"Esempio SSH": {
"protocol": "ssh",
"host": "192.168.1.100",
"port": "22",
"user": "utente",
"password": "",
"private_key": "",
"x11": False,
"compression": False,
"keepalive": False,
"startup_cmd": "",
"term_theme": "Scuro (Default)",
"term_font": "Monospace",
"term_size": "11",
"jump_host": "",
"jump_user": "",
"jump_port": "22",
"sftp_browser": True,
"notes": "Sessione SSH di esempio"
},
"Esempio RDP": {
"protocol": "rdp",
"host": "10.0.0.50",
"port": "3389",
"user": "amministratore",
"password": "",
"rdp_client": "xfreerdp",
"fullscreen": True,
"redirect_drives": False,
"redirect_clipboard": True,
"notes": ""
},
"Esempio VNC": {
"protocol": "vnc",
"host": "192.168.1.20",
"port": "5900",
"password": "",
"vnc_client": "vncviewer",
"vnc_color": "Truecolor (32 bpp)",
"vnc_quality": "Buona",
"notes": ""
},
"Esempio SFTP": {
"protocol": "sftp",
"host": "192.168.1.100",
"port": "22",
"user": "utente",
"password": "",
"private_key": "",
"notes": ""
},
"Esempio FTP": {
"protocol": "ftp",
"host": "192.168.1.100",
"port": "21",
"user": "utente",
"password": "",
"ftp_tls": False,
"ftp_passive": True,
"notes": "FTP plain — usa FTPS per cifrare il traffico"
},
"Esempio Telnet": {
"protocol": "telnet",
"host": "192.168.1.200",
"port": "23",
"user": "",
"notes": ""
},
"Esempio Mosh": {
"protocol": "mosh",
"host": "192.168.1.100",
"port": "22",
"user": "utente",
"password": "",
"private_key": "",
"notes": ""
},
"Esempio Seriale": {
"protocol": "serial",
"device": "/dev/ttyUSB0",
"baud": "115200",
"data_bits": "8",
"stop_bits": "1",
"parity": "None",
"notes": ""
},
}
save_profiles(default)
# ---------------------------------------------------------------------------
# Impostazioni globali
# ---------------------------------------------------------------------------
DEFAULT_SETTINGS = {
"general": {
"home_dir": os.path.expanduser("~"),
"default_editor": "nano",
"confirm_on_exit": True,
"language": "it",
"protected_mode": False,
},
"terminal": {
"default_theme": "Scuro (Default)",
"default_font": "Monospace",
"default_font_size": 11,
"scrollback_lines": 10000,
"confirm_on_close": True,
"log_output": False,
"log_dir": "/tmp/pcm_logs",
"word_delimiters": "/~+-.&?$%",
"warn_multiline_paste": True,
},
"ssh": {
"keepalive_interval": 60,
"strict_host_check": False,
"default_sftp_browser": True,
},
"tunnels": [],
"variables": {}, # variabili globali {NOME: valore}
"custom_tools": {
"vnc": [], # [{label, path, syntax}]
"rdp": [],
},
"display": {
"sidebar_visible": True,
"toolbar_visible": True,
"statusbar_visible": True,
"split_mode": "single",
},
"shortcuts": {
"new_terminal": "Ctrl+Alt+T",
"close_tab": "Ctrl+Alt+Q",
"prev_tab": "Ctrl+Alt+Left",
"next_tab": "Ctrl+Alt+Right",
"new_session": "Ctrl+Shift+N",
"toggle_sidebar": "Ctrl+Shift+B",
"find": "Ctrl+Shift+F",
"fullscreen": "F11",
}
}
def load_settings() -> dict:
if not os.path.exists(SETTINGS_FILE):
save_settings(DEFAULT_SETTINGS)
return dict(DEFAULT_SETTINGS)
try:
with open(SETTINGS_FILE, "r", encoding="utf-8") as f:
saved = json.load(f)
# merge con i default per aggiungere chiavi mancanti
merged = _deep_merge(DEFAULT_SETTINGS, saved)
return merged
except Exception as e:
print(f"[config] Errore lettura settings: {e}")
return dict(DEFAULT_SETTINGS)
def save_settings(settings: dict) -> bool:
try:
with open(SETTINGS_FILE, "w", encoding="utf-8") as f:
json.dump(settings, f, indent=4, ensure_ascii=False)
return True
except Exception as e:
print(f"[config] Errore salvataggio settings: {e}")
return False
def _deep_merge(base: dict, override: dict) -> dict:
result = dict(base)
for k, v in override.items():
if k in result and isinstance(result[k], dict) and isinstance(v, dict):
result[k] = _deep_merge(result[k], v)
else:
result[k] = v
return result
# ---------------------------------------------------------------------------
# Tunnel manager
# ---------------------------------------------------------------------------
def load_tunnels() -> list:
s = load_settings()
return s.get("tunnels", [])
def save_tunnels(tunnels: list):
s = load_settings()
s["tunnels"] = tunnels
save_settings(s)
# ---------------------------------------------------------------------------
# Variabili globali
# ---------------------------------------------------------------------------
def load_variables() -> dict:
"""Restituisce il dizionario {NOME: valore} delle variabili globali."""
s = load_settings()
return s.get("variables", {})
def save_variables(variables: dict):
"""Salva il dizionario variabili globali."""
s = load_settings()
s["variables"] = variables
save_settings(s)
def expand_variables(testo: str) -> str:
"""Sostituisce {NOME} con il valore dalla tabella variabili globali."""
vars_ = load_variables()
for nome, valore in vars_.items():
testo = testo.replace(f"{{{nome}}}", valore)
return testo
# ---------------------------------------------------------------------------
# Strumenti personalizzati (VNC / RDP)
# ---------------------------------------------------------------------------
def load_custom_tools() -> dict:
"""Restituisce {"vnc": [...], "rdp": [...]} con i client personalizzati."""
return load_settings().get("custom_tools", {"vnc": [], "rdp": []})
def save_custom_tools(custom_tools: dict):
s = load_settings()
s["custom_tools"] = custom_tools
save_settings(s)
if __name__ == "__main__":
p = load_profiles()
print(f"Sessioni caricate: {len(p)}")
s = load_settings()
print(f"Impostazioni caricate: {list(s.keys())}")