java获取机器号_(转)JAVA获得机器码的实现
http://yangshangchuan.iteye.com/blog/2012401
首先,定義了一個統一的接口,以支持不同操作系統不同實現的透明切換:
Java代碼? 收藏代碼
/**
*生成機器碼的接口,不同平臺有不同實現
* @author 楊尚川
*/
public interface SequenceService {
/**
* 獲取機器碼
* @return? 機器碼
*/
public String getSequence();
}
其次,定義了一個抽象類,實現了一些通用的功能,如生成MD5摘要、將很長的字符串以固定的位數分割開,以便于人類閱讀(如將機器碼 71F5DA7F495E7F706D47F3E63DC6349A 每4個一組,以-分割為71F5-DA7F-495E-7F70-6D47-F3E6-3DC6-349A)、利用sigar來生成機器碼。這里需要在pom.xml中加入sigar依賴。
Xml代碼? 收藏代碼
org.fusesource
sigar
1.6.4
log4j
log4j
Java代碼? 收藏代碼
import org.apdplat.module.system.service.PropertyHolder;
import org.apdplat.platform.log.APDPlatLogger;
import org.apdplat.platform.util.ConvertUtils;
import org.apdplat.platform.util.FileUtils;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashSet;
import java.util.Properties;
import java.util.Set;
import org.apdplat.platform.log.APDPlatLoggerFactory;
import org.hyperic.sigar.Mem;
import org.hyperic.sigar.NetFlags;
import org.hyperic.sigar.NetInterfaceConfig;
import org.hyperic.sigar.Sigar;
/**
*機器碼生成的通用服務
* @author 楊尚川
*/
public abstract class AbstractSequenceService?? implements SequenceService{
protected final APDPlatLogger LOG = APDPlatLoggerFactory.getAPDPlatLogger(getClass());
/**
* 對一段String生成MD5摘要信息
* @param message 要摘要的String
* @return 生成的MD5摘要信息
*/
protected String getMD5(String message) {
message += "{apdplat}";
try {
MessageDigest md = MessageDigest.getInstance("MD5");
LOG.debug("MD5摘要長度:" + md.getDigestLength());
byte[] b = md.digest(message.getBytes("utf-8"));
String md5 = ConvertUtils.byte2HexString(b)+message.length();
return getSplitString(md5);
} catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
LOG.error("MD5摘要失敗",e);
}
return null;
}
/**
* 將很長的字符串以固定的位數分割開,以便于人類閱讀
* @param str
* @return
*/
protected String getSplitString(String str){
return getSplitString(str, "-", 4);
}
/**
* 將很長的字符串以固定的位數分割開,以便于人類閱讀
* 如將
* 71F5DA7F495E7F706D47F3E63DC6349A
* 以-,每4個一組,則分割為
* 71F5-DA7F-495E-7F70-6D47-F3E6-3DC6-349A
* @param str 字符串
* @param split 分隔符
* @param length 長度
* @return
*/
protected String getSplitString(String str, String split, int length){
int len=str.length();
StringBuilder temp=new StringBuilder();
for(int i=0;i
if(i%length==0 && i>0){
temp.append(split);
}
temp.append(str.charAt(i));
}
String[] attrs=temp.toString().split(split);
StringBuilder finalMachineCode=new StringBuilder();
for(String attr : attrs){
if(attr.length()==length){
finalMachineCode.append(attr).append(split);
}
}
String result=finalMachineCode.toString().substring(0, finalMachineCode.toString().length()-1);
return result;
}
/**
* 利用sigar來生成機器碼,當然這個實現不是很好,無法獲得CPU ID,希望有興趣的朋友來改進這個實現
* @param osName 操作系統類型
* @return 機器碼
*/
protected String getSigarSequence(String osName) {
try {
File libFile = new File(FileUtils.getAbsolutePath("/WEB-INF/lib/"+PropertyHolder.getProperty("libsigar."+osName)));
LOG.debug("libsigar."+osName+" : "+libFile.getAbsolutePath());
System.load(libFile.getAbsolutePath());
Set result = new HashSet<>();
Sigar sigar = new Sigar();
String[] ifaces = sigar.getNetInterfaceList();
for (String iface : ifaces) {
NetInterfaceConfig cfg = sigar.getNetInterfaceConfig(iface);??????????????? if (NetFlags.LOOPBACK_ADDRESS.equals(cfg.getAddress()) || (cfg.getFlags() & NetFlags.IFF_LOOPBACK) != 0
|| NetFlags.NULL_HWADDR.equals(cfg.getHwaddr())) {
continue;
}
String mac = cfg.getHwaddr();
result.add(mac);
LOG.debug("mac: " + mac);
}
if(result.size()<1){
return null;
}
Properties props = System.getProperties();
String javaVersion = props.getProperty("java.version");
result.add(javaVersion);
LOG.debug("Java的運行環境版本:??? " + javaVersion);
String javaVMVersion = props.getProperty("java.vm.version");
result.add(javaVMVersion);
LOG.debug("Java的虛擬機實現版本:??? " + props.getProperty("java.vm.version"));
String osVersion = props.getProperty("os.version");
result.add(osVersion);
LOG.debug("操作系統的版本:??? " + props.getProperty("os.version"));
Mem mem = sigar.getMem();
// 內存總量
String totalMem = mem.getTotal() / 1024L + "K av";
LOG.debug("內存總量:??? " + totalMem);
result.add(totalMem);
LOG.debug("result:??? " + result);
String machineCode = getMD5(result.toString());
return machineCode;
} catch (Throwable ex) {
LOG.error("生成 "+osName+" 平臺下的機器碼失敗", ex);
}
return null;
}
}
最后,我們分別看看不同平臺的實現。
Windows:
Java代碼? 收藏代碼
/**
*在Windows平臺上生成機器碼
* @author 楊尚川
*/
public final class WindowsSequenceService extends AbstractSequenceService{
@Override
public String getSequence() {
String cpuID=getCPUSerial();
String hdID=getHDSerial("C");
if(cpuID==null || hdID==null){
return null;
}
String machineCode = getMD5(cpuID+hdID);
return machineCode;
}
/**
*
* @param drive 硬盤驅動器分區 如C,D
* @return 該分區的卷標
*/
private String getHDSerial(String drive) {
StringBuilder result = new StringBuilder();
try {
File file = File.createTempFile("tmp", ".vbs");
file.deleteOnExit();
try (FileWriter fw = new java.io.FileWriter(file)) {
String vbs = "Set objFSO = CreateObject(\"Scripting.FileSystemObject\")\n"
+ "Set colDrives = objFSO.Drives\n" + "Set objDrive = colDrives.item(\"" + drive + "\")\n"
+ "Wscript.Echo objDrive.SerialNumber";
fw.write(vbs);
}
Process p = Runtime.getRuntime().exec("cscript //NoLogo " + file.getPath());
try (BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()))) {
String line;
while ((line = input.readLine()) != null) {
result.append(line);
}
}
file.delete();
} catch (Throwable e) {
LOG.error("生成HDSerial失敗", e);
}
if (result.length() < 1) {
LOG.info("無磁盤ID被讀取");
}
return result.toString();
}
/**
* 獲取CPU號,多CPU時,只取第一個
* @return
*/
private String getCPUSerial() {
StringBuilder result = new StringBuilder();
try {
File file = File.createTempFile("tmp", ".vbs");
file.deleteOnExit();
try (FileWriter fw = new FileWriter(file)) {
String vbs = "On Error Resume Next \r\n\r\n" + "strComputer = \".\"? \r\n"
+ "Set objWMIService = GetObject(\"winmgmts:\" _ \r\n"
+ "??? & \"{impersonationLevel=impersonate}!\\\\\" & strComputer & \"\\root\\cimv2\") \r\n"
+ "Set colItems = objWMIService.ExecQuery(\"Select * from Win32_Processor\")? \r\n "
+ "For Each objItem in colItems\r\n " + "??? Wscript.Echo objItem.ProcessorId? \r\n "
+ "??? exit for? ' do the first cpu only! \r\n" + "Next??????????????????? ";
fw.write(vbs);
}
Process p = Runtime.getRuntime().exec("cscript //NoLogo " + file.getPath());
try (BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()))) {
String line;
while ((line = input.readLine()) != null) {
result.append(line);
}
}
file.delete();
} catch (Throwable e) {
LOG.error("生成CPUSerial失敗", e);
}
if (result.length() < 1) {
LOG.info("無CPU_ID被讀取");
}
return result.toString();
}
public static void main(String[] args) {
SequenceService s = new WindowsSequenceService();
String seq = s.getSequence();
System.out.println(seq);
}
}
Linux:
Java代碼? 收藏代碼
/**
*在Linux平臺上生成機器碼
* @author 楊尚川
*/
public class LinuxSequenceService? extends AbstractSequenceService{
@Override
public String getSequence() {
return getSigarSequence("linux");
}
public static void main(String[] args) {
SequenceService s = new LinuxSequenceService();
String seq = s.getSequence();
System.out.println(seq);
}
}
Mac OS X:
Java代碼? 收藏代碼
/**
*在Mac OS X平臺上生成機器碼
* @author 楊尚川
*/
public class MacSequenceService??? extends AbstractSequenceService{
@Override
public String getSequence() {
return getSigarSequence("mac");
}
public static void main(String[] args) {
SequenceService s = new MacSequenceService();
String seq = s.getSequence();
System.out.println(seq);
}
}
Solaris:
Java代碼? 收藏代碼
/**
*在Solaris平臺上生成機器碼
* @author 楊尚川
*/
public class SolarisSequenceService??? extends AbstractSequenceService{
@Override
public String getSequence() {
return getSigarSequence("solaris");
}
public static void main(String[] args) {
SequenceService s = new SolarisSequenceService();
String seq = s.getSequence();
System.out.println(seq);
}
}
已有 0 人發表留言,猛擊->> 這里<
ITeye推薦
總結
以上是生活随笔為你收集整理的java获取机器号_(转)JAVA获得机器码的实现的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 缺钙的症状有哪些
- 下一篇: 土人参叶的功效与作用