简体   繁体   中英

How do I detect Xen in a Python script?

I need to determine when my Python script is running in a Xen virtual machine. The VM will be running Linux.

I can't find anything obvious in the platform module. The closest I can get is the appearance of 'xen' in platform.platform()

>>> platform.platform()
'Linux-2.6.18-194.el5xen-x86_64-with-redhat-5.5-Final'

What is the best way to determine this?

Thanks.

FYI, if its a paravirtual VM, there should be a /proc/xen/capabilities file. If its contents is "control_d" then, you are running under dom0 else , you are running on a domU.
DONT rely on the kernel version. If the VM is compiled with a custom kernel or a different kernel version or even a modern day PV-ops kernel (which has no "xen" string in it, unlike REDHAT's kernel), then your code wont work.

On the other hand, there are other nifty tricks. cpuid instruction is one such example. I dont know how to do it in python, but if you set eax to 1 and call cpuid, bit 31 of ECX would have the answer. If its set, you are running on a hypervisor. Else, you are not. But this works only for 64bit platforms.

virt-what: http://people.redhat.com/~rjones/virt-what/

virt-what is a shell script which can be used to detect if the program is running in a virtual machine.

virt-what supports a very large number of different hypervisor types, including common open source hypervisors (KVM, Xen, QEMU, VirtualBox), mainframe systems like IBM Systemz, LPAR, z/VM, hardware partitioning schemes like Hitachi Virtage, proprietary hypervisors like VMWare, Microsoft Hyper-V and much more.

您可以调用用C编写的xen-detect命令。

Can you depend on platform.platform() ? I don't know. If you can and it works everytime:

>>> output = 'Linux-2.6.18-194.el5xen-x86_64-with-redhat-5.5-Final'
>>> if 'xen' in output:
      print 'Xen found'

Xen found

There is more than one method of doing this. Which one you want to follow depends on you. Have a look at this question here on SO, which answers this question only. Now your task is implementing this in Python, which might involve calling some external process and checking the output. Is it possible? Yes.

Some systems don't make difference in "normal" kernel and kernel for Xen DomU, such as Fedora. It's not always reliable to use kernel's name to detect whether the system is running on top of Xen.

One possible method is to check the kernel booting message and grep xen:

dmesg | grep xen

For paravirtualized VM, use this:

ps auwx | egrep -c '\[xenbus\]$'

If return value is 1, it is a xen paravirtualized guest. Otherwise, it is not.

import re, platform

def is_xen():
    return bool(re.search('xen', platform.platform()))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM