Java hardware information read the serial number Windows, linux system

Collection of Java reading system hardware information online usable code, use the Windows script to read, use the command on linux or read the script, but rights problems in linux!

import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.swing.LookAndFeel;

import org.apache.log4j.Logger;

public class HardWareUtils {
	private static Logger logger = Logger.getLogger(HardWareUtils.class);
	private static String OSName =System.getProperty("os.name").toLowerCase();
	public static List<String> listResult = new ArrayList<String>();
	public HardWareUtils() {
		logger.info("------当前系统版本-----:"+OSName);
	}
	/**
	 * 获取当前操作系统名称
	 */
	public static String getOSName() {
		return OSName;
	}
 
	// 主板序列号 windows
	private static String getMainBordId_windows() {
		String result = "";
		try {
			File file = File.createTempFile("realhowto", ".vbs");
			file.deleteOnExit();
			FileWriter fw = new java.io.FileWriter(file);
 
			String vbs = "Set objWMIService = GetObject(\"winmgmts:\\\\.\\root\\cimv2\")\n"
					+ "Set colItems = objWMIService.ExecQuery _ \n" + "   (\"Select * from Win32_BaseBoard\") \n"
					+ "For Each objItem in colItems \n" + "    Wscript.Echo objItem.SerialNumber \n"
					+ "    exit for  ' do the first cpu only! \n" + "Next \n";
 
			fw.write(vbs);
			fw.close();
			Process p = Runtime.getRuntime().exec("cscript //NoLogo " + file.getPath());
			BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
			String line;
			while ((line = input.readLine()) != null) {
				result += line;
			}
			input.close();
		} catch (Exception e) {
			logger.error("获取主板信息错误", e);
		}
		return result.trim();
	}
 
	// 主板序列号 linux
	private static String getMainBordId_linux() {
 
		String result = "";
		String maniBord_cmd = "dmidecode | grep 'Serial Number' | awk '{print $3}' | tail -1";
		Process p;
		try {
			p = Runtime.getRuntime().exec(new String[] { "sh", "-c", maniBord_cmd });// 管道
			BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
			String line;
			while ((line = br.readLine()) != null) {
				result += line;
				break;
			}
			br.close();
		} catch (IOException e) {
			logger.error("获取主板信息错误", e);
		}
		return result;
	}
 
	/**
	 * 获取mac地址 (如果Linux下有eth0这个网卡)
	 */
	private static String getMAC_linux() {
		String mac = null;
		BufferedReader bufferedReader = null;
		Process process = null;
		try {
			// linux下的命令,一般取eth0作为本地主网卡
			process = Runtime.getRuntime().exec("ifconfig eth0");
			// 显示信息中包含有mac地址信息
			bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
			String line = null;
			int index = -1;
			while ((line = bufferedReader.readLine()) != null) {
				// 寻找标示字符串[hwaddr]
				index = line.toLowerCase().indexOf("hwaddr");
				if (index >= 0) {// 找到了
					// 取出mac地址并去除2边空格
					mac = line.substring(index + "hwaddr".length() + 1).trim();
					break;
				}
			}
		} catch (IOException e) {
			logger.error("获取mac信息错误", e);
		} finally {
			try {
				if (bufferedReader != null) {
					bufferedReader.close();
				}
			} catch (IOException e1) {
				logger.error("获取mac信息错误", e1);
			}
			bufferedReader = null;
			process = null;
		}
		return mac;
	}
 
    /**
    * 获取Linux的mac
    */
	private static String getMAC_linuxs() {
		
		String mac = null;
		BufferedReader bufferedReader = null;
		Process process = null;
		try {
			// linux下的命令,一般取eth0作为本地主网卡
			process = Runtime.getRuntime().exec("ifconfig");
			// 显示信息中包含有mac地址信息
			bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
			String line = null;
			int index = -1;
			 while ((line = bufferedReader.readLine()) != null) 
			 {
				 Pattern pat = Pattern.compile("\\b\\w+:\\w+:\\w+:\\w+:\\w+:\\w+\\b");
				 Matcher mat= pat.matcher(line);
				 if(mat.find())
				 {
					 mac=mat.group(0);
				 }
			 }
 
		} catch (IOException e) {
			logger.error("获取mac信息错误", e);
		} finally {
			try {
				if (bufferedReader != null) {
					bufferedReader.close();
				}
			} catch (IOException e1) {
				logger.error("获取mac信息错误", e1);
			}
			bufferedReader = null;
			process = null;
		}
		return mac;
	}
 
	/**
	 * 获取widnows网卡的mac地址.
	 */
	private static String getMAC_windows() {
		InetAddress ip = null;
		NetworkInterface ni = null;
		List<String> macList = new ArrayList<String>();
		try {
			Enumeration<NetworkInterface> netInterfaces = (Enumeration<NetworkInterface>) NetworkInterface
					.getNetworkInterfaces();
			while (netInterfaces.hasMoreElements()) {
				ni = (NetworkInterface) netInterfaces.nextElement();
				// ----------特定情况,可以考虑用ni.getName判断
				// 遍历所有ip
				Enumeration<InetAddress> ips = ni.getInetAddresses();
				while (ips.hasMoreElements()) {
					ip = (InetAddress) ips.nextElement();
					if (!ip.isLoopbackAddress() // 非127.0.0.1
							&& ip.getHostAddress().matches("(\\d{1,3}\\.){3}\\d{1,3}")) {
						macList.add(getMacFromBytes(ni.getHardwareAddress()));
					}
				}
			}
		} catch (Exception e) {
			logger.error("获取mac错误", e);
		}
		if (macList.size() > 0) {
			return macList.get(0);
		} else {
			return "";
		}
 
	}
 
	private static String getMacFromBytes(byte[] bytes) {
		StringBuffer mac = new StringBuffer();
		byte currentByte;
		boolean first = false;
		for (byte b : bytes) {
			if (first) {
				mac.append("-");
			}
			currentByte = (byte) ((b & 240) >> 4);
			mac.append(Integer.toHexString(currentByte));
			currentByte = (byte) (b & 15);
			mac.append(Integer.toHexString(currentByte));
			first = true;
		}
		return mac.toString().toUpperCase();
	}
 
	/**
	 * 获取CPU序列号 Windows
	 * 
	 * @return
	 */
	private static String getCPUID_Windows() {
		String result = "";
		try {
			File file = File.createTempFile("tmp", ".vbs");
			file.deleteOnExit();
			FileWriter fw = new java.io.FileWriter(file);
			String vbs = "Set objWMIService = GetObject(\"winmgmts:\\\\.\\root\\cimv2\")\n"
					+ "Set colItems = objWMIService.ExecQuery _ \n" + "   (\"Select * from Win32_Processor\") \n"
					+ "For Each objItem in colItems \n" + "    Wscript.Echo objItem.ProcessorId \n"
					+ "    exit for  ' do the first cpu only! \n" + "Next \n";
 
			fw.write(vbs);
			fw.close();
			Process p = Runtime.getRuntime().exec("cscript //NoLogo " + file.getPath());
			BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
			String line;
			while ((line = input.readLine()) != null) {
				result += line;
			}
			input.close();
			file.delete();
		} catch (Exception e) {
			logger.error("获取windows cpu信息错误", e);
		}
		return result.trim();
	}
 
	/**
	 * 获取CPU序列号 linux
	 * 
	 * @return
	 */
	private static String getCPUID_linux() throws InterruptedException {
		String result = "";
		String CPU_ID_CMD = "dmidecode";
		BufferedReader bufferedReader = null;
		Process p = null;
		try {
			p = Runtime.getRuntime().exec(new String[] { "sh", "-c", CPU_ID_CMD });// 管道
			bufferedReader = new BufferedReader(new InputStreamReader(p.getInputStream()));
			String line = null;
			int index = -1;
			while ((line = bufferedReader.readLine()) != null) {
				// 寻找标示字符串[hwaddr]
				index = line.toLowerCase().indexOf("uuid");
				if (index >= 0) {// 找到了
					// 取出mac地址并去除2边空格
					result = line.substring(index + "uuid".length() + 1).trim();
					break;
				}
			}
 
		} catch (IOException e) {
			logger.error("获取liunx cpu信息错误", e);
		}
		return result.trim();
	}
	/**
	 * 获取硬盘序列号(该方法获取的是 盘符的逻辑序列号,并不是硬盘本身的序列号)硬盘驱动器分区 如C,D
	 * 硬盘序列号还在研究中
	 * @param drive 盘符
	 * @return
	 */
	private static String getHardDiskSN_Windows(String drive) {
		String result = "";
		try {
			File file = File.createTempFile("realhowto", ".vbs");
			file.deleteOnExit();
			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"; // see note
			fw.write(vbs);
			fw.close();
			String path = file.getPath().replace("%20", " ");
			Process p = Runtime.getRuntime().exec(
					"cscript //NoLogo " + path);
			BufferedReader input = new BufferedReader(new InputStreamReader(
					p.getInputStream()));
			String line;
			while ((line = input.readLine()) != null) {
				result += line;
			}
			input.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result.trim();
	}
	private static String getBiosSN_Windows() {
		String result = "";
		try {
        	Runtime rt = Runtime.getRuntime();
            Process p = rt.exec("cmd.exe /c wmic bios get serialnumber");
            InputStream in = p.getInputStream();
            BufferedReader input = new BufferedReader(new InputStreamReader(
					p.getInputStream()));
			String line;
			while ((line = input.readLine()) != null) {
				result += line;
			}
			input.close();
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException();
		}
		return result.split("SerialNumber")[1].trim().toString();
	}
	/***************************linux下 通过执行shell读取 *********************************/
	/**
     * Java执行shell脚本入口
     * @param shellName 脚本文件名
     * @throws Exception
     */
    public static void service(String shellName) throws Exception{
        String shellDir = "";
        String shellPath = "";
        try {
            //获取脚本所在的目录
            String configFilePath = Thread.currentThread().getContextClassLoader().getResource("jdbc.properties").getPath();
            File f = new File(configFilePath);
            shellDir = f.getParent().split("java")[0];
            logger.info("shell dir = " + shellDir);

            //拼接完整的脚本目录
            shellPath = shellDir + "java/solution/Shell/" + shellName;
            logger.info("shell path = " + shellPath);

            //执行脚本
            callScript(shellPath);

        } catch (Exception e) {
        	logger.error("ShellExcutor异常" + e.getMessage(), e);
            throw e;
        }
    }

    /**
     * 脚本文件具体执行及脚本执行过程探测
     * @param script 脚本文件绝对路径
     * @throws Exception
     */
    private static void callScript(String script) throws Exception{
        try {
            String cmd = "sh " + script;
            try {
            	//解决脚本没有执行权限
                ProcessBuilder builder = new ProcessBuilder("/bin/chmod", "755",script);
                Process chmodprocess = builder.start();
                int w=chmodprocess.waitFor();
                if(w!=0)
                {
                	logger.error("------callScript 开启脚本权限不成功!");
                	BufferedReader erro_br = new BufferedReader(new InputStreamReader(chmodprocess.getErrorStream()));;
	    			 String erroResult = "";
	    			 String l="";
	    	         while((l = erro_br.readLine()) != null){
	    	        	 erroResult+=l+"\n";
	    	          }
	    	         if(erroResult.length()>0)
	    	             logger.error("-----callScript erro"+erroResult);
	    	         erro_br.close();
                }
                chmodprocess.destroy();
			} catch (Exception e) {
				// TODO: handle exception
			}
//            //启动独立线程等待process执行完成
//            CommandWaitForThread commandThread = new CommandWaitForThread(cmd);
//            commandThread.start();
//
//            while (!commandThread.isFinish()) {
//            	logger.info("shell " + script + " 还未执行完毕,10s后重新探测");
//                Thread.sleep(10000);
//            }
//
//            //检查脚本执行结果状态码
//            if(commandThread.getExitValue() != 0){
//                throw new Exception("shell " + script + "执行失败,exitValue = " + commandThread.getExitValue());
//            }
//            logger.info("shell " + script + "执行成功,exitValue = " + commandThread.getExitValue());
            logger.info("------callScript cmd job : " + cmd);
    		Scanner input = null;
    		Process process = null;
    		try {
    			//整个命令作为sh的参数进行执行,以便执行重定向和管道命令,否则管道命令会被当成参数执行,得到错误结果
    			//process = Runtime.getRuntime().exec(new String[] { "/bin/sh", "-c", cmd });
    			process = Runtime.getRuntime().exec(cmd);
    			try {
    				//等待命令执行完成
    				//process.waitFor(10, TimeUnit.SECONDS);
    				int waitfor = process.waitFor();
    				if(waitfor!=0)
    				{
    					logger.error("------callScript 执行命令不成功!");
    					BufferedReader erro_br = new BufferedReader(new InputStreamReader(process.getErrorStream()));;
    	    			 String erroResult = "";
    	    			 String l="";
    	    	         while((l = erro_br.readLine()) != null){
    	    	        	 erroResult+=l+"\n";
    	    	          }
    	    	         if(erroResult.length()>0)
    	    	             logger.error("-----callScript erro"+erroResult);
    	    	         erro_br.close();
    				}
    					
    			} catch (InterruptedException e) {
    				e.printStackTrace();
    			}
    			BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
    			String line;
    			while ((line = br.readLine()) != null) {
    				listResult.add(line);
    			}
    			
    			br.close();
    		} finally {
    			if (input != null) {
    				input.close();
    			}
    			if (process != null) {
    				process.destroy();
    			}
    		}
        }
        catch (Exception e){
            throw new Exception("执行脚本发生异常,脚本路径" + script, e);
        }
    }
    /**
     * 脚本函数执行线程
     */
    private static class CommandWaitForThread extends Thread {

        private String cmd;
        private boolean finish = false;
        private int exitValue = -1;

        public CommandWaitForThread(String cmd) {
            this.cmd = cmd;
        }

        public void run(){
            try {
                //执行脚本并等待脚本执行完成
                Process process = Runtime.getRuntime().exec(cmd);

                //写出脚本执行中的过程信息
                BufferedReader infoInput = new BufferedReader(new InputStreamReader(process.getInputStream()));
                BufferedReader errorInput = new BufferedReader(new InputStreamReader(process.getErrorStream()));
                String line = "";
                while ((line = infoInput.readLine()) != null) {
                	logger.info(line);
                }
                while ((line = errorInput.readLine()) != null) {
                	logger.error(line);
                }
                infoInput.close();
                errorInput.close();

                //阻塞执行线程直至脚本执行完成后返回
                this.exitValue = process.waitFor();
            } catch (Throwable e) {
            	logger.error("CommandWaitForThread accure exception,shell " + cmd, e);
                exitValue = 110;
            } finally {
                finish = true;
            }
        }

        public boolean isFinish() {
            return finish;
        }

        public void setFinish(boolean finish) {
            this.finish = finish;
        }

        public int getExitValue() {
            return exitValue;
        }
    }

   /**
   * 通过硬件名获取硬件信息
   */
    private static String getInfoByName(String name) {
    	String infoString="";
    	try {
    		if(listResult.size()==0)
    			service("HardWareInfo.sh");
    		for(String line:listResult)
    		{
    			if(line.contains(name))
    			{
    				String[] r= line.replace(name+":", "").trim().split(":");
    				if(r.length>1)
    				{
    					if(r.length==2)
    						return r[1];
    					else {
    						//针对这种情况  00:16:3e:0a:6d:70
    						String rString="";
							for (int i = 0; i <r.length; i++) {
								rString+=":"+r[i];
							}
							return rString.split(":",2)[1];
						}
    				}
    					
    				else 
    					return r[0];
    			}
    				
    		}
		} catch (Exception e) {
			// TODO: handle exception
			logger.error("------getInfoByName "+name+":"+e.getMessage(),e);
			throw new RuntimeException();
		}
    	return infoString;
	}
    /***************************linux下 通过命令读取 *********************************/
	 
	private static String executeLinuxCmd(String cmd) throws IOException  {
		logger.info("------executeLinuxCmd got cmd job : " + cmd);
		Scanner input = null;
		String result = "";
		Process process = null;
		try {
			//整个命令作为sh的参数进行执行,以便执行重定向和管道命令,否则管道命令会被当成参数执行,得到错误结果
			process = Runtime.getRuntime().exec(new String[] { "/bin/sh", "-c", cmd });
			try {
				//等待命令执行完成
				//process.waitFor(10, TimeUnit.SECONDS);
				int waitfor = process.waitFor();
				if(waitfor!=0)
					logger.error("------executeLinuxCmd 执行命令不成功!");
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
//			InputStream is = process.getInputStream();
//			input = new Scanner(is);
//			while (input.hasNextLine()) {
//				result += input.nextLine() + "\n";
//			}
			BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
			String line;
			while ((line = br.readLine()) != null) {
				result += line;
				break;
			}
			 br = new BufferedReader(new InputStreamReader(process.getErrorStream()));;
			 String erroResult = "";
	         while((line = br.readLine()) != null){
	        	 erroResult+=line+"\n";
	          }
	         if(erroResult.length()>0)
	             logger.error("-----executeLinuxCmd erro"+erroResult);
			br.close();
			//result = cmd + "\n" + result; //加上命令本身,打印出来
		} finally {
			if (input != null) {
				input.close();
			}
			if (process != null) {
				process.destroy();
			}
		}
		return result;

	}
	
	/**
	 * 
	 * @param cmd 命令语句
	 * @param record 要查看的字段
	 * @param symbol 分隔符
	 * @return
	 */
	private static String getSerialNumber(String cmd ,String record,String symbol) {
		try {
			
			String execResult = executeLinuxCmd(cmd);
			logger.info("------getSerialNumber execResult:"+execResult);
			String[] infos = execResult.split("\n");
			
			for(String info : infos) {
				info = info.trim();
				if(info.indexOf(record) != -1) {
					info.replace(" ", "");
					String[] sn = info.split(symbol);
					logger.info("------getSerialNumber return:"+sn[1]);
					return sn[1];
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
			//e.printStackTrace();
			logger.error(e);
			throw new RuntimeException();
		}
		return "";
	}
	/**
	 * linux 硬盘序列号  fdisk -l |grep 'Disk identifier'
	 * @return
	 */
	private static String getHardDiskSN_Linux() {

		return getSerialNumber("fdisk -l", "Disk identifier",":").replace(" ", "");
	}
	/**
	 * linux Bios版本号
	 * @return
	 */
	private static String getBiosVersion_Linux() {

		return getSerialNumber("dmidecode -s bios-version", "","").trim();
	}
	/**
	 * linux Bios版本内存序列号  云服务器可能获取不到:Serial Number: Not Specified
	 * @return
	 */
	private static String getMemroySN_Linux() {
		return getSerialNumber("dmidecode -t memory |grep 'Serial Number'", "","").split(":")[1].trim();
	}
	/**
	 * 获取CPU序列号 linux 云服务器
	 * 
	 * @return
	 */
	private static String getCPUID_linux2() {
		return getSerialNumber("dmidecode -t processor | grep 'ID'", "","").split(":")[1].trim();
	}
	// 主板序列号 linux
	private static String getMainBordId_linux2() {
		return getSerialNumber("dmidecode | grep 'Serial Number'", "","").split(":")[1].trim();
	}
	
	
	/***************************整合*********************************/
	/**
	 * 获取CPU序列号 
	 * 
	 * @return
	 */
	public static String getCPUID() { 
		logger.info("------当前系统版本-----:"+OSName);
		try {
			if (OSName!=null&&OSName.indexOf("linux")>-1) {
				
					//return getCPUID_linux2();
				return getInfoByName("cpuid");
				
			} else {
	           return getCPUID_Windows();
			}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				throw new RuntimeException();
			}

	}
	/**
	 * 获取主板序列号
	 * 
	 * @return
	 */
	public static String getMainBordId() {
		try {
			if (OSName!=null&&OSName.indexOf("linux")>-1) {
				
					//return getMainBordId_linux2();
				return getInfoByName("mainborid");
				
			} else {
	           return getMainBordId_windows();
			}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				logger.error("------getMainBordId------:"+e.getMessage());
				throw new RuntimeException();
			}

	}
	/**
	 * linux 硬盘序列号
	 * @return
	 */
	public static String getHardDiskSN() {
		try {
			if (OSName!=null&&OSName.indexOf("linux")>-1) {
				
					//return getHardDiskSN_Linux();
				return getInfoByName("harddisksn");
				
			} else {
	           return getHardDiskSN_Windows("C");
			}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				logger.error("------getHardDiskSN------:"+e.getMessage());
				throw new RuntimeException();
			}
		
	}
	/**
	 * 获取bios列号 
	 * @return
	 */
	public static String getBiosSN() {
		try {
			if (OSName!=null&&OSName.indexOf("linux")>-1) {
				
				//return getBiosVersion_Linux();
				return getInfoByName("biossn");
			
		    } else {
		    	
           return getBiosSN_Windows();
		}
		} catch (Exception e) {
			logger.error("------getBiosSN------:"+e.getMessage());
			throw new RuntimeException();
		}
	}
	
	//硬盘驱动????
	
	/**
	 * 获取widnows网卡的mac地址.
	 */
	public static String getMAC() {
		try {
			if (OSName!=null&&OSName.indexOf("linux")>-1) {
				
				//return getMAC_linuxs();
				return getInfoByName("mac");
			
		    } else {
		    	
	       return getMAC_windows();
		}
		} catch (Exception e) {
			logger.error("------getMAC------:"+e.getMessage());
			throw new RuntimeException();
		}
	}
	   
	
	
}

 

Published 14 original articles · won praise 15 · views 1628

Guess you like

Origin blog.csdn.net/u011323200/article/details/104313700