-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfinal_shell_decoder.py
More file actions
422 lines (333 loc) · 15.2 KB
/
Copy pathfinal_shell_decoder.py
File metadata and controls
422 lines (333 loc) · 15.2 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
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
#!/usr/bin/env python3
"""FinalShell 批量解析工具 — GUI 版本."""
from __future__ import annotations
import logging
import tkinter as tk
from pathlib import Path
from tkinter import filedialog, messagebox, ttk, scrolledtext
import pyperclip
from src.core import (
ServerCredential,
build_credential_copy_value,
detect_final_shell_path,
is_final_shell_dir,
load_credentials,
load_key_data_map,
)
_COLUMNS = ["名称", "主机", "端口", "用户名", "认证方式", "登录凭据"]
logger = logging.getLogger("fsdp.gui")
# ---------------------------------------------------------------------------
# Tkinter logging handler — routes log records into the detail text area
# ---------------------------------------------------------------------------
class _TextHandler(logging.Handler):
"""A logging handler that appends formatted records to a tkinter Text widget."""
def __init__(self, text_widget: tk.Text) -> None:
super().__init__()
self._widget = text_widget
def emit(self, record: logging.LogRecord) -> None:
msg = self.format(record)
self._widget.insert(tk.END, msg + "\n")
self._widget.see(tk.END)
class FinalShellDecoder:
def __init__(self, root: tk.Tk) -> None:
self.root = root
self.root.title("FinalShell Decoder X")
self.root.geometry("1220x780")
self.credentials: list[ServerCredential] = []
self._init_ui()
self._init_logging()
self._auto_detect()
# ---- UI construction --------------------------------------------------
def _init_ui(self) -> None:
# ---- path bar ----
path_frame = tk.Frame(self.root, padx=8, pady=8)
path_frame.pack(fill=tk.X, expand=False)
tk.Label(path_frame, text="FinalShell 路径:", font=("Arial", 10)).pack(
side=tk.LEFT, padx=4
)
self.path_var = tk.StringVar()
self.path_entry = tk.Entry(path_frame, textvariable=self.path_var, width=50)
self.path_entry.pack(side=tk.LEFT, padx=4, expand=True, fill=tk.X)
btn_frame = tk.Frame(path_frame)
btn_frame.pack(side=tk.RIGHT)
tk.Button(btn_frame, text="自动检测", command=self._auto_detect).pack(
side=tk.LEFT, padx=4
)
tk.Button(btn_frame, text="手动选择", command=self._choose_dir).pack(
side=tk.LEFT, padx=4
)
tk.Button(btn_frame, text="开始解析", command=self._parse_all).pack(
side=tk.LEFT, padx=4
)
# ---- table ----
table_frame = tk.Frame(self.root)
table_frame.pack(fill=tk.BOTH, expand=True, padx=8, pady=4)
# Create a subframe for the table and scrollbars
tree_container = tk.Frame(table_frame)
tree_container.pack(fill=tk.BOTH, expand=True)
self.tree = ttk.Treeview(tree_container, columns=_COLUMNS, show="headings")
for col in _COLUMNS:
self.tree.heading(col, text=col, command=lambda _col=col: self._sort_column(_col, False))
self.tree.column(col, minwidth=80, width=150, anchor=tk.W)
self.tree.column("名称", width=180, stretch=tk.YES)
self.tree.column("主机", width=180, stretch=tk.YES)
self.tree.column("端口", width=80, stretch=tk.NO)
self.tree.column("用户名", width=120, stretch=tk.YES)
self.tree.column("认证方式", width=120, stretch=tk.NO)
self.tree.column("登录凭据", width=350, stretch=tk.YES)
# Add horizontal scrollbar
h_scrollbar = ttk.Scrollbar(tree_container, orient=tk.HORIZONTAL, command=self.tree.xview)
self.tree.configure(xscrollcommand=h_scrollbar.set)
scrollbar = ttk.Scrollbar(tree_container, orient=tk.VERTICAL, command=self.tree.yview)
self.tree.configure(yscrollcommand=scrollbar.set)
# Pack the tree and scrollbars properly
self.tree.grid(row=0, column=0, sticky="nsew")
scrollbar.grid(row=0, column=1, sticky="ns")
h_scrollbar.grid(row=1, column=0, sticky="ew")
# Configure grid weights to make the tree expand properly
tree_container.grid_rowconfigure(0, weight=1)
tree_container.grid_columnconfigure(0, weight=1)
self.tree.bind("<Double-1>", self._on_double_click)
self.tree.bind("<Button-3>", self._show_context_menu)
# Add context menu
self.context_menu = tk.Menu(self.root, tearoff=0)
self.context_menu.add_command(label="复制登录凭据", command=self._copy_selected_credential)
self.context_menu.add_command(label="查看详情", command=self._show_selected_detail)
# Add sorting support
self._sort_column("名称", False)
# ---- detail area ----
detail_frame = tk.Frame(self.root, padx=8, pady=8)
detail_frame.pack(fill=tk.BOTH, expand=True)
tk.Label(detail_frame, text="详细信息:", font=("Arial", 10)).pack(anchor=tk.W)
self.detail_text = scrolledtext.ScrolledText(
detail_frame, width=100, height=15, font=("Monaco", 10)
)
self.detail_text.pack(fill=tk.BOTH, expand=True)
# Add right-click menu for detail text area
self.detail_text.bind("<Button-3>", self._show_detail_context_menu)
self.detail_context_menu = tk.Menu(self.root, tearoff=0)
self.detail_context_menu.add_command(label="清空", command=self._clear_detail_text)
# ---- status bar ----
self.status_var = tk.StringVar(value="就绪")
status_bar = tk.Label(
self.root,
textvariable=self.status_var,
bd=1,
relief=tk.SUNKEN,
anchor=tk.W,
)
status_bar.pack(side=tk.BOTTOM, fill=tk.X)
# ---- logging ----------------------------------------------------------
def _init_logging(self) -> None:
"""Attach a handler that writes log records into the detail text area."""
handler = _TextHandler(self.detail_text)
handler.setFormatter(logging.Formatter("%(asctime)s [%(levelname)s] %(message)s",
datefmt="%H:%M:%S"))
logger.addHandler(handler)
logger.setLevel(logging.DEBUG)
# ---- path resolution --------------------------------------------------
def _auto_detect(self) -> None:
logger.info("正在自动检测 FinalShell 安装目录...")
detected = detect_final_shell_path()
if detected:
self.path_var.set(str(detected))
self.status_var.set(f"已自动检测路径: {detected}")
logger.info("检测到目录: %s", detected)
else:
self.status_var.set("未自动检测到路径,请手动选择 FinalShell 安装目录")
logger.warning("未检测到 FinalShell 安装目录")
def _choose_dir(self) -> None:
dir_path = filedialog.askdirectory(title="选择 FinalShell 安装目录(目录下需包含 conn)")
if dir_path:
self.path_var.set(dir_path)
logger.debug("用户选择目录: %s", dir_path)
# ---- parsing ----------------------------------------------------------
def _parse_all(self) -> None:
path_text = self.path_var.get().strip()
if not path_text:
messagebox.showwarning("提示", "请先选择 FinalShell 安装目录")
return
base_dir = Path(path_text)
if not is_final_shell_dir(base_dir):
messagebox.showerror("错误", "目录不正确:未找到 conn 文件夹")
return
try:
conn_dir = base_dir / "conn"
config_path = base_dir / "config.json"
self.detail_text.delete(1.0, tk.END)
logger.info("===== 开始解析 =====")
logger.info("目录: %s", base_dir)
logger.info("正在加载私钥数据...")
key_data_map = load_key_data_map(config_path)
logger.info("私钥条目: %d", len(key_data_map))
logger.info("正在解析 %s ...", conn_dir)
self.credentials = load_credentials(conn_dir, key_data_map)
logger.info("解析到 %d 条服务器记录", len(self.credentials))
self._update_table()
self.status_var.set(f"解析完成:共 {len(self.credentials)} 条服务器记录")
if not config_path.exists():
logger.warning("未找到 config.json,私钥无法解析")
self.status_var.set(
self.status_var.get() + "(未找到 config.json,私钥无法解析)"
)
except Exception as exc:
logger.exception("解析失败")
self.status_var.set(f"解析失败: {exc}")
messagebox.showerror("错误", f"解析失败: {exc}")
# ---- table operations -------------------------------------------------
def _sort_column(self, col: str, reverse: bool) -> None:
"""Sort the table by column."""
if not self.credentials:
return
# Get the index of the column
col_idx = _COLUMNS.index(col)
# Get the values to sort by
data = []
for i, cred in enumerate(self.credentials):
if col == "名称":
value = cred.name or cred.file_name
elif col == "主机":
value = cred.host
elif col == "端口":
value = cred.port
elif col == "用户名":
value = cred.user_name
elif col == "认证方式":
value = cred.auth_mode
elif col == "登录凭据":
value = cred.credential_display
else:
value = ""
data.append((value, i))
# Sort the data
data.sort(reverse=reverse)
# Rearrange the treeview
for idx, (_, original_idx) in enumerate(data):
self.tree.move(self.tree.get_children()[original_idx], "", idx)
# Toggle the sort direction for next click
self.tree.heading(col, command=lambda: self._sort_column(col, not reverse))
def _show_context_menu(self, event: tk.Event) -> None:
"""Show context menu on right-click."""
selected = self.tree.selection()
if not selected:
return
try:
self.context_menu.tk_popup(event.x_root, event.y_root, 0)
finally:
self.context_menu.grab_release()
def _show_detail_context_menu(self, event: tk.Event) -> None:
"""Show context menu for detail text area on right-click."""
try:
self.detail_context_menu.tk_popup(event.x_root, event.y_root, 0)
finally:
self.detail_context_menu.grab_release()
def _clear_detail_text(self) -> None:
"""Clear the detail text area."""
self.detail_text.delete(1.0, tk.END)
self.status_var.set("详细信息已清空")
def _copy_selected_credential(self) -> None:
"""Copy credential from selected row."""
selected = self.tree.selection()
if not selected:
return
idx = self.tree.index(selected[0])
if idx >= len(self.credentials):
return
cred = self.credentials[idx]
copy_value = build_credential_copy_value(cred)
if not copy_value:
self.status_var.set("该字段没有可复制内容")
return
pyperclip.copy(copy_value)
if cred.secret_key_id and not cred.encrypted_password:
self.status_var.set("已复制 登录凭据(私钥)")
else:
self.status_var.set(f"已复制 登录凭据: {self._preview(copy_value)}")
def _show_selected_detail(self) -> None:
"""Show detail for selected row."""
selected = self.tree.selection()
if not selected:
return
idx = self.tree.index(selected[0])
if idx >= len(self.credentials):
return
cred = self.credentials[idx]
self._show_detail(cred)
def _update_table(self) -> None:
for item in self.tree.get_children():
self.tree.delete(item)
for cred in self.credentials:
name = cred.name or cred.file_name
host = cred.host
port = str(cred.port) if cred.port > 0 else ""
display = cred.credential_display
# Truncate long display text
if len(display) > 52:
display = display[:52] + "..."
self.tree.insert(
"",
tk.END,
values=(name, host, port, cred.user_name, cred.auth_mode, display),
)
def _on_double_click(self, event: tk.Event) -> None:
selected = self.tree.selection()
if not selected:
return
idx = self.tree.index(selected[0])
if idx >= len(self.credentials):
return
cred = self.credentials[idx]
copy_value = build_credential_copy_value(cred)
if not copy_value:
self.status_var.set("该字段没有可复制内容")
return
pyperclip.copy(copy_value)
self._show_detail(cred)
if cred.secret_key_id and not cred.encrypted_password:
self.status_var.set("已复制 登录凭据(私钥)")
else:
self.status_var.set(f"已复制 登录凭据: {self._preview(copy_value)}")
def _show_detail(self, cred: ServerCredential) -> None:
self.detail_text.delete(1.0, tk.END)
self.detail_text.insert(tk.END, "本次复制字段: 登录凭据\n\n")
self.detail_text.insert(tk.END, f"文件名: {cred.file_name}\n")
self.detail_text.insert(tk.END, f"连接名称: {cred.name or ''}\n")
self.detail_text.insert(tk.END, f"服务器ID: {cred.id}\n")
self.detail_text.insert(tk.END, f"主机: {cred.host}:{cred.port}\n")
self.detail_text.insert(tk.END, f"用户名: {cred.user_name}\n")
self.detail_text.insert(
tk.END,
f"认证方式: {cred.auth_mode} (authentication_type={cred.authentication_type})\n",
)
self.detail_text.insert(tk.END, f"secret_key_id: {cred.secret_key_id}\n\n")
self.detail_text.insert(
tk.END, f"登录凭据显示值:\n{cred.credential_display}\n\n"
)
self.detail_text.insert(
tk.END,
f"可复制的登录凭据实际值:\n{build_credential_copy_value(cred)}\n\n",
)
self.detail_text.insert(
tk.END, f"加密密码:\n{cred.encrypted_password}\n\n"
)
self.detail_text.insert(
tk.END, f"解密密码:\n{cred.decoded_password or ''}\n\n"
)
self.detail_text.insert(
tk.END, f"加密私钥(key_data):\n{cred.encrypted_private_key}\n\n"
)
self.detail_text.insert(
tk.END, f"解密私钥:\n{cred.decoded_private_key or ''}\n"
)
@staticmethod
def _preview(value: str) -> str:
flat = value.replace("\r", " ").replace("\n", " ").strip()
if len(flat) <= 26:
return flat
return flat[:26] + "..."
def run() -> None:
root = tk.Tk()
FinalShellDecoder(root)
root.mainloop()
if __name__ == "__main__":
run()