如何检测我的应用程序是否在虚拟机中运行?

Jas*_*son 35 .net virtualization winapi

如果我的应用程序在虚拟机中运行,如何检测(.NET或Win32)?

Rob*_*los 39

这是我使用的:

using (var searcher = new System.Management.ManagementObjectSearcher("Select * from Win32_ComputerSystem"))
{
  using (var items = searcher.Get())
  {
    foreach (var item in items)
    {
      string manufacturer = item["Manufacturer"].ToString().ToLower();
      if ((manufacturer == "microsoft corporation" && item["Model"].ToString().ToUpperInvariant().Contains("VIRTUAL"))
          || manufacturer.Contains("vmware")
          || item["Model"].ToString() == "VirtualBox")
      {
        return true;
      }
    }
  }
}
return false;
Run Code Online (Sandbox Code Playgroud)

编辑2014-12-02:更新了代码,以便它不再将Microsoft Surface Pro检测为VM.感谢Erik Funkenbusch指出这一点.

编辑2017-06-29:更新了代码,以便它还检查HypervisorPresent属性的值.

编辑2018-02-05:删除了对HypervisorPresent属性的检查,因为它不正确.如果在hyper-V服务器上的主机O/S上运行,则此属性可能返回true.

  • 一些快速测试看起来像测试表达式可以简化(对于'简化'的某些定义)到`item ["Model"].ToString().ToLower().包含("虚拟")`. (2认同)
  • 我认为这段代码会将微软的计算机硬件检测为VM,例如Surface Pro. (2认同)

Jay*_*uzi 19

根据Virtual PC Guy的博客文章" 检测Microsoft虚拟机 ",您可以使用WMI检查主板的制造商.在PowerShell中:

 (gwmi Win32_BaseBoard).Manufacturer -eq "Microsoft Corporation"
Run Code Online (Sandbox Code Playgroud)

  • 呃,非MS VM怎么样? (18认同)
  • 另外,正如评论者@ErikFunkenbusch对我对此问题的回答所提到的,此检查会错误地将MS Surface Pro识别为VM. (4认同)
  • 公平地说,对于 MS 虚拟机,Surface 系列产品是在发布此答案之后发布的。 (2认同)

Art*_*yan 12

以下是一种实现方法的示例.它只适用于微软的Virtual PC和VMWare,但它是一个开始:http: //www.codeproject.com/KB/system/VmDetect.aspx


小智 5

此 C 函数将检测 VM 来宾操作系统:(在 Windows 上测试,使用 Visual Studio 编译)

#include <intrin.h>

    bool isGuestOSVM()
    {
        unsigned int cpuInfo[4];
        __cpuid((int*)cpuInfo,1);
        return ((cpuInfo[2] >> 31) & 1) == 1;
    }
Run Code Online (Sandbox Code Playgroud)

  • 为了澄清,这段代码使用“cpuid”指令来检测是否设置了指示代码正在虚拟机管理程序上运行的功能位。当然,并不要求实际的虚拟机管理程序总是设置该位,特别是对于软件虚拟机管理程序。 (3认同)
  • 我不会用这个。在我的电脑上测试误报(Windows 10、VS)。我在 BIOS 中打开了虚拟化支持,但没有在 VM 中运行,所以可能是这样(?)。 (2认同)