How to identify that you're running under a VM?

后端 未结 12 1997
南旧
南旧 2020-11-29 23:42

Is there a way to identify, from within a VM, that your code is running inside a VM?

I guess there are more or less easy ways to identify specific VM systems, especi

12条回答
  •  悲&欢浪女
    2020-11-30 00:37

    Here is a (java + windows) solution to identify whether underlying machine is physical or virtual.

    Virtual Machines Examples:

    Manufacturer

    • Xen
    • Microsoft Corporation
    • innotek GmbH
    • Red Hat
    • VMware, Inc.

    Model

    • HVM domU
    • Virtual Machine
    • VirtualBox
    • KVM
    • VMware Virtual Platform

      import java.io.BufferedReader;
      import java.io.InputStreamReader;
      import java.util.ArrayList;
      import java.util.List;
      
      public abstract class OSUtil {
      
      public static final List readCmdOutput(String command) {
          List result = new ArrayList<>();
      
          try {
              Process p=Runtime.getRuntime().exec("cmd /c " + command);
              p.waitFor();
              BufferedReader reader=new BufferedReader(
                      new InputStreamReader(p.getInputStream())
                      );
              String line;
              while((line = reader.readLine()) != null) {
                  if(line != null && !line.trim().isEmpty()) {
                      result.add(line);
                  }
              }
          } catch (Exception e) {
              e.printStackTrace();
          }
      
          return result;
      }
      
      public static final String readCmdOutput(String command, int lineNumber) {
          List result = readCmdOutput(command);
          if(result.size() < lineNumber) {
              return null;
          }
      
          return result.get(lineNumber - 1);
      }
      
      public static final String getBiosSerial() {
          return readCmdOutput("WMIC BIOS GET SERIALNUMBER", 2);
      }
      
      public static final String getHardwareModel() {
          return readCmdOutput("WMIC COMPUTERSYSTEM GET MODEL", 2);
      }
      
      public static final String getHardwareManufacturer() {
          return readCmdOutput("WMIC COMPUTERSYSTEM GET MANUFACTURER", 2);
      }
      
      public static void main(String[] args) {
          System.out.println("BIOS Serial: " + getBiosSerial());
          System.out.println("Hardware Model: " + getHardwareModel());
          System.out.println("Hardware Manufacturer: " + getHardwareManufacturer());
      }
      }
      

    You can use the output to decide whether it is a VM or a physical machine:

    Physical machine output:

    BIOS Serial: 2HC3J12
    Hardware Model: Inspiron 7570
    Hardware Manufacturer: Dell Inc.

    Virtual machine output:

    BIOS Serial: 0
    Hardware Model: Innotec GmBH
    Hardware Manufacturer: Virtual Box

提交回复
热议问题