功能:扩展U盘兼容并优化插拔响应和导出负载

This commit is contained in:
songyiming committed 2026-11-04 19:12:42 +08:00
1 parent b2de05c6a6
commit bb5f554820
9 files changed
+589 -73

No files matched your search

+68 -18
View File
@@ -1,10 +1,12 @@
#!/usr/bin/env python3
"""Install a one-device usbredir POC using a restricted SSH tunnel.
"""Install USB Mass Storage redirection using a restricted SSH tunnel.
Requires paramiko on the admin machine and rustc/cargo/usbredirect on the box.
PVE authentication uses SSH keys or VDI_PVE_SSH_PASSWORD (never stored in files).
This prepares services only. Safely unmount the selected USB volume, start the
box service, then run usb-device-qmp.py attach on the PVE node.
Use --any-storage to accept any pure USB Mass Storage device, or provide an
exact VID/PID/serial identity for the legacy single-device policy. The
deployment installs a QMP watcher so the runtime USB endpoint is restored
after a VM/PVE restart.
"""
import argparse
import json
@@ -13,6 +15,7 @@ from pathlib import Path
import re
import shlex
import subprocess
import tempfile
import time
@@ -35,10 +38,16 @@ def pve_run(client, command):
def install(args, password=None):
import paramiko
if not re.fullmatch(r"[0-9a-f]{4}", args.vendor) or not re.fullmatch(r"[0-9a-f]{4}", args.product):
raise ValueError("VID/PID must be four lowercase hex digits")
if not re.fullmatch(r"[A-Za-z0-9_.-]+", args.serial) or not args.serial:
raise ValueError("POC installer supports nonempty alphanumeric serials only")
exact = all(getattr(args, name, None) for name in ("vendor", "product", "serial"))
if args.any_storage and exact:
raise ValueError("--any-storage cannot be combined with an exact device identity")
if not args.any_storage and not exact:
raise ValueError("choose --any-storage or provide --vendor, --product and --serial")
if exact:
if not re.fullmatch(r"[0-9a-f]{4}", args.vendor) or not re.fullmatch(r"[0-9a-f]{4}", args.product):
raise ValueError("VID/PID must be four lowercase hex digits")
if not re.fullmatch(r"[A-Za-z0-9_.-]+", args.serial) or not args.serial:
raise ValueError("installer supports nonempty alphanumeric serials only")
if not re.fullmatch(r"[a-z_][a-z0-9_-]*@[A-Za-z0-9.-]+", args.box):
raise ValueError("invalid box SSH destination")
if args.vm < 100:
@@ -80,12 +89,33 @@ p.chmod(0o600)
f'command="/bin/false" {pubkey}')
box_run(args.box, f"python3 - {shlex.quote(backup)} {shlex.quote(auth_line)}", auth_script)
stage = box_run(args.box, "mktemp -d /tmp/vdi-usb-deploy.XXXXXX").strip()
subprocess.run(["scp", "-q", str(repo / "terminal/usb-monitor/etc/vdi-usb-monitor.service"),
f"{args.box}:{stage}/vdi-usb-monitor.service"], check=True)
env = f'VDI_USB_VENDOR={args.vendor}\nVDI_USB_PRODUCT={args.product}\nVDI_USB_SERIAL={args.serial}\n'
rule = (f'# VDI USB device POC: only the approved device\nSUBSYSTEM=="block", '
f'ATTRS{{idVendor}}=="{args.vendor}", ATTRS{{idProduct}}=="{args.product}", '
f'ATTRS{{serial}}=="{args.serial}", ENV{{UDISKS_IGNORE}}="1"\n')
service_text = (repo / "terminal/usb-monitor/etc/vdi-usb-monitor.service").read_text()
if args.any_storage:
service_exec = ("ExecStart=/usr/local/libexec/vdi-usb-monitor serve "
"--any-storage --listen 127.0.0.1:40001")
else:
service_exec = (f"ExecStart=/usr/local/libexec/vdi-usb-monitor serve --vendor {args.vendor} "
f"--product {args.product} --serial {args.serial} --listen 127.0.0.1:40001")
service_text = re.sub(r"^ExecStart=.*$", service_exec, service_text, flags=re.MULTILINE)
service_fd, service_path = tempfile.mkstemp(prefix="vdi-usb-monitor-", suffix=".service")
os.close(service_fd)
service_tmp = Path(service_path)
service_tmp.write_text(service_text)
try:
subprocess.run(["scp", "-q", str(service_tmp),
f"{args.box}:{stage}/vdi-usb-monitor.service"], check=True)
finally:
service_tmp.unlink(missing_ok=True)
if args.any_storage:
env = 'VDI_USB_MODE=any-storage\n'
rule = ('# VDI USB: ignore USB disks locally; the monitor checks exclusive use\n'
'SUBSYSTEM=="block", ENV{ID_BUS}=="usb", ENV{ID_TYPE}=="disk", '
'ENV{UDISKS_IGNORE}="1"\n')
else:
env = f'VDI_USB_VENDOR={args.vendor}\nVDI_USB_PRODUCT={args.product}\nVDI_USB_SERIAL={args.serial}\n'
rule = (f'# VDI USB device: only the approved device\nSUBSYSTEM=="block", '
f'ATTRS{{idVendor}}=="{args.vendor}", ATTRS{{idProduct}}=="{args.product}", '
f'ATTRS{{serial}}=="{args.serial}", ENV{{UDISKS_IGNORE}}="1"\n')
box_install = '''import pathlib,shutil,subprocess,sys
stage,backup,env,rule=sys.argv[1:]
backup=pathlib.Path(backup)
@@ -126,18 +156,36 @@ NoNewPrivileges=yes
PrivateTmp=yes
[Install]
WantedBy=multi-user.target
'''
qmp_args = ("--any-storage" if args.any_storage else
f"--vendor {args.vendor} --product {args.product}")
qmp_unit = f'''[Unit]
Description=VDI USB QMP endpoint for VM {args.vm}
After=network-online.target vdi-usb-tunnel-{args.vm}.service
Wants=network-online.target
[Service]
Type=simple
ExecStart=/usr/local/libexec/vdi-usb-device-qmp.py watch --vm {args.vm} --port 40001 --bus ehci-2.0 {qmp_args}
Restart=always
RestartSec=3
NoNewPrivileges=yes
PrivateTmp=yes
[Install]
WantedBy=multi-user.target
'''
sftp = client.open_sftp()
try:
for path, content in [(f"{host_dir}/known_hosts", known),
(f"/etc/systemd/system/vdi-usb-tunnel-{args.vm}.service", unit),
(f"/etc/systemd/system/vdi-usb-qmp-{args.vm}.service", qmp_unit),
("/usr/local/libexec/vdi-usb-device-qmp.py", (repo / "tools/usb-device-qmp.py").read_text())]:
with sftp.open(path, "w") as f:
f.write(content)
sftp.chmod(path, 0o600 if "known_hosts" in path else 0o644)
mode = 0o600 if "known_hosts" in path else (0o755 if path.endswith("usb-device-qmp.py") else 0o644)
sftp.chmod(path, mode)
finally:
sftp.close()
pve_run(client, f"systemctl daemon-reload && systemctl enable --now vdi-usb-tunnel-{args.vm}.service")
pve_run(client, f"systemctl daemon-reload && systemctl enable --now vdi-usb-tunnel-{args.vm}.service vdi-usb-qmp-{args.vm}.service")
print(json.dumps({"box_backup": backup, "pve_directory": host_dir,
"state": "prepared; unmount USB safely before starting export"}, indent=2))
finally:
@@ -149,7 +197,9 @@ if __name__ == "__main__":
parser.add_argument("--pve", required=True)
parser.add_argument("--box", required=True)
parser.add_argument("--vm", type=int, required=True)
parser.add_argument("--vendor", required=True)
parser.add_argument("--product", required=True)
parser.add_argument("--serial", required=True)
parser.add_argument("--any-storage", action="store_true",
help="accept any pure USB Mass Storage device")
parser.add_argument("--vendor")
parser.add_argument("--product")
parser.add_argument("--serial")
install(parser.parse_args())