You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用pyvmomi获取主机WWNN?尝试vim.host.HostBusAdapter无效

获取ESXi主机WWNN的pyvmomi解决方案

我之前也碰到过这个问题——直接调用vim.host.HostBusAdapter确实没法拿到WWNN,因为WWNN是光纤通道(FC)/FCoE适配器专属的属性,普通的适配器(比如以太网)根本没有这个字段。正确的做法是先筛选出主机上的FC类适配器,再提取对应的WWNN值。

具体步骤&代码示例

下面是完整的可运行代码,包含从连接到提取WWNN的全流程:

from pyVim.connect import SmartConnect, Disconnect
import ssl

# 注意:生产环境建议使用合法SSL证书,这里仅为测试禁用验证
ssl_context = ssl._create_unverified_context()

# 1. 连接到vCenter或ESXi主机
vcenter_host = "your-vcenter-or-esxi-ip"
username = "admin@vsphere.local"
password = "your-password"

try:
    service_instance = SmartConnect(
        host=vcenter_host,
        user=username,
        pwd=password,
        sslContext=ssl_context
    )
    if not service_instance:
        print("连接失败,请检查凭证或主机地址")
        exit()

    # 2. 获取目标主机对象(这里通过主机名匹配,你也可以根据需求调整查找逻辑)
    content = service_instance.RetrieveContent()
    target_host_name = "your-esxi-host-name"
    target_host = None

    # 创建容器视图遍历所有主机
    host_container = content.viewManager.CreateContainerView(
        content.rootFolder,
        [vim.HostSystem],
        recursive=True
    )
    for host in host_container.view:
        if host.name == target_host_name:
            target_host = host
            break
    host_container.Destroy()

    if not target_host:
        print(f"未找到主机:{target_host_name}")
        Disconnect(service_instance)
        exit()

    # 3. 遍历主机存储适配器,筛选FC类型并提取WWNN
    print(f"\n主机 {target_host_name} 的WWNN信息:")
    storage_adapters = target_host.config.storageDevice.hostBusAdapter
    for adapter in storage_adapters:
        # 只处理光纤通道适配器
        if adapter.adapterType == "FibreChannel":
            # 原始WWNN是整数,需要格式化为标准的冒号分隔十六进制格式
            raw_wwnn = adapter.nodeWorldWideName
            formatted_wwnn = ':'.join([f'{(raw_wwnn >> (i*8)) & 0xFF:02X}' for i in range(7, -1, -1)])
            print(f"FC适配器[{adapter.device}]:{formatted_wwnn}")

finally:
    # 确保断开连接
    if service_instance:
        Disconnect(service_instance)

关键说明

  • 为什么之前失败?:vim.host.HostBusAdapter是所有主机总线适配器的基类,只有当适配器类型为FibreChannel时,才会包含nodeWorldWideName属性(也就是WWNN)。直接遍历所有适配器的话,非FC适配器没有这个字段,自然拿不到值。
  • 格式转换:pyvmomi返回的nodeWorldWideName是整数类型,需要手动转换为大家熟悉的XX:XX:XX:XX:XX:XX:XX:XX格式。
  • 多适配器场景:如果主机有多个FC端口,代码会输出所有对应的WWNN。

内容的提问来源于stack exchange,提问作者Ekansh Kanodia

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:43:49