Libvirt 获取当前虚拟机 CPU 使用率
要获取当前虚拟机的 CPU 使用比例,可以使用 libvirt 提供的 API 来查询虚拟机的状态信息。以下是一个示例代码,可以获取虚拟机的 CPU 使用率:
import libvirt
def get_cpu_usage(domain_name):
conn = libvirt.open()
domain = conn.lookupByName(domain_name)
stats = domain.getCPUStats(True)
cpu_time_total = 0
cpu_time_used = 0
for cpu in stats:
cpu_time_total += cpu['cpu_time']
cpu_time_used += cpu['cpu_time'] - cpu['system_time'] - cpu['user_time']
cpu_usage = (cpu_time_used / cpu_time_total) * 100
return cpu_usage
# 调用函数并打印结果
domain_name = 'your_domain_name'
cpu_usage = get_cpu_usage(domain_name)
print('CPU usage: %.2f%%' % cpu_usage)
请注意,上述代码中的 your_domain_name 应替换为您要查询的虚拟机的名称。此外,您需要确保已安装 libvirt 库,并且已正确配置连接到 libvirt 守护进程。
原文地址: https://www.cveoy.top/t/topic/d6EG 著作权归作者所有。请勿转载和采集!