Python 读取esxi上所有主机的设备信息

(主要是为了统计所有虚拟机的设备名称和所属主机)

代码:

from pyVim import connect
from pyVmomi import vim
import ssl


def get_vm_devices(vm):
    devices = []
    try:
        if vm.config is not None and hasattr(vm.config, 'hardware') and hasattr(vm.config.hardware, 'device'):
            for device in vm.config.hardware.device:
                if hasattr(device, 'deviceInfo') and hasattr(device.deviceInfo, 'label'):
                    devices.append(device.deviceInfo.label)
                else:
                    devices.append("Unknown Device")
        else:
            print(f"虚拟机 {vm.name} 的配置信息不完整或者设备信息不可用。")
    except Exception as e:
        print(f"获取虚拟机 {vm.name} 的设备信息时出现异常: {str(e)}")
    return devices


# def get_vm_host(vm):
#     try:
#         if vm.runtime.host:
#             return vm.runtime.host.name
#         else:
#             return "Unknown Host"
#     except Exception as e:
#         print(f"获取虚拟机 {vm.name} 的所属主机时出现异常: {str(e)}")
#         return "Unknown Host"


def main():
    # 定义 ESXi 主机的连接参数
    vcenter_ip = ''
    username = ''
    password = ''

    service_instance = None
    total_vm_count = 0

    try:
        # 连接 vCenter Server
        context = ssl.create_default_context()
        context.check_hostname = False
        context.verify_mode = ssl.CERT_NONE
        service_instance = connect.SmartConnect(host=vcenter_ip, user=username, pwd=password, sslContext=context)

        # 获取 ESXi 主机列表
        content = service_instance.RetrieveContent()
        container = content.rootFolder
        viewType = [vim.HostSystem]
        recursive = True

        hosts = content.viewManager.CreateContainerView(container, viewType, recursive)
        for host in hosts.view:
            print("Found ESXi host:", host.name)

            # 获取该主机上的虚拟机列表
            vm_container = host.vm
            for vm in vm_container:
                print("  Virtual Machine:", vm.name)
                total_vm_count += 1
                # vm_host = get_vm_host(vm)
                # print("    Host:", vm_host)

                # 获取虚拟机的设备名称
                devices = get_vm_devices(vm)
                print("    Devices:", devices)
            print()

        print(f"总数是:{total_vm_count}")

    except vim.fault.InvalidLogin as e:
        print("登录失败:", e.msg)
    except vim.fault.NotFound as e:
        print("未找到对象:", e.msg)
    except vim.fault.HostCommunication as e:
        print("主机通信错误:", e.msg)
    except ssl.SSLError as e:
        print("SSL 错误:", e)
    except Exception as e:
        print("发生错误:", e)

    finally:
        if service_instance:
            connect.Disconnect(service_instance)


if __name__ == "__main__":
    main()

效果:

代码解释:

gpt是真好用,以下是gpt的解释

包介绍:

  • pyVim 和 pyVmomi 是 VMware 提供的 Python SDK,用于与 vSphere API 进行交互。
  • ssl 用于处理 SSL 连接的配置,这在连接到 vCenter Server 时是必要的。

get_vm_devices(vm)函数:

  • get_vm_devices(vm) 函数用于获取虚拟机 vm 的设备信息列表。
  • 首先检查虚拟机配置的完整性和设备信息的可用性,然后遍历虚拟机的硬件设备列表,并尝试获取每个设备的标签信息 (deviceInfo.label)。
  • 如果设备信息不完整或者出现异常,会打印相应的错误信息,并返回一个包含 "Unknown Device" 的列表。

main()函数:

  • main() 函数是整个程序的入口。
  • 首先定义了连接 vCenter Server 的参数(IP、用户名、密码)。
  • 使用 ssl.create_default_context() 创建一个 SSL 连接的默认上下文,并禁用证书验证,以便连接到 vCenter Server。
  • connect.SmartConnect() 方法建立到 vCenter Server 的连接,并获取一个 service_instance 对象。
  • 使用 service_instance.RetrieveContent() 获取 vCenter Server 内容。
  • 创建一个包含 vim.HostSystem 视图类型的容器视图 hosts,并逐个遍历每个 ESXi 主机。
  • 对于每个主机,获取其上运行的虚拟机列表 (host.vm),并遍历每个虚拟机。
  • 打印每个虚拟机的名称,并调用 get_vm_devices(vm) 函数获取并打印其设备信息。
  • 最后统计并打印总的虚拟机数量 (total_vm_count)。

异常处理:

  • 在 try 块中,对可能发生的异常进行了捕获和处理,包括登录失败、对象未找到、主机通信错误、SSL 错误以及其他异常情况。
  • 在 finally 块中,确保最终关闭 service_instance 的连接,释放资源。

优化

我只需要获取到设备名称和所属主机,硬件信息对于管控来说没什么大用,所以针对此需求进行优化,将所需要的信息保存到json文件中

import json
from pyVim import connect
from pyVmomi import vim
import ssl


def get_vm_devices(vm):
    devices = []
    try:
        if vm.config is not None and hasattr(vm.config, 'hardware') and hasattr(vm.config.hardware, 'device'):
            for device in vm.config.hardware.device:
                if hasattr(device, 'deviceInfo') and hasattr(device.deviceInfo, 'label'):
                    devices.append(device.deviceInfo.label)
                else:
                    devices.append("Unknown Device")
        else:
            print(f"虚拟机 {vm.name} 的配置信息不完整或者设备信息不可用。")
    except Exception as e:
        print(f"获取虚拟机 {vm.name} 的设备信息时出现异常: {str(e)}")
    return devices


def main():
    vcenter_ip = '此处省略IP'
    username = '此处省略用户'
    password = '此处省略密码'

    service_instance = None
    total_vm_count = 0
    vm_info_list = []

    try:
        # 建立到 vCenter Server 的连接
        context = ssl.create_default_context()
        context.check_hostname = False
        context.verify_mode = ssl.CERT_NONE
        service_instance = connect.SmartConnect(host=vcenter_ip, user=username, pwd=password, sslContext=context)

        # 获取 vCenter Server 内容
        content = service_instance.RetrieveContent()
        container = content.rootFolder
        viewType = [vim.HostSystem]
        recursive = True

        # 创建主机视图并遍历每个主机
        hosts = content.viewManager.CreateContainerView(container, viewType, recursive)
        for host in hosts.view:
            host_name = host.name

            # 获取该主机上的虚拟机列表
            vm_container = host.vm
            for vm in vm_container:
                vm_name = vm.name
                vm_info = {
                    "虚拟机名称": vm_name,
                    "所属主机": host_name
                }
                vm_info_list.append(vm_info)
                total_vm_count += 1

                # 获取虚拟机的设备信息
                devices = get_vm_devices(vm)
                print(f"    Devices for {vm_name}: {devices}")
            print(f"所属主机下的虚拟机是: {total_vm_count}")
            print()

        print(f"总数是: {total_vm_count}")

        # 将信息写入 JSON 文件
        with open('vm_info.json', 'w') as json_file:
            json.dump(vm_info_list, json_file, indent=4, ensure_ascii=False)
            print(f"已写入到json文件,数量是 {len(vm_info_list)}")

    except vim.fault.InvalidLogin as e:
        print("登录失败:", e.msg)
    except vim.fault.NotFound as e:
        print("未找到对象:", e.msg)
    except vim.fault.HostCommunication as e:
        print("主机通信错误:", e.msg)
    except ssl.SSLError as e:
        print("SSL 错误:", e)
    except Exception as e:
        print("发生错误:", e)

    finally:
        if service_instance:
            connect.Disconnect(service_instance)

if __name__ == "__main__":
    main()

优化后得到的json文件部分截图显示如下:

总结

一定要多用gpt,AI智能就是未来大趋势

半吊子都可以适当开发

  • 8
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值