使用Python和libvirt获取运行中的域信息

6 投票
3 回答
7962 浏览
提问于 2025-04-16 10:07

我正在尝试写一个简单的脚本,用来获取在xen主机上运行的域的一些信息。

到目前为止,我有:

import libvirt
import pprint
conn = libvirt.open('xen:///')

for id in conn.listDomainsID():
    dom = conn.lookupByID(id)
    infos = libvirt.virDomainGetInfo(dom)

但是这段代码给我带来了以下错误:

AttributeError: 'module' object has no attribute 'virDomainGetInfo'

根据API的说明(http://www.libvirt.org/html/libvirt-libvirt.html#virDomainGetInfo),这应该至少能返回一些信息。

有没有什么线索?(我还是个Python新手)

3 个回答

0

在编程中,有时候我们需要让程序做一些特定的事情,比如处理数据、显示信息或者与用户互动。为了实现这些功能,我们通常会用到一些代码块,这些代码块就像是程序的“指令”,告诉计算机该做什么。

在这个例子中,

import libvirt
import xml.etree.ElementTree as ET
conn = libvirt.open(name)
domain = conn.lookupByName(domain_name)
domain_config = ET.fromstring(domain.XMLDesc())
domain_disks = domain_config.findall('//disk')
就是一个代码块的占位符。它代表了一段具体的代码,这段代码可能包含了实现某个功能的具体步骤。通过这些代码,程序能够按照我们的要求去执行任务。

总之,代码块是编程中非常重要的部分,它们帮助我们把想法变成实际的操作,让计算机能够理解并执行我们的指令。

4

想要获取关于libvirt在Python中使用的文档,可以使用内置的帮助功能。

首先,启动你的Python解释器(只需在命令行中输入python)。

>>> import libvirt
>>> help(libvirt)

这样你就能看到关于libvirt的详细文档了。

6

来自文档的内容:http://www.libvirt.org/python.html

There is a couple of function who don't map directly to their C counterparts due to specificities in their argument conversions:

    * virConnectListDomains is replaced by virDomain::listDomainsID(self) which returns a list of the integer ID for the currently running domains
    * virDomainGetInfo is replaced by virDomain::info() which returns a list of
         1. state: one of the state values (virDomainState)
         2. maxMemory: the maximum memory used by the domain
         3. memory: the current amount of memory used by the domain
         4. nbVirtCPU: the number of virtual CPU
         5. cpuTime: the time used by the domain in nanoseconds

撰写回答