Java代码如何判断linux系统windows系统

   2023-02-07 学习力0
核心提示:目录Java代码判断linux系统windows系统Java在Linux与windows系统下获取主板序列号,cpu序列号以及mac地址总结Java代码判断linux系统windows系统在使用硬件SDK的时候,往往有windows、linux两套。本地开发的时候使用windows,打包发布的时候使用linux,来回切

Java代码判断linux系统windows系统

在使用硬件SDK的时候,往往有windows、linux两套。

本地开发的时候使用windows,打包发布的时候使用linux,来回切换很麻烦。

可以使用下面的判断来加载不同版本的SDK。

package Commom;
 
public class osSelect {
 
    public static boolean isLinux() {
        return System.getProperty("os.name").toLowerCase().contains("linux");
    }
 
    public static boolean isWindows() {
        return System.getProperty("os.name").toLowerCase().contains("windows");
    }
 
}

Java在Linux与windows系统下获取主板序列号,cpu序列号以及mac地址

概述:

实现了获取当前操作系统名称,主板序列号,CPU序列号,mac地址的相关方法函数。

应对的场景是信创设备无法正常识别我们的加密狗,对于软件license的限制,我们通过系统当前日期以及绑定对方设备进行限制。

import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
 
public class DmcUtils {
 
 
	/**
	 * 获取当前操作系统名称
	 */
	public static String getOSName() {
		return System.getProperty("os.name").toLowerCase();
	}
 
	// 主板序列号 windows
	public 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) {
			System.out.print("获取主板信息错误");
			 
		}
		return result.trim();
	}
 
	// 主板序列号 linux
	public 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) {
			System.out.print("获取主板信息错误");
		}
		return result;
	}
 
	/**
	 * 获取mac地址 (如果Linux下有eth0这个网卡)
	 */
	public 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) {
			System.out.print("获取mac信息错误");
		 
		} finally {
			try {
				if (bufferedReader != null) {
					bufferedReader.close();
				}
			} catch (IOException e1) {
				System.out.print("获取mac信息错误");
			}
			bufferedReader = null;
			process = null;
		}
		return mac;
	}
 
        /*
         * 获取Linux的mac
         */
        public 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) {
			System.out.print("获取mac信息错误");
			 
		} finally {
			try {
				if (bufferedReader != null) {
					bufferedReader.close();
				}
			} catch (IOException e1) {
				System.out.print("获取mac信息错误");
				 
			}
			bufferedReader = null;
			process = null;
		}
		return mac;
	}
 
 
	/**
	 * 获取widnows网卡的mac地址.
	 */
	public 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) {
			System.out.print("获取mac信息错误");
			 
		}
		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
	 */
	public 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) {
			System.out.print("获取mac信息错误");
		}
		return result.trim();
	}
 
	/**
	 * 获取CPU序列号 linux
	 * 
	 * @return
	 */
	public 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) {
			System.out.print("获取mac信息错误");
		}
		return result.trim();
	}
	
	public static void main(String [] args) throws Exception {
		System.out.println("开始获取!");
		String cpuId=getCPUID_linux();
		System.out.println("linux cpuId:"+cpuId);
		//String cpuId=  getCPUID_Windows();
		//System.out.println("Windows cpuId:"+cpuId);
		String bordId= getMainBordId_linux();
		System.out.println("linux bordId:"+bordId);
		//String bordId=  getMainBordId_windows();
		//System.out.println("Windows bordId:"+bordId);
		System.out.println("获取结束!");
	}
 
}

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

原文地址:https://blog.csdn.net/wenxingchen/article/details/126259394
 
标签: Java 判断 linux windows
反对 0举报 0 评论 0
 

免责声明:本文仅代表作者个人观点,与乐学笔记(本网)无关。其原创性以及文中陈述文字和内容未经本站证实,对本文以及其中全部或者部分内容、文字的真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
    本网站有部分内容均转载自其它媒体,转载目的在于传递更多信息,并不代表本网赞同其观点和对其真实性负责,若因作品内容、知识产权、版权和其他问题,请及时提供相关证明等材料并与我们留言联系,本网站将在规定时间内给予删除等相关处理.

  • Hadoop中mapreduce运行WordCount程序报错Error:
    这个问题是因为map的方法参数与继承mapper定义的参数类型不一致导致的,应该将Mapper的key参数类型设置成Object,就可以解决这个问题 
    03-08
  • Debian安装JAVA环境 debian安装jdk11
     http://blog.csdn.net/gongora/archive/2009/05/15/4190469.aspxDebian官方没有维护专门的Java软件包,所以不能直接用apt-get工具来安装。在Debian系统中要安装Java,有两种方式,一种是用传统方式;一种是Debian方式。1. 传统方式在 sun 下载了最新的 JDK
    02-10
  • org.apache.jasper.JasperExce:无法在web.xml或
    参考 https://blog.csdn.net/Dawn510/article/details/112636990 我是第三种情况 ! 完美解决!! 还有前提就是缺少jar包 我在maven中导入了以下jar包dependencygroupIdjavax.servlet/groupIdartifactIdjstl/artifactIdversion1.2/version/dependencydepe
    02-10
  • Exceptionin thread "main" java.lang.Unsatisf
    在eclipse上运行hadoop报错:Exceptionin thread "main" java.lang.UnsatisfiedLinkError:org.apache.hadoop.util.NativeCrc32.nativeComputeChunkedSumsByteArray(II[BI[BIILjav,这个问题折腾了我很久,后来找到方法解决。描述一下:电脑是win8.1的64位操作系
    02-10
  • java.lang.ClassNotFoundException: org.apache
      运行servler报错java.lang.NoClassDefFoundError: org/apache/commons/fileupload/FileItemFactory或java.lang.ClassNotFoundException: org.apache.commons.fileupload.FileItemFactory程序编译通过但是报这个错,网上搜了一下,大部分说是包未正确导入
    02-10
  • java 调用apache.commons.codec的包简单实现MD5
    转自:https://blog.csdn.net/mmd1234520/article/details/70210002/ 1 import java.security.MessageDigest; 2 import java.security.NoSuchAlgorithmException; 34 import org.apache.commons.codec.digest.DigestUtils;//开发的jar包 使用更方便 5 public
    02-10
  • java.lang.UnsatisfiedLinkError: org.apache.hadoop.util.NativeCrc32.nativeComputeChunkedSumsByteArray
    java.lang.UnsatisfiedLinkError: org.apache.h
    环境: Spark2.1.0 、Hadoop-2.7.5   代码运行系统:Win 7在运行Spark程序写出文件(savaAsTextFile)的时候,我遇到了这个错误:18/06/12 20:13:34 ERROR Utils: Aborting taskjava.lang.UnsatisfiedLinkError: org.apache.hadoop.util.NativeCrc32.nativeCom
    02-10
  • java.lang.Exception: org.apache.http.conn.Ht
    java.lang.Exception: org.apache.http.conn.HttpHostConnectException: Connect to 172.24.1.227:80 [/172.24.1.227] failed: 拒绝连接 (Connection refused)at com.trs.util.HttpUtil.doPost(HttpUtil.java:197)at com.trs.util.HttpUtil.doPost(HttpUtil.j
    02-10
  • 排查Hive报错:org.apache.hadoop.hive.serde2.
    CREATE TABLE json_nested_test (count string,usage string,pkg mapstring,string,languages arraystring,store mapstring,arraymapstring,string)ROW FORMAT SERDE 'org.apache.hive.hcatalog.data.JsonSerDe'STORED AS TEXTFILE;以上述sql创建表json_neste
    02-10
  • tomcat启动提示java.lang.UnsatisfiedLinkError
    https://blog.csdn.net/a274360781/article/details/52411984
    02-10
点击排行