psutil
psutil copied to clipboard
Provide information about running in a Virtual Machine
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
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.
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.
systemd-detect-virt
implementation:
https://github.com/systemd/systemd/blob/f90eea7d18d9ebe88e6a66cd7a86b618def8945d/src/basic/virt.c#L641
Interesting windows resource: https://resources.infosecinstitute.com/topic/how-malware-detects-virtualized-environment-and-its-countermeasures-an-overview/
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
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