psutil icon indicating copy to clipboard operation
psutil copied to clipboard

Provide information about running in a Virtual Machine

Open jelly opened this issue 7 years ago • 6 comments

I would like to see something as psutil.virtualized added to psutil if that falls in the use case of the library.

An ugly example implementation:

virtualized = False
for line in open('/proc/cpuinfo'):
    if line.startswith('flags') and 'hypervisor' in line:
        virtualized = True
        break

This however does not determine the virtualisation method such as vmware, kvm, lxc.

There are some alternatives available such as virt-what, dmidecode or systemd-detect-virt.

Some background info. http://unix.stackexchange.com/questions/89714/easy-way-to-determine-virtualization-technology

jelly avatar Jun 21 '17 14:06 jelly

I doubt there is a standardized way to do this on Linux, let alone on other platforms. Also, we're dealing with different independent technologies (virtualbox, xen, etc.), so each one is free to provide its own method to determine this, and that same method (such as relying on dmidecode) may even change with newer versions. In summary, I can't see a reliable way of implementing this.

giampaolo avatar Aug 04 '17 12:08 giampaolo

I can't recall why I opened this issue, but these days systemd-detect-virt can be used to detect virtualisation. systemd does all the logic for you.

jelly avatar Sep 27 '21 19:09 jelly

systemd-detect-virt implementation: https://github.com/systemd/systemd/blob/f90eea7d18d9ebe88e6a66cd7a86b618def8945d/src/basic/virt.c#L641

giampaolo avatar Sep 28 '21 10:09 giampaolo

Interesting windows resource: https://resources.infosecinstitute.com/topic/how-malware-detects-virtualized-environment-and-its-countermeasures-an-overview/

giampaolo avatar Dec 31 '21 13:12 giampaolo

Possible fallback / solution to detect vmware in a "cross-platform" fashion (utility needs to be installed though):

import subprocess, shutil

if shutil.which("vmware-checkvm"):
    code = subprocess.call(["vmware-checkvm"], stdout=subprocess.PIPE,
                           stderr=subprocess.PIPE)
    if code == 0:
        return "vmware"

Source code: https://github.com/vmware/open-vm-tools/blob/master/open-vm-tools/checkvm/checkvm.c

giampaolo avatar Dec 31 '21 14:12 giampaolo

Windows, ways to detect VMWare: https://stackoverflow.com/questions/41750144/c-how-to-detect-the-virtual-machine-your-application-is-running-in-has-focus https://kb.vmware.com/s/article/1009458

giampaolo avatar Jan 15 '22 15:01 giampaolo