Objective: Determine if OS is running on a virtual machine.
Before we start, let’s look at some basic stuff. A hypervisor is a piece of computer software, firmware or hardware that creates and runs virtual machines. There are two main types of hypervisors:
- Type-1: native or bare-metal hypervisors
- Type-2: hosted hypervisors
Type-1 hypervisors run directly on the host’s hardware to control the hardware and to manage guest operating systems. KVM, Citrix XenServer, Microsoft Hyper-V and VMware ESX/ESXi are some exmaples of Type-1 hypervisors.
Type-2 hypervisors run on a conventional operating system just as other computer programs do. A guest operating system runs as a process on the host. These hypervisors abstract the guest operating systems from the host operating system. VMware Workstation, VMware Player, VirtualBox, Parallels Desktop for Mac and QEMU are examples of type-2 hypervisors.
The easiest way to check if the OS is running on a virtual machine is to check for the presence of the
hypervisor cpu flag in
/proc/cpuinfo. I used the code below on a machine running under KVM.
$ grep -q "^flags.*hypervisor" /proc/cpuinfo && echo "Machine running under VM" Machine running under VM
Below is the list of cpu flags in case you are interested.
$ grep "^flags" /proc/cpuinfo flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ss syscall nx pdpe1gb rdtscp lm constant_tsc arch_perfmon rep_good nopl eagerfpu pni pclmulqdq ssse3 cx16 pcid sse4_1 sse4_2 x2apic popcnt tsc_deadline_timer aes xsave avx f16c rdrand hypervisor lahf_lm fsgsbase tsc_adjust smep erms xsaveopt arat
hypervisor cpu flag was not set when I did the same test on a machine running on VirtualBox. I believe this flag is only useful when a Type-1 hypervisor is in use.
A better approach to determine if the machine is running on a virtual machine is to use the
virt-what script. Install the
virt-what script on your machine based on your Linux distribution.
# Install on Debian based Linux distributions $ sudo yum install virt-what
# Install on RedHat based distributions $ sudo yum install virt-what
At the time of writing,
virt-what detects the following virtualization environments:
- hyperv: Microsoft Hyper-V hypervisor
- lxc: Linux LXC container
- kvm: KVM hypervisor
- openvz: OpenVZ or Virtuozzo container
- parallels: Parallels Virtual Platform (Parallels Desktop, Parallels Server)
- powervm_lx86: IBM PowerVM Lx86 Linux/x86 emulator
- qemu: QEMU hypervisor
- uml: User-Mode Linux (UML)
- virtualbox: VirtualBox
- virtualpc: Microsoft VirtualPC
- vmware: VMware hypervisor
- xen: Xen hypervisor
- virt: Unable to detect virtualization technology
virt-what script on a machine running on VirtualBox gave the following output.
$ sudo virt-what virtualbox