Repository navigation
Expand file tree
/
Copy pathremote_access.py
More file actions
993 lines (913 loc) · 47.5 KB
/
Copy pathremote_access.py
File metadata and controls
993 lines (913 loc) · 47.5 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
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
"""Windows OpenSSH enrollment UI."""
import base64
import ctypes
from ctypes import wintypes
import ipaddress
import json
import os
from pathlib import Path
import queue
import re
import socket
import subprocess
import tempfile
import threading
import tkinter as tk
import webbrowser
from tkinter import filedialog, messagebox, simpledialog, ttk
import winreg
def _literal(value):
return "'" + str(value).replace("'", "''") + "'"
def _powershell_path():
return Path(os.environ["SystemRoot"]) / "System32/WindowsPowerShell/v1.0/powershell.exe"
def _service_status():
api = ctypes.WinDLL("advapi32", use_last_error=True)
api.OpenSCManagerW.argtypes = (wintypes.LPCWSTR, wintypes.LPCWSTR, wintypes.DWORD)
api.OpenSCManagerW.restype = wintypes.HANDLE
api.OpenServiceW.argtypes = (wintypes.HANDLE, wintypes.LPCWSTR, wintypes.DWORD)
api.OpenServiceW.restype = wintypes.HANDLE
api.CloseServiceHandle.argtypes = (wintypes.HANDLE,)
api.CloseServiceHandle.restype = wintypes.BOOL
api.QueryServiceStatus.argtypes = (wintypes.HANDLE, ctypes.POINTER(wintypes.DWORD))
api.QueryServiceStatus.restype = wintypes.BOOL
manager = api.OpenSCManagerW(None, None, 0x0001) # SC_MANAGER_CONNECT
if not manager:
return "Unknown"
try:
service = api.OpenServiceW(manager, "sshd", 0x0004) # SERVICE_QUERY_STATUS
if not service:
return "Missing" if ctypes.get_last_error() == 1060 else "Unknown"
try:
status = (wintypes.DWORD * 7)() # SERVICE_STATUS
if not api.QueryServiceStatus(service, status):
return "Unknown"
return {
1: "Stopped", 2: "StartPending", 3: "StopPending", 4: "Running",
5: "ContinuePending", 6: "PausePending", 7: "Paused",
}.get(status[1], "Unknown")
finally:
api.CloseServiceHandle(service)
finally:
api.CloseServiceHandle(manager)
def _bundled_installer():
installers = list((Path(__file__).resolve().parent / "openssh-installer").glob("*.msi"))
return installers[0] if len(installers) == 1 else None
def _configure(request):
root = Path(__file__).resolve().parent
installer = _bundled_installer()
request["installer"] = str(installer) if installer else ""
with tempfile.TemporaryDirectory(prefix="wbsm-ssh-") as directory:
request_file = Path(directory) / "request.json"
result_file = Path(directory) / "result.json"
request_file.write_text(json.dumps(request), encoding="utf-8")
# Keep the response file owned by the unelevated caller.
result_file.touch(exist_ok=False)
command = (
f"& {_literal(root / 'remote_access.ps1')} "
f"-RequestPath {_literal(request_file)} -ResultPath {_literal(result_file)}"
)
encoded = base64.b64encode(command.encode("utf-16-le")).decode("ascii")
launcher = (
"$ErrorActionPreference = 'Stop'; "
"$p = Start-Process -FilePath (Join-Path $PSHOME 'powershell.exe') "
f"-ArgumentList '-NoProfile -NonInteractive -ExecutionPolicy Bypass -EncodedCommand {encoded}' "
"-Verb RunAs -Wait -PassThru; exit $p.ExitCode"
)
process = subprocess.run(
[str(_powershell_path()), "-NoProfile", "-NonInteractive", "-Command", launcher],
capture_output=True,
creationflags=subprocess.CREATE_NO_WINDOW,
)
result = result_file.read_text(encoding="utf-8-sig").strip()
if result:
return json.loads(result)
return {"error": f"Administrator setup did not return a result ({process.returncode})."}
def starts_with_wbsm():
try:
with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r"SYSTEM\CurrentControlSet\Services\sshd") as key:
return winreg.QueryValueEx(key, "WbsmStartWithApp")[0] == 1
except OSError:
return None
def _load_connection_info():
try:
with winreg.OpenKey(
winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\WindowsBatchScriptManager\RemoteAccess",
access=winreg.KEY_READ | winreg.KEY_WOW64_64KEY,
) as key:
info = json.loads(winreg.QueryValueEx(key, "ConnectionInfo")[0])
except (OSError, ValueError, TypeError):
return {}
if not isinstance(info, dict) or info.get("enabled") is not True:
return info if isinstance(info, dict) else {}
info.pop("password", None)
if not info.get("account") or not info.get("host"):
return {}
try:
addresses = list(dict.fromkeys(
item[4][0] for item in socket.getaddrinfo(socket.gethostname(), None, socket.AF_INET)
if not item[4][0].startswith(("127.", "169.254."))
))
if addresses:
info["addresses"] = list(dict.fromkeys([*info.get("addresses", []), *addresses]))
except OSError:
pass
return info
PRODUCTION_APPROVAL_INSTRUCTIONS = (
"【WBSM 生产远程操作约定】\n"
"先确认目标主机、账号和连接入口,并核对 SSH 主机指纹。目标不明确或指纹无法核对时,停止并询问。"
"只读检查可直接执行。命令串接、管道和重定向按整条命令的实际影响判断。\n"
"上传文件(含临时文件)、覆盖文件、修改配置、启停或重启业务任务前,先提交操作单。"
"写明编号、目标主机和入口、绝对路径、逐条命令、影响范围、预计中断、备份位置和回滚步骤。"
"路径应在已确认的授权范围内。另等一轮明确回复「批准 <操作单编号>」后才执行。"
"批准仅对该操作单有效。目标、路径、命令或影响范围改变时,重新提交操作单。\n"
"删除业务数据、修改 ACL 或防火墙、操作系统服务、修改注册表、格式化磁盘等高风险操作,"
"默认暂停。确有必要时,在操作单中单独说明原因、影响与恢复方法,获批后再就具体高风险动作二次确认。"
"提权、下载后执行或组合命令按其中影响最大的步骤审批。\n"
"执行后报告实际命令、退出码和关键结果,遮盖密码、令牌、私钥及私钥口令。"
"如果结果偏离操作单,停止后续动作并报告。只执行操作单中明确获批的回滚步骤。"
)
def _connection_handoff(connection, detected_public_ip=None):
addresses = connection.get("addresses") or []
hosts = addresses or [connection["host"]]
public_addresses = [
address for address in addresses
if ipaddress.IPv4Address(address).is_global and not ipaddress.IPv4Address(address).is_multicast
]
ports = connection.get("ports") or [22]
account = connection["account"]
try:
detected_ip = ipaddress.ip_address(detected_public_ip)
except ValueError:
detected_ip = None
outbound = (
{"outboundPublicIp": str(detected_ip)}
if detected_ip and detected_ip.is_global and not detected_ip.is_multicast else {}
)
return {
"host": connection["host"],
"addresses": addresses,
"publicAddresses": public_addresses,
**outbound,
"account": account,
"enabled": connection.get("enabled", False),
"ports": ports,
"hostKeyFingerprints": connection.get("hostKeyFingerprints") or [],
"directories": connection.get("directories") or [],
"services": connection.get("services") or [],
"verification": connection.get("verification") or "Check SSH login and SFTP from the development machine.",
"sshCommands": [f"ssh -p {port} -l {account} {host}" for host in hosts for port in ports],
"sftpCommands": [f"sftp -P {port} {account}@{host}" for host in hosts for port in ports],
"aiInstructions": (
f"请连接 Windows 主机 {connection['host']},使用账号 {account}。"
"先测试 sshCommands 中开发机可达的入口。如果 TCP 超时,请报告试过的地址和端口,"
"并提示检查公网入口、端口映射、云安全组和 Windows 防火墙是否允许开发机的来源 IP。"
"outboundPublicIp 是公网出口;使用前请确认对外的 SSH 地址和端口。"
"\n\nTCP 连通后核对 hostKeyFingerprints。指纹不匹配或无法核对时,停止并报告。"
"如有 authorizedKeys,用其中的公钥指纹匹配开发机本地或 ssh-agent 中的密钥,再指定匹配的密钥连接。若日志出现 Server accepts key,但客户端未完成签名,"
"请先检查开发机能否读取并解锁对应私钥,或当前 SSH 客户端能否使用已加载该密钥的 ssh-agent。"
"若需私钥口令,请操作者在开发机本地输入,再用同一把密钥复测 SSH 和 SFTP。"
"若密钥尚未授权,或原私钥无法找回或解锁,请回传实际要使用的一行 .pub 公钥,"
"请操作者在「远程运维 → 管理公钥 → 导入公钥」中粘贴。"
"如需 Windows 账号密码,使用随附密码,或请操作者在本地 SSH 提示中输入。"
"报告中省略私钥、私钥口令和密码。"
"\n\n登录后用 SSH 执行 hostname,用 SFTP 执行 pwd。两项通过后继续我交代的任务。"
"失败时报告试过的入口、失败阶段和操作者下一步要做什么。"
"文件操作权限不足时,报告具体路径和所需权限,请操作者在 WBSM 授权。"
),
}
def _pick_grant_directories(parent):
picker = tk.Toplevel(parent)
picker.title("选择多个文件夹或磁盘 / Select Folders or Drives")
picker.transient(parent)
picker.grab_set()
picker.columnconfigure(0, weight=1)
picker.rowconfigure(2, weight=1)
current = None
entries = []
selected = []
path_label = ttk.Label(picker)
path_label.grid(row=0, column=0, sticky="w", padx=8, pady=6)
ttk.Label(
picker, text="Ctrl 逐项选,Shift 或鼠标拖选范围。 / Ctrl to select items, Shift or drag for a range.",
).grid(row=1, column=0, sticky="w", padx=8)
folders = tk.Listbox(picker, width=72, height=15, selectmode=tk.EXTENDED, exportselection=False)
folders.grid(row=2, column=0, sticky="nsew", padx=(8, 0), pady=6)
scrollbar = ttk.Scrollbar(picker, orient="vertical", command=folders.yview)
scrollbar.grid(row=2, column=1, sticky="ns", padx=(0, 8), pady=6)
folders.configure(yscrollcommand=scrollbar.set)
def show(path):
nonlocal current, entries
try:
if path is None:
drives = ctypes.windll.kernel32.GetLogicalDrives()
items = [Path(f"{chr(65 + index)}:/") for index in range(26) if drives & (1 << index)]
else:
with os.scandir(path) as children:
items = sorted(
(Path(entry.path) for entry in children if entry.is_dir(follow_symlinks=False)),
key=lambda item: item.name.casefold(),
)
except OSError as exc:
messagebox.showerror(picker.title(), str(exc), parent=picker)
return
current, entries = path, items
path_label.configure(text=str(path) if path else "此电脑 / This PC")
folders.delete(0, "end")
for item in entries:
folders.insert("end", item.name if current else str(item))
update_buttons()
def update_buttons(event=None):
count = len(folders.curselection())
enter_button.state(["!disabled"] if count == 1 else ["disabled"])
add_button.state(["!disabled"] if count or current is not None else ["disabled"])
def enter_folder(event=None):
rows = folders.curselection()
if len(rows) == 1:
show(entries[rows[0]])
def accept():
selected.extend(str(entries[row]) for row in folders.curselection())
if not selected and current is not None:
selected.append(str(current))
picker.destroy()
actions = ttk.Frame(picker)
actions.grid(row=3, column=0, columnspan=2, sticky="w", padx=8, pady=(0, 8))
ttk.Button(actions, text="上一级 / Up", command=lambda: show(
current.parent if current is not None and current.parent != current else None,
)).pack(side="left")
enter_button = ttk.Button(actions, text="打开文件夹 / Open Folder", command=enter_folder)
enter_button.pack(side="left", padx=6)
add_button = ttk.Button(actions, text="加入所选 / Add Selection", command=accept)
add_button.pack(side="left")
ttk.Button(actions, text="取消 / Cancel", command=picker.destroy).pack(side="left", padx=6)
folders.bind("<<ListboxSelect>>", update_buttons)
folders.bind("<Double-Button-1>", enter_folder)
picker.bind("<Escape>", lambda event: picker.destroy())
show(None)
parent.wait_window(picker)
if parent.winfo_exists():
parent.grab_set()
return selected
def show_remote_access(parent, get_public_ip=lambda: None):
dialog = tk.Toplevel(parent)
dialog.title("远程运维 / Remote Access")
dialog.transient(parent)
dialog.columnconfigure(0, weight=1)
output = tk.Text(dialog, height=11, width=74, wrap="word", state="disabled")
output.grid(row=7, column=0, sticky="nsew", padx=8, pady=8)
dialog.rowconfigure(7, weight=1)
results = queue.Queue()
connection = {}
directory_drafts = {}
current_password = None
start_with_app = tk.BooleanVar(master=dialog, value=bool(starts_with_wbsm()))
saved_startup = start_with_app.get()
current_service_status = "Unknown"
service_status = tk.StringVar(master=dialog, value="正在查看服务 / Checking service")
port_status = tk.StringVar(master=dialog, value="SSH/SFTP: —")
def display_service_status(status):
nonlocal current_service_status
current_service_status = status
labels = {
"Running": "运行中 / Running",
"Stopped": "已停止 / Stopped",
"Paused": "已暂停 / Paused",
"Missing": "未安装 / Not installed",
}
service_status.set("OpenSSH: " + labels.get(status, status or "状态未知 / Unknown"))
for button, allowed in (
(start_service, status == "Stopped"),
(stop_service, status in ("Running", "Paused")),
(restart_service, status in ("Running", "Paused")),
):
button.state(["!disabled"] if allowed else ["disabled"])
def copy_text(value):
if value:
dialog.clipboard_clear()
dialog.clipboard_append(value)
def copy_current_password():
if current_password:
copy_text(current_password)
return
messagebox.showinfo(
dialog.title(),
"当前窗口没有可复制的密码,请点击「修改密码」设置或随机生成。\n"
"No password is available in this window. Choose Password to set or generate one.",
parent=dialog,
)
def copy_connection():
start("key-list-for-copy", account=connection["account"])
def copy_connection_result(keys):
handoff = _connection_handoff(connection, get_public_ip())
if keys is not None:
handoff["authorizedKeys"] = [
{"fingerprint": key["fingerprint"], "comment": key.get("comment") or ""}
for key in keys
]
if current_password:
handoff["password"] = current_password
copy_text(json.dumps(handoff, ensure_ascii=False, indent=2))
def copy_ssh_command():
copy_text(_connection_handoff(connection)["sshCommands"][0])
def show_result(message):
output.configure(state="normal")
output.delete("1.0", "end")
output.insert("1.0", message)
output.configure(state="disabled")
def connection_summary(info):
handoff = _connection_handoff(info, get_public_ip())
prompt = handoff.pop("aiInstructions")
return f"给 Codex / Claude Code 的提示词\n{prompt}\n\n" + json.dumps(
handoff, ensure_ascii=False, indent=2,
)
def poll():
nonlocal current_password, saved_startup
if results.empty():
dialog.after(150, poll)
return
action, result, status = results.get_nowait()
display_service_status(status)
if action == "status":
connection.clear()
if result.get("enabled") is True:
connection.update(result)
show_result(connection_summary(result))
elif result.get("enabled") is False:
current_password = None
show_result("远程账号已禁用 / Remote account disabled.")
else:
show_result("尚无保存的接入信息,请点击启用 / No saved connection information. Click Enable.")
elif action == "key-list-for-copy":
if result.get("error"):
if messagebox.askyesno(
dialog.title(),
"无法读取授权公钥。是否继续复制基础接入信息?\n"
"Could not read authorized keys. Copy the connection details anyway?\n\n"
+ result["error"],
parent=dialog,
):
copy_connection_result(None)
else:
copy_connection_result(result.get("keys") or [])
elif action in ("key-list", "key-revoke", "key-revoke-all"):
if action in ("key-revoke", "key-revoke-all") and not result.get("error"):
show_result(connection_summary(connection))
if result.get("error"):
messagebox.showerror(dialog.title(), result["error"], parent=dialog)
else:
dialog.after_idle(lambda: manage_public_keys(result.get("keys") or []))
elif action in ("list-directories", "remove-external-drive-rule"):
if result.get("error"):
messagebox.showerror(dialog.title(), result["error"], parent=dialog)
else:
dialog.after_idle(lambda: manage_directory_grants(result))
elif action == "grant-directory" and result.get("directoryGrantConflict"):
conflict = result["directoryGrantConflict"]
target = f"{conflict['account']} → {conflict['path']}"
if conflict["covered"]:
messagebox.showinfo(
dialog.title(), target + "\n\n"
"已有外部授权规则包含所选权限。WBSM 保留这条规则,请用远程账号验证实际访问。\n"
"An existing rule grants the requested rights. Verify actual access with the remote account.",
parent=dialog,
)
else:
messagebox.showwarning(
dialog.title(), target + "\n\n"
"已有外部授权规则,且未涵盖所选权限。请在 Windows 文件夹安全属性中调整,"
"或在 WBSM 选择具体子目录。\n"
"The existing rule lacks the requested rights. Adjust it in Windows Security properties "
"or choose a specific subfolder in WBSM.",
parent=dialog,
)
show_result(connection_summary(connection))
elif action.startswith("service-"):
if action == "service-startup":
if "startWithApp" in result:
saved_startup = result["startWithApp"]
start_with_app.set(saved_startup)
if result.get("error"):
messagebox.showerror(dialog.title(), result["error"], parent=dialog)
elif action != "status":
password = result.pop("password", None)
grant_results = result.pop("grantResults", [])
if result.get("enabled") is True:
connection.clear()
connection.update(result)
if action == "enable":
saved_startup = start_with_app.get()
if password:
current_password = password
elif result.get("enabled") is False:
connection.clear()
current_password = None
elif action == "password":
current_password = None
if action == "uninstall-ssh" and result.get("enabled") is False:
details = (
"重启 Windows 后完成移除 / Restart Windows to complete removal."
if result.get("restartRequired") else "已移除完成 / Removal complete."
)
elif result.get("enabled") is True:
details = connection_summary(result)
else:
details = json.dumps(result, ensure_ascii=False, indent=2)
if grant_results:
labels = {
"granted": "已授权 / Granted",
"existing_rule": "已有规则 / Existing rule",
"failed": "失败 / Failed",
}
details += "\n\n批量授权结果 / Directory grant results"
for entry in grant_results:
details += f"\n{entry['path']} · {labels[entry['status']]}"
if entry.get("error"):
details += f" · {entry['error']}"
if action == "key" and result.get("importedKeyFingerprint"):
details += f"\n\n已导入公钥 / Imported key: {result['importedKeyFingerprint']}"
if password:
details += f"\n\n新密码 / New password: {password}"
show_result(details)
ports = connection.get("ports") or []
port_status.set("SSH/SFTP: " + (", ".join(map(str, ports)) if ports else "22 (default)" if status == "Missing" else "—"))
change_port.state(["!disabled"] if status == "Running" and len(ports) == 1 else ["disabled"])
if action in ("port", "grant-directory", "grant-directories", "revoke-directory", "revoke-all-directories") and result.get("error"):
messagebox.showerror(dialog.title(), result["error"], parent=dialog)
copy_button.state(["!disabled"] if connection else ["disabled"])
copy_ssh.state(["!disabled"] if connection else ["disabled"])
copy_account.state(["!disabled"] if connection.get("account") else ["disabled"])
copy_password.state(["!disabled"])
enable.state(["!disabled"])
disable.state(["!disabled"])
change_account.state(["!disabled"])
change_password.state(["!disabled"])
import_key.state(["!disabled"] if connection else ["disabled"])
grant_directory.state(["!disabled"] if connection else ["disabled"])
refresh_service.state(["!disabled"])
uninstall_ssh.state(["!disabled"])
startup.state(["!disabled"])
dialog.protocol("WM_DELETE_WINDOW", dialog.destroy)
def start(action, **options):
request = {"action": action, **options}
if action == "enable":
request["startWithApp"] = start_with_app.get()
for control in (
enable, disable, change_account, change_password, import_key,
copy_button, copy_account, copy_password, copy_ssh, startup,
start_service, stop_service, restart_service, refresh_service,
uninstall_ssh, change_port, grant_directory,
):
control.state(["disabled"])
dialog.protocol("WM_DELETE_WINDOW", lambda: None)
if action == "status" or action.startswith("service-"):
service_status.set("OpenSSH: 正在处理 / Working")
elif action not in ("key-list", "key-list-for-copy", "key-revoke", "key-revoke-all", "list-directories", "remove-external-drive-rule"):
show_result("等待管理员授权 / Waiting for administrator approval.")
def run():
try:
result = _load_connection_info() if action == "status" else _configure(request)
except (OSError, ValueError) as exc:
result = {"error": str(exc)}
results.put((
action, result, result.get("serviceStatus") or _service_status(),
))
threading.Thread(target=run, daemon=True).start()
dialog.after(150, poll)
def control_service(action):
if action in ("service-stop", "service-restart") and not messagebox.askokcancel(
dialog.title(),
"此操作可能中断 SSH/SFTP 连接。继续?\n"
"This may interrupt SSH/SFTP connections. Continue?",
parent=dialog,
):
return
start(action)
def manage_directory_grants(result):
entries = result.get("directories") or []
editor = tk.Toplevel(dialog)
editor.title(f"授权目录 / Directory Access — {connection['account']}")
editor.transient(dialog)
editor.grab_set()
editor.columnconfigure(0, weight=1)
editor.rowconfigure(0, weight=1)
table = ttk.Treeview(editor, columns=("path", "permission", "source"), show="headings", selectmode="browse")
table.heading("path", text="路径 / Path")
table.heading("permission", text="权限 / Permission")
table.heading("source", text="来源 / Source")
table.column("source", width=125, stretch=False)
table.column("path", width=320)
table.column("permission", width=150, stretch=False)
table.grid(row=0, column=0, sticky="nsew", padx=(8, 0), pady=8)
scrollbar = ttk.Scrollbar(editor, orient="vertical", command=table.yview)
scrollbar.grid(row=0, column=1, sticky="ns", padx=(0, 8), pady=8)
table.configure(yscrollcommand=scrollbar.set)
grants = {}
external_rules = {}
labels = {"read": "只读 / Read only", "modify": "可修改 / Modify", "custom": "自定义 / Custom"}
for entry in entries:
managed = entry["source"] == "wbsm"
label = "WBSM" if managed else "外部 / External"
row = table.insert("", "end", values=(entry["path"], labels.get(entry["permission"], "—"), label))
if managed:
grants[row] = entry["path"]
elif entry.get("removable"):
external_rules[row] = entry
if not entries:
ttk.Label(editor, text="未找到已记录的授权或盘根目录规则 / No recorded grants or drive root rules").grid(
row=2, column=0, sticky="w", padx=8, pady=(0, 8),
)
warnings = []
if result.get("historyError"):
warnings.append("WBSM 历史授权暂不可用 / Saved grants unavailable: " + result["historyError"])
if result.get("unreadableDrives"):
warnings.append("无法读取盘根权限 / Drive ACL unavailable: " + ", ".join(result["unreadableDrives"]))
if warnings:
ttk.Label(editor, text="\n".join(warnings), wraplength=560).grid(
row=3, column=0, columnspan=2, sticky="w", padx=8, pady=(0, 8),
)
def revoke_selected():
selected = table.selection()
path = grants.get(selected[0]) if selected else None
if path and messagebox.askokcancel(
editor.title(), f"撤销 WBSM 对此路径的授权?\nRevoke WBSM access for this path?\n\n{path}",
parent=editor, default=messagebox.CANCEL,
):
editor.destroy()
start("revoke-directory", path=path, account=connection["account"])
def remove_external():
selected = table.selection()
rule = external_rules.get(selected[0]) if selected else None
if not rule:
return
account = connection["account"]
permission = labels.get(rule["permission"], rule["permission"])
if messagebox.askokcancel(
editor.title(),
f"移除此 Windows 权限规则? / Remove this Windows permission rule?\n\n"
f"{account} → {rule['path']}\n{permission}\n\n"
"继承该规则的子项也会失去这项授权。\nChild items will lose access inherited from this rule.",
parent=editor, default=messagebox.CANCEL,
):
editor.destroy()
start("remove-external-drive-rule", account=account, path=rule["path"],
sid=rule["sid"], rights=rule["rights"])
def revoke_all():
if messagebox.askokcancel(
editor.title(),
"撤销全部 WBSM 目录授权?外部规则保留。\nRevoke all WBSM directory grants? External rules are kept.",
parent=editor, default=messagebox.CANCEL,
):
editor.destroy()
start("revoke-all-directories", account=connection["account"])
def add_grant():
editor.destroy()
choose_directory_grant(lambda: manage_directory_grants(result))
actions = ttk.Frame(editor)
actions.grid(row=1, column=0, columnspan=2, sticky="w", padx=8, pady=(0, 8))
ttk.Button(actions, text="新增授权 / Add Grant", command=add_grant).pack(side="left")
revoke_button = ttk.Button(actions, text="撤销选中 / Revoke Selected", command=revoke_selected)
revoke_button.pack(side="left", padx=6)
revoke_all_button = ttk.Button(actions, text="撤销全部 WBSM 授权 / Revoke All WBSM Grants", command=revoke_all)
revoke_all_button.pack(side="left")
if not grants:
revoke_all_button.state(["disabled"])
revoke_button.state(["disabled"])
external_button = ttk.Button(editor, text="移除外部规则 / Remove External Rule", command=remove_external)
external_button.grid(row=4, column=0, sticky="w", padx=8, pady=(0, 8))
external_button.state(["disabled"])
def update_directory_actions(event=None):
selected = table.selection()
row = selected[0] if selected else None
revoke_button.state(["!disabled"] if row in grants else ["disabled"])
external_button.state(["!disabled"] if row in external_rules else ["disabled"])
table.bind("<<TreeviewSelect>>", update_directory_actions)
def choose_directory_grant(return_to_list):
editor = tk.Toplevel(dialog)
editor.title("新增授权 / Add Directory Grants")
editor.transient(dialog)
editor.grab_set()
account = connection["account"]
ttk.Label(editor, text=f"账号 / Account: {account}").pack(anchor="w", padx=8, pady=6)
paths = tk.Listbox(editor, width=75, height=8, selectmode=tk.EXTENDED)
paths.pack(fill="both", expand=True, padx=8)
draft_paths, draft_mode = directory_drafts.get(account, ([], "read"))
for path in draft_paths:
paths.insert("end", path)
permission = tk.StringVar(master=editor, value=draft_mode)
def cancel_edit():
directory_drafts[account] = (list(paths.get(0, "end")), permission.get())
editor.destroy()
return_to_list()
editor.protocol("WM_DELETE_WINDOW", cancel_edit)
editor.bind("<Escape>", lambda event: cancel_edit())
choices = ttk.Frame(editor)
choices.pack(fill="x", padx=8, pady=6)
ttk.Radiobutton(choices, text="只读 / Read only", value="read", variable=permission).pack(side="left")
ttk.Radiobutton(choices, text="可修改(含删除) / Modify", value="modify", variable=permission).pack(side="left", padx=6)
def add_path():
existing = {os.path.normcase(value) for value in paths.get(0, "end")}
for path in _pick_grant_directories(editor):
path = os.path.normpath(path)
normalized = os.path.normcase(path)
if normalized not in existing:
paths.insert("end", path)
existing.add(normalized)
if paths.size():
apply_button.state(["!disabled"])
def remove_paths():
for index in reversed(paths.curselection()):
paths.delete(index)
if not paths.size():
apply_button.state(["disabled"])
def apply_grants():
selected = list(paths.get(0, "end"))
if not selected:
return
if len(selected) > 100:
messagebox.showerror(editor.title(), "每批最多 100 项 / Up to 100 paths per batch", parent=editor)
return
mode = permission.get()
permission_text = "可修改(含删除) / Modify (including delete)" if mode == "modify" else "只读 / Read only"
if not messagebox.askokcancel(
editor.title(),
f"{account} · {len(selected)} · {permission_text}\n\n"
"权限可由子项继承,盘根授权影响整个盘。\n"
"Child items can inherit permissions. A drive root affects the entire drive.",
parent=editor, default=messagebox.CANCEL,
):
return
directory_drafts.pop(account, None)
editor.destroy()
start("grant-directories", paths=selected, account=account, permission=mode)
actions = ttk.Frame(editor)
actions.pack(fill="x", padx=8, pady=(0, 8))
ttk.Button(actions, text="添加目录 / Add Folder", command=add_path).pack(side="left")
ttk.Button(actions, text="移出选中 / Remove Selected", command=remove_paths).pack(side="left", padx=6)
apply_button = ttk.Button(actions, text="应用授权 / Apply Grants", command=apply_grants)
apply_button.pack(side="left")
apply_button.state(["!disabled"] if paths.size() else ["disabled"])
ttk.Button(actions, text="返回 / Back", command=cancel_edit).pack(side="left", padx=6)
def edit_port():
ports = connection.get("ports") or []
if len(ports) != 1:
return
port = simpledialog.askinteger(
"SSH/SFTP", "输入共用端口 / Enter the shared port (1–65535)",
parent=dialog, initialvalue=ports[0], minvalue=1, maxvalue=65535,
)
if port is None or port == ports[0]:
return
if messagebox.askokcancel(
"SSH/SFTP", "修改端口会重启整台机器的 OpenSSH 服务并可能断开现有连接。\n"
"Changing the port restarts OpenSSH for this machine and may disconnect existing sessions.",
parent=dialog, default=messagebox.CANCEL,
):
start("port", port=port, previousPort=ports[0])
def change_startup():
if current_service_status == "Missing":
return
start("service-startup", startWithApp=start_with_app.get())
def confirm_removal():
if messagebox.askyesno(
"确认移除 / Confirm removal",
"一键移除远程运维?将移除接入并卸载 OpenSSH,SSH/SFTP 会断开。业务文件保留。\n"
"Remove remote access and uninstall OpenSSH? SSH/SFTP will disconnect. Your files are kept.",
default="no", parent=dialog,
):
start("uninstall-ssh")
def manage_public_keys(keys):
editor = tk.Toplevel(dialog)
editor.title("管理公钥 / Manage Public Keys")
editor.transient(dialog)
editor.grab_set()
table = ttk.Treeview(editor, columns=("comment", "fingerprint"), show="headings", selectmode="browse")
table.heading("comment", text="备注 / Comment")
table.heading("fingerprint", text="指纹 / Fingerprint")
table.column("comment", width=190)
table.column("fingerprint", width=405)
table.pack(fill="both", expand=True, padx=8, pady=8)
keys_by_row = {}
for key in keys:
row = table.insert("", "end", values=(key.get("comment") or "—", key["fingerprint"]))
keys_by_row[row] = key
def copy_selected_key():
selected = table.selection()
if selected:
copy_text(keys_by_row[selected[0]].get("publicKey"))
def copy_key_for_ai():
selected = table.selection()
key = keys_by_row[selected[0]] if selected else {}
public_key = key.get("publicKey")
if not public_key:
return
copy_text(
f"这是 Windows 主机 {connection['host']} 为账号 {connection['account']} 授权的一把 SSH 公钥。\n"
f"公钥指纹:{key['fingerprint']}\n"
"请核对开发机上哪把 SSH 密钥与此公钥匹配。若有对应的私钥,"
"请在本机为 SSH 和 SFTP 指定这把密钥,并在连接前核对服务器主机指纹。"
"如果日志显示 Server accepts key 但客户端未完成签名,请检查本机私钥是否已解锁,"
"以及当前 SSH 客户端能否使用已加载密钥的 ssh-agent。需要私钥口令时,请我在开发机本地输入。"
"若没有可用的对应私钥,请回传你实际要使用的一行 .pub 公钥,供我在 WBSM 导入。"
"不要输出私钥、私钥口令或登录密码。主机地址和端口以我提供的 AI 接入信息为准。\n\n"
f"{public_key}"
)
def import_key():
editor.destroy()
select_public_key()
def revoke_selected():
selected = table.selection()
if not selected:
return
fingerprint = table.item(selected[0], "values")[1]
if messagebox.askokcancel(
editor.title(),
f"撤销此公钥的新登录权限?\nRevoke this public key for new logins?\n\n{fingerprint}",
parent=editor, default=messagebox.CANCEL,
):
editor.destroy()
start("key-revoke", account=connection["account"], fingerprint=fingerprint)
def revoke_all():
if messagebox.askokcancel(
editor.title(),
"撤销全部公钥的新登录权限?已有会话可继续使用。\n"
"Revoke all listed public keys for new logins? Existing sessions continue.",
parent=editor, default=messagebox.CANCEL,
):
editor.destroy()
start("key-revoke-all", account=connection["account"])
actions = ttk.Frame(editor)
actions.pack(fill="x", padx=8, pady=(0, 8))
ttk.Button(actions, text="导入公钥 / Import Key", command=import_key).pack(side="left")
revoke = ttk.Button(actions, text="撤销选中 / Revoke Selected", command=revoke_selected)
revoke.pack(side="left", padx=6)
revoke_all_button = ttk.Button(actions, text="撤销全部公钥 / Revoke All Keys", command=revoke_all)
revoke_all_button.pack(side="left", padx=(0, 6))
if not keys:
revoke_all_button.state(["disabled"])
copy_key = ttk.Button(actions, text="复制公钥 / Copy Public Key", command=copy_selected_key)
copy_key.pack(side="left")
copy_key_ai = ttk.Button(actions, text="复制公钥给 AI / Copy Key for AI", command=copy_key_for_ai)
copy_key_ai.pack(side="left", padx=6)
def update_key_actions(event=None):
selected = table.selection()
revoke.state(["!disabled"] if selected else ["disabled"])
can_copy = selected and keys_by_row[selected[0]].get("publicKey")
for button in (copy_key, copy_key_ai):
button.state(["!disabled"] if can_copy else ["disabled"])
update_key_actions()
table.bind("<<TreeviewSelect>>", update_key_actions)
def select_public_key():
editor = tk.Toplevel(dialog)
editor.title("导入公钥 / Import Public Key")
editor.transient(dialog)
editor.grab_set()
ttk.Label(editor, text="粘贴开发机 SSH 公钥,或选择 .pub 文件 / Paste a public key or select a .pub file").pack(
anchor="w", padx=10, pady=(10, 4),
)
entry = tk.Text(editor, width=68, height=4, wrap="char")
entry.pack(fill="both", expand=True, padx=10, pady=(0, 8))
actions = ttk.Frame(editor)
actions.pack(fill="x", padx=10, pady=(0, 10))
def submit(value):
key = value.strip()
if not key or len(key) > 8192 or len(key.splitlines()) != 1:
messagebox.showerror(
editor.title(), "请输入一行 OpenSSH 公钥 / Enter a single OpenSSH public key.", parent=editor,
)
return
editor.destroy()
start("key", publicKey=key)
def browse():
filename = filedialog.askopenfilename(
parent=editor, title=editor.title(), filetypes=(("OpenSSH public key", "*.pub"),),
)
if filename:
try:
with open(filename, encoding="utf-8-sig") as source:
value = source.read(8193)
except (OSError, ValueError) as exc:
messagebox.showerror(editor.title(), str(exc), parent=editor)
return
submit(value)
ttk.Button(actions, text="导入 / Import", command=lambda: submit(entry.get("1.0", "end-1c"))).pack(side="left")
ttk.Button(actions, text="选择 .pub 文件 / Select .pub File", command=browse).pack(side="left", padx=6)
editor.bind("<Escape>", lambda event: editor.destroy())
entry.focus_set()
def edit_credential(action, title, field):
editor = tk.Toplevel(dialog)
editor.title(title)
editor.transient(dialog)
editor.grab_set()
ttk.Label(editor, text=title).pack(anchor="w", padx=10, pady=(10, 2))
entry = ttk.Entry(editor, width=34, show="*" if action == "password" else "")
entry.pack(fill="x", padx=10, pady=(0, 8))
actions = ttk.Frame(editor)
actions.pack(fill="x", padx=10, pady=(0, 10))
def submit(random):
value = entry.get()
if not random and not value:
entry.focus_set()
return
editor.destroy()
start(action, **({} if random else {field: value}))
ttk.Button(actions, text="保存 / Save", command=lambda: submit(False)).pack(side="left")
ttk.Button(actions, text="随机生成 / Generate", command=lambda: submit(True)).pack(side="left", padx=6)
entry.bind("<Return>", lambda event: submit(False))
editor.bind("<Escape>", lambda event: editor.destroy())
entry.focus_set()
buttons = ttk.Frame(dialog)
buttons.grid(row=0, column=0, sticky="ew", padx=8, pady=(8, 0))
enable = ttk.Button(buttons, text="启用 / Enable", command=lambda: start("enable"))
disable = ttk.Button(buttons, text="禁用账号 / Disable Account", command=lambda: start("disable"))
enable.pack(side="left", padx=4)
change_account = ttk.Button(
buttons, text="修改账号 / Account",
command=lambda: edit_credential("rename", "修改账号 / Change account", "name"),
)
change_account.pack(side="left", padx=4)
change_password = ttk.Button(
buttons, text="修改密码 / Password",
command=lambda: edit_credential("password", "修改密码 / Change password", "password"),
)
change_password.pack(side="left", padx=4)
disable.pack(side="left", padx=4)
copy_bar = ttk.Frame(dialog)
copy_bar.grid(row=3, column=0, sticky="ew", padx=8, pady=(6, 0))
copy_account = ttk.Button(
copy_bar, text="复制账号 / Copy Account", command=lambda: copy_text(connection.get("account")),
)
copy_password = ttk.Button(
copy_bar, text="复制密码 / Copy Password", command=copy_current_password,
)
copy_ssh = ttk.Button(copy_bar, text="复制 SSH 命令 / Copy SSH", command=copy_ssh_command)
copy_button = ttk.Button(copy_bar, text="复制 AI 接入信息 / Copy AI Connection", command=copy_connection)
for button in (copy_account, copy_password, copy_ssh, copy_button):
button.state(["disabled"])
button.pack(side="left", padx=4)
import_key = ttk.Button(
copy_bar, text="管理公钥 / Manage Keys",
command=lambda: start("key-list", account=connection["account"]),
)
import_key.state(["disabled"])
import_key.pack(side="left", padx=4)
startup = ttk.Checkbutton(
dialog, text="随 WBSM 启动 / Start with WBSM",
variable=start_with_app, command=change_startup,
)
startup.grid(row=1, column=0, sticky="w", padx=8, pady=(6, 0))
service_bar = ttk.Frame(dialog)
service_bar.grid(row=2, column=0, sticky="ew", padx=8, pady=(6, 0))
ttk.Label(service_bar, textvariable=service_status).pack(side="left", padx=(0, 8))
package_bar = ttk.Frame(dialog)
package_bar.grid(row=6, column=0, sticky="w", padx=8, pady=(0, 6))
bundled = _bundled_installer()
installer = bundled.name if bundled else ""
match = re.search(r"-v([\d.]+)\.msi$", installer, re.IGNORECASE)
package_version = match[1] if match else installer or "未内置 / Not bundled"
ttk.Label(package_bar, text=f"OpenSSH 内置离线包 / Bundled package: {package_version}").pack(side="left")
ttk.Button(
package_bar, text="加速下载 / Faster Download",
command=lambda: webbrowser.open("https://github.com/shellsec/gh-release-fetch"),
).pack(side="left", padx=6)
ttk.Button(
package_bar, text="官方下载 / Official Downloads",
command=lambda: webbrowser.open("https://github.com/PowerShell/Win32-OpenSSH/releases"),
).pack(side="left")
start_service = ttk.Button(service_bar, text="启动服务 / Start", command=lambda: control_service("service-start"))
stop_service = ttk.Button(service_bar, text="停止服务 / Stop", command=lambda: control_service("service-stop"))
restart_service = ttk.Button(service_bar, text="重启服务 / Restart", command=lambda: control_service("service-restart"))
refresh_service = ttk.Button(service_bar, text="刷新 / Refresh", command=lambda: start("status"))
ttk.Label(service_bar, textvariable=port_status).pack(side="left", padx=(0, 4))
change_port = ttk.Button(service_bar, text="修改端口 / Change Port", command=edit_port)
change_port.state(["disabled"])
change_port.pack(side="left", padx=(0, 4))
for button in (start_service, stop_service, restart_service, refresh_service):
button.pack(side="left", padx=4)
help_text = ttk.Label(
dialog,
text=(
"关闭窗口后 SSH/SFTP 继续运行。「随 WBSM 启动」在打开程序时启动服务。\n"
"禁用账号会阻止该账号的新登录。停止服务会停止整台机器的 SSH/SFTP 接入。\n"
"Closing this window leaves SSH/SFTP running. Start with WBSM starts it when you open the app.\n"
"Disable Account blocks new logins for that account. Stop stops SSH/SFTP for everyone."
),
wraplength=590,
justify="left",
)
help_text.grid(row=4, column=0, sticky="w", padx=8, pady=(8, 0))
cleanup_bar = ttk.Frame(dialog)
cleanup_bar.grid(row=5, column=0, sticky="ew", padx=8, pady=(6, 0))
grant_directory = ttk.Button(
cleanup_bar, text="授权目录 / Directory Access",
command=lambda: start("list-directories", account=connection["account"]),
)
grant_directory.state(["disabled"])
grant_directory.pack(side="left", padx=4)
uninstall_ssh = ttk.Button(
cleanup_bar, text="一键移除远程运维 / Remove Remote Access", command=confirm_removal,
)
uninstall_ssh.pack(side="left", padx=4)
ttk.Button(
cleanup_bar, text="复制生产审批约定 / Copy Production Approval",
command=lambda: copy_text(PRODUCTION_APPROVAL_INSTRUCTIONS),
).pack(side="left", padx=4)
start("status")