73 lines
2.0 KiB
Python
73 lines
2.0 KiB
Python
"""
|
||
机器硬件指纹生成
|
||
通过 MAC 地址 + 磁盘序列号 + CPU ID 生成稳定的唯一编码,
|
||
使用 SHA256 哈希,保证同一台机器每次生成结果一致。
|
||
"""
|
||
import hashlib
|
||
import platform
|
||
import subprocess
|
||
import uuid
|
||
|
||
|
||
def _run_wmic(args: list[str]) -> str:
|
||
"""执行 wmic 命令并返回输出(仅 Windows)"""
|
||
try:
|
||
result = subprocess.run(
|
||
["wmic"] + args,
|
||
capture_output=True,
|
||
text=True,
|
||
timeout=10,
|
||
encoding="utf-8",
|
||
errors="ignore",
|
||
)
|
||
return result.stdout.strip()
|
||
except Exception:
|
||
return ""
|
||
|
||
|
||
def get_mac_address() -> str:
|
||
"""获取网卡 MAC 地址"""
|
||
mac = uuid.getnode()
|
||
return ":".join(
|
||
"%02x" % ((mac >> (8 * i)) & 0xFF) for i in range(5, -1, -1)
|
||
)
|
||
|
||
|
||
def get_disk_serial() -> str:
|
||
"""获取主磁盘序列号(Windows)"""
|
||
output = _run_wmic(["diskdrive", "get", "serialnumber"])
|
||
lines = [l.strip() for l in output.splitlines() if l.strip() and l.strip().lower() != "serialnumber"]
|
||
return lines[0] if lines else ""
|
||
|
||
|
||
def get_cpu_id() -> str:
|
||
"""获取 CPU ProcessorId(Windows)"""
|
||
output = _run_wmic(["cpu", "get", "processorid"])
|
||
lines = [l.strip() for l in output.splitlines() if l.strip() and l.strip().lower() != "processorid"]
|
||
return lines[0] if lines else ""
|
||
|
||
|
||
def generate_client_code() -> str:
|
||
"""
|
||
生成机器唯一编码。
|
||
组合多个硬件特征,避免单一特征缺失导致不稳定。
|
||
"""
|
||
parts = [
|
||
get_mac_address(),
|
||
get_disk_serial(),
|
||
get_cpu_id(),
|
||
platform.node(), # 计算机名作为兜底
|
||
]
|
||
raw = "|".join(parts)
|
||
return hashlib.sha256(raw.encode("utf-8")).hexdigest()
|
||
|
||
|
||
def get_machine_summary() -> dict:
|
||
"""返回机器基本信息(用于展示)"""
|
||
return {
|
||
"hostname": platform.node(),
|
||
"system": f"{platform.system()} {platform.release()}",
|
||
"mac": get_mac_address(),
|
||
"client_code": generate_client_code(),
|
||
}
|