Linux: Check If Running on Virtual Machine

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.

Below is the list of cpu flags in case you are interested.

The 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.

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

Running the virt-what script on a machine running on VirtualBox gave the following output.

ibrahim = { interested_in(unix, linux, android, open_source, reverse_engineering); coding(c, shell, php, python, java, javascript, nodejs, react); plays_on(xbox, ps4); linux_desktop_user(true); }