#!/usr/bin/env python # -*- coding: utf-8 -*- """ HW_ID 获取工具 ============== 在服务器上运行此脚本,即可获取本机 HW_ID。 HW_ID 用于向授权管理平台申请授权码。 用法: python get_hw_id.py 输出示例: ================================ 本机 HW_ID: a1b2c3d4e5f6a7b8 ================================ """ import hashlib, socket, platform, subprocess, re, uuid def get_macs(): """获取所有 MAC 地址,取前 2 个参与指纹计算""" macs = [] for iface in uuid.getnode(): # fallback pass try: if platform.system() == 'Windows': r = subprocess.run(['getmac', '/fo', 'csv', '/nh'], capture_output=True, text=True, timeout=5) for line in r.stdout.strip().split('\n'): parts = line.strip().strip('"').split('","') if parts and re.match(r'^[0-9A-Fa-f]{12}$', parts[0].replace('-', '')): macs.append(parts[0].replace('-', '').lower()) else: for iface in sorted(subprocess.check_output( ['ls', '/sys/class/net'], text=True).strip().split('\n')): try: with open(f'/sys/class/net/{iface}/address') as f: mac = f.read().strip().replace(':', '').lower() if mac and mac != '000000000000': macs.append(mac) except: pass except: pass # 去重取前2 seen = set() unique = [] for m in macs: if m not in seen: seen.add(m) unique.append(m) if len(unique) >= 2: break return unique def get_disks(): """获取硬盘序列号,取第一个参与指纹计算""" serials = [] try: if platform.system() == 'Windows': r = subprocess.run( ['wmic', 'diskdrive', 'get', 'serialnumber'], capture_output=True, text=True, timeout=5) for line in r.stdout.strip().split('\n')[1:]: s = line.strip() if s: serials.append(s) except: pass return serials def get_hw_id(): """计算 HW_ID""" macs = get_macs() disks = get_disks() hostname = platform.node().lower() # 取前2个MAC、第1个硬盘、主机名 raw = { 'macs': macs[:2], 'disk': disks[0] if disks else '', 'hostname': hostname, } raw_str = '|'.join(macs[:2]) + '|' + (disks[0] if disks else '') + '|' + hostname fingerprint = hashlib.sha256(raw_str.encode()).hexdigest()[:16] return fingerprint, raw if __name__ == '__main__': hw_id, raw = get_hw_id() print() print('=' * 50) print(f' 本机 HW_ID: {hw_id}') print('=' * 50) print() print('参与指纹计算的信息:') print(f' MAC 地址(前2个): {", ".join(raw["macs"]) if raw["macs"] else "无"}') print(f' 硬盘序列号(第1个): {raw["disk"] if raw["disk"] else "无"}') print(f' 主机名: {raw["hostname"]}') print() print('将上方 HW_ID 提供给管理员即可生成授权码。')