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

 更新时间:2023年01月10日 08:38:16   作者:苍穹之跃  
这篇文章主要介绍了Java代码如何判断linux系统windows系统问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

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("获取结束!");
	}
 
}

总结

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

相关文章

  • Spring mvc AJAX技术实现原理解析

    Spring mvc AJAX技术实现原理解析

    这篇文章主要介绍了Spring mvc AJAX技术实现原理解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-03-03
  • spring-boot-starter-validation 校验参数的实现

    spring-boot-starter-validation 校验参数的实现

    参数校验在很多地方都可以用到,本文主要介绍了spring-boot-starter-validation 校验参数的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2022-04-04
  • Java轻松掌握面向对象的三大特性封装与继承和多态

    Java轻松掌握面向对象的三大特性封装与继承和多态

    本文主要讲述的是面向对象的三大特性:封装,继承,多态,内容含括从封装到继承再到多态的所有重点内容以及使用细节和注意事项,内容有点长,请大家耐心看完
    2022-05-05
  • Spring Data JPA使用JPQL与原生SQL进行查询的操作

    Spring Data JPA使用JPQL与原生SQL进行查询的操作

    这篇文章主要介绍了Spring Data JPA使用JPQL与原生SQL进行查询的操作,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-06-06
  • Java编程关于子类重写父类方法问题的理解

    Java编程关于子类重写父类方法问题的理解

    这篇文章主要介绍了Java编程关于子类重写父类方法问题的理解,分享了有关子类重写父类的实例,具有一定参考价值,需要的朋友可以了解下。
    2017-11-11
  • Java中的WeakHashMap简析

    Java中的WeakHashMap简析

    这篇文章主要介绍了Java中的WeakHashMap简析,Map 的子类常见的有 HashMap、Hashtable、ConcurrentHashMap、LinkedHashMap 等,WeakHashMap,直译就是,虚弱的 HashMap,从名字可得知其和 HashMap 有关,需要的朋友可以参考下
    2023-09-09
  • Java解决删除字符使频率相同问题

    Java解决删除字符使频率相同问题

    给你一个下标从0开始的字符串 word ,字符串只包含小写英文字母,你需要选择一个下标并删除下标处的字符,使得word中剩余每个字母出现频率相同,本文给大家介绍了Java解决删除字符使频率相同问题,需要的朋友可以参考下
    2024-02-02
  • SpringBoot发送各种复杂格式邮件的示例详解

    SpringBoot发送各种复杂格式邮件的示例详解

    本文主要介绍了如何使用JavaMailSender接口和MimeMessageHelper类,在SpringBoot实现发送带有附件,嵌入资源,抄送和密送的复杂邮件,需要的可以了解下
    2024-11-11
  • 图文详解Java的反射机制

    图文详解Java的反射机制

    反射就是Reflection,Java的反射是指程序在运行期可以拿到一个对象的所有信息。反射机制是框架的灵魂,一个java程序员不能不会使用反射,本文就来和大家一起详细聊聊Java的反射机制
    2022-08-08
  • springboot拦截器不拦截静态资源,只拦截controller的实现方法

    springboot拦截器不拦截静态资源,只拦截controller的实现方法

    这篇文章主要介绍了springboot拦截器不拦截静态资源,只拦截controller的实现方法,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2023-07-07

最新评论