如何用Python的pyvmomi库从vSphere API获取VM实时资源利用率?
获取vSphere虚拟机实时内存与带宽利用率(pyvmomi实现)
Hey there! I get it—right now you're only pulling allocated resource data from your VMs via pyvmomi, but what you really need is that live memory and bandwidth utilization data. Let's fix that using vSphere's PerformanceManager, which is the key to accessing real-time stats.
核心思路:使用PerformanceManager
vSphere API的PerformanceManager组件专门负责收集和查询虚拟机的性能指标。你需要:
- 获取
PerformanceManager实例 - 确定你要查询的性能指标ID(比如内存使用率、网络带宽)
- 构建查询规范,指定目标VM、指标和采样间隔
- 执行查询并解析返回的统计数据
关键性能指标ID参考
- 内存使用率:
mem.usage(百分比) - 内存已用:
mem.used(MB) - 网络带宽使用率:
net.usage(KBps) - CPU使用率:
cpu.usage(百分比)
完整代码示例
这里把你现有的代码和实时统计查询部分整合起来:
from pyVmomi import vim # 假设你已经建立了vSphere连接(变量c是你的ServiceInstance) print(c.CurrentTime()) searcher = c.content.searchIndex vm = searcher.FindByIp(ip='10.0.10.54', vmSearch=True) # --- 原有配置信息输出 --- print("VM name: ", vm.config.name) print("VM Guest OS:", vm.config.guestFullName) print("Location:", vm.config.files.snapshotDirectory) print("VM numCPU:", vm.config.hardware.numCPU) print("VM number of cores:", vm.config.hardware.numCoresPerSocket) print("Allocated RAM (MB):", vm.config.hardware.memoryMB) # --- 新增:获取实时性能数据 --- perf_manager = c.content.performanceManager # 定义要查询的指标(对应counterId可通过QueryPerfCounterByLevel查询) metrics_to_query = [ vim.PerformanceManager.MetricId(counterId=100, instance="*"), # mem.usage vim.PerformanceManager.MetricId(counterId=102, instance="*"), # mem.used vim.PerformanceManager.MetricId(counterId=4000, instance="*") # net.usage ] # 获取实时采样间隔(取最新的1分钟间隔,可根据需求调整) interval_id = perf_manager.QueryAvailableIntervals()[0] # 构建查询规范 perf_query_spec = vim.PerformanceManager.QuerySpec( entity=vm, metricId=metrics_to_query, intervalId=interval_id, maxSample=1 # 只取最新的1个采样点 ) # 执行查询 perf_results = perf_manager.QueryPerf(querySpec=[perf_query_spec]) # 解析并输出结果 if perf_results: print("\n--- Real-Time VM Stats ---") for metric in perf_results[0].value: # 匹配指标ID对应的名称 counter_info = perf_manager.QueryCounter(counterId=metric.id.counterId)[0] metric_name = f"{counter_info.groupInfo.key}.{counter_info.nameInfo.key}" # 根据指标单位格式化输出 if metric_name == "mem.usage": print(f"Memory Usage: {metric.value[0]}%") elif metric_name == "mem.used": print(f"Used Memory: {metric.value[0]} MB") elif metric_name == "net.usage": print(f"Network Bandwidth Usage: {metric.value[0]} KBps")
注意事项
- 如果不知道指标对应的
counterId,可以用perf_manager.QueryPerfCounterByLevel(level=4)列出所有可用指标(level=4是最详细的级别) - 采样间隔
intervalId可以通过perf_manager.QueryAvailableIntervals()查看所有可用间隔,默认有1分钟、5分钟等不同粒度 - 如果你需要批量查询所有运行中的VM,可以先通过
container_view获取所有VM对象,再遍历执行上述查询
内容的提问来源于stack exchange,提问作者SMAB95
相关产品推荐
相关产品推荐

