How can I programmatically know if I am in a VM?

2019-06-09 16:45发布

I want to be able to do so from both Windows and from Linux. I know that there are ways by getting sysinfo and using thumb rules related to hardware identifiers.

I want to know if there is a more fundamental method, like looking at a memory address / issuing an interrupt etc.

BTW I am trying to do this on Intel hardware and the virtualization software I use are Vmware Workstation and Windows HyperV.

3条回答
兄弟一词,经得起流年.
2楼-- · 2019-06-09 17:25

Here is one more useful command:

$ lscpu | grep -E 'Hypervisor vendor|Virtualization type'
Hypervisor vendor:     KVM
Virtualization type:   full

Example output of other commands:

$ sudo virt-what
kvm

$ dmesg | grep -i virtual
[    0.000000] Booting paravirtualized kernel on KVM
[    0.029160] CPU0: Intel QEMU Virtual CPU version 1.0 stepping 03

$ sudo dmidecode | egrep -i 'manufacturer|product|vendor|domU'
    Vendor: Bochs
    Manufacturer: Bochs
    Product Name: Bochs
    Manufacturer: Bochs
    Manufacturer: Bochs
    Manufacturer: Bochs
    Manufacturer: Bochs
    Manufacturer: Bochs
    Manufacturer: Bochs
    Manufacturer: Bochs
    Manufacturer: Bochs
    Manufacturer: Bochs
查看更多
老娘就宠你
3楼-- · 2019-06-09 17:25

Most software check the hypervisor CPUID leaf - Leaf 0x40000000, Hypervisor CPUID information

EAX: The maximum input value for hypervisor CPUID info (0x40000010).

EBX, ECX, EDX: Hypervisor vendor ID signature. E.g. "KVMKVMKVM"

Leaf 0x40000010, Timing information.

EAX: (Virtual) TSC frequency in kHz.

EBX: (Virtual) Bus (local apic timer) frequency in kHz.

ECX, EDX: RESERVED

Ofcourse, you are still relying on the hypervisor to give you this information. It may very well decide to not report 0x40000000 at all, in turn leading the guest to believe that it's actually running on real hardware

查看更多
做个烂人
4楼-- · 2019-06-09 17:47

At least one of these should work to detect if you are running under VMware (or some other common virtual environment) on Linux:

Check for virtual devices detected by kernel when system boots.

dmesg | grep -i virtual

Another way to detect virtualized hardware devices, if dmesg doesn't say anything useful.

dmidecode | egrep -i 'manufacturer|product|vendor|domU'

You can also check for virtual disks:

cat /proc/ide/hd*/model

Virtuozzo can usually be detected by looking for /proc/vz or /dev/vzfs.

查看更多
登录 后发表回答