2025-09-08 17:01:50 +08:00
|
|
|
|
package com.yj.earth.common.util;
|
|
|
|
|
|
|
|
|
|
|
|
import lombok.extern.slf4j.Slf4j;
|
|
|
|
|
|
import oshi.SystemInfo;
|
|
|
|
|
|
import oshi.hardware.*;
|
|
|
|
|
|
|
|
|
|
|
|
import java.security.MessageDigest;
|
|
|
|
|
|
import java.util.HexFormat;
|
2025-09-16 11:41:45 +08:00
|
|
|
|
import java.util.List;
|
2025-09-08 17:01:50 +08:00
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
|
* 服务器唯一标识工具类
|
|
|
|
|
|
* 基于CPU、主板、磁盘、网卡硬件信息生成唯一标识、不更换核心硬件则标识不变
|
|
|
|
|
|
*/
|
|
|
|
|
|
@Slf4j
|
|
|
|
|
|
public class ServerUniqueIdUtil {
|
|
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
|
* 获取服务器唯一标识
|
|
|
|
|
|
*/
|
|
|
|
|
|
public static String getServerUniqueId() {
|
|
|
|
|
|
// 初始化系统信息(oshi核心入口)
|
|
|
|
|
|
SystemInfo systemInfo = new SystemInfo();
|
|
|
|
|
|
HardwareAbstractionLayer hardware = systemInfo.getHardware();
|
|
|
|
|
|
|
|
|
|
|
|
try {
|
|
|
|
|
|
// 收集稳定的核心硬件信息
|
|
|
|
|
|
StringBuilder hardwareRawInfo = new StringBuilder();
|
|
|
|
|
|
|
|
|
|
|
|
// CPU唯一标识
|
|
|
|
|
|
CentralProcessor cpu = hardware.getProcessor();
|
|
|
|
|
|
String cpuId = cpu.getProcessorIdentifier().getProcessorID();
|
|
|
|
|
|
if (cpuId != null && !cpuId.trim().isEmpty()) {
|
|
|
|
|
|
hardwareRawInfo.append(cpuId).append("|");
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// 主板UUID
|
|
|
|
|
|
ComputerSystem mainBoard = hardware.getComputerSystem();
|
|
|
|
|
|
String boardUuid = mainBoard.getHardwareUUID();
|
|
|
|
|
|
if (boardUuid != null && !boardUuid.trim().isEmpty()) {
|
|
|
|
|
|
hardwareRawInfo.append(boardUuid).append("|");
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// 第一个物理磁盘序列号
|
|
|
|
|
|
List<HWDiskStore> disks = hardware.getDiskStores();
|
|
|
|
|
|
for (HWDiskStore disk : disks) {
|
|
|
|
|
|
// 过滤虚拟磁盘(
|
|
|
|
|
|
if (!disk.getModel().toLowerCase().contains("virtual") && disk.getSize() > 0) {
|
|
|
|
|
|
String diskSerial = disk.getSerial();
|
|
|
|
|
|
if (diskSerial != null && !diskSerial.trim().isEmpty()) {
|
|
|
|
|
|
hardwareRawInfo.append(diskSerial).append("|");
|
|
|
|
|
|
break;
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// 第一个物理网卡MAC地址
|
|
|
|
|
|
List<NetworkIF> netCards = hardware.getNetworkIFs();
|
|
|
|
|
|
for (NetworkIF netCard : netCards) {
|
|
|
|
|
|
String mac = netCard.getMacaddr();
|
|
|
|
|
|
// 过滤条件非空、非全零MAC、非回环网卡
|
|
|
|
|
|
if (mac != null && !mac.trim().isEmpty() && !mac.startsWith("00:00:00:00:00:00")) {
|
|
|
|
|
|
hardwareRawInfo.append(mac).append("|");
|
|
|
|
|
|
break;
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// MD5哈希
|
|
|
|
|
|
MessageDigest md = MessageDigest.getInstance("MD5");
|
|
|
|
|
|
byte[] hashBytes = md.digest(hardwareRawInfo.toString().getBytes());
|
|
|
|
|
|
|
|
|
|
|
|
// 字节数组转十六进制字符串
|
|
|
|
|
|
return HexFormat.of().formatHex(hashBytes).toUpperCase();
|
|
|
|
|
|
|
|
|
|
|
|
} catch (Exception e) {
|
|
|
|
|
|
return "unknown";
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|