python 获取vmware vsphere信息

使用vmware官方的pyvimomi包可以获取vmware 服务的信息。

安装

pip install pyVmomi pyVim

获取所有主机信息

import atexit

from pyVim import connect
from pyVmomi import vmodl
from pyVmomi import vim


def print_vm_info(virtual_machine):
    """
    Print information for a particular virtual machine or recurse into a
    folder with depth protection
    """
    summary = virtual_machine.summary
    print("Name       : ", summary.config.name)
    print("Template   : ", summary.config.template)
    print("Path       : ", summary.config.vmPathName)
    print("Guest      : ", summary.config.guestFullName)
    print("Instance UUID : ", summary.config.instanceUuid)
    print("Bios UUID     : ", summary.config.uuid)
    annotation = summary.config.annotation
    if annotation:
        print("Annotation : ", annotation)
    print("State      : ", summary.runtime.powerState)
    if summary.guest is not None:
        ip_address = summary.guest.ipAddress
        tools_version = summary.guest.toolsStatus
        if tools_version is not None:
            print("VMware-tools: ", tools_version)
        else:
            print("Vmware-tools: None")
        if ip_address:
            print("IP         : ", ip_address)
        else:
            print("IP         : None")
    if summary.runtime.question is not None:
        print("Question  : ", summary.runtime.question.text)
    print("")


def main():
    """
    Simple command-line program for listing the virtual machines on a system.
    """

    host = "192.168.1.252"
    user = "root"
    pwd = "xxx"
    port = 443

    try:
        service_instance = connect.SmartConnectNoSSL(host=host,
                                                     user=user,
                                                     pwd=pwd,
                                                     port=port)

        atexit.register(connect.Disconnect, service_instance)

        content = service_instance.RetrieveContent()

        container = content.rootFolder  # starting point to look into
        viewType = [vim.VirtualMachine]  # object types to look for
        recursive = True  # whether we should look into it recursively
        containerView = content.viewManager.CreateContainerView(
            container, viewType, recursive)

        children = containerView.view
        for child in children:
            print_vm_info(child)

    except vmodl.MethodFault as error:
        print("Caught vmodl fault : " + error.msg)
        return -1

    return 0


# Start program
if __name__ == "__main__":
    main()

获取根目录信息

from pyVim.connect import SmartConnect, Disconnect
from pyVmomi import vim
import atexit


def getVmwareContent(host, username, password):
    if hasattr(ssl, '_create_unverified_context'):
        context = ssl._create_unverified_context()
    si = SmartConnect(host=host, user=username, pwd=password, sslContext=context)
    if not si:
        return None
    atexit.register(Disconnect, si)
    return si.RetrieveContent()

数据中心

def getVmwareDatacenterList(host, username, password):
    content = getVmwareContent(host, username, password)
    if content is None:
        return None
    return content.viewManager.CreateContainerView(content.rootFolder, [vim.Datacenter], True).view

集群

def getVmwareClusterList(host, username, password):
    content = getVmwareContent(host, username, password)
    if content is None:
        return None
    return content.viewManager.CreateContainerView(content.rootFolder, [vim.ClusterComputeResource], True).view

物理主机

def getVmwareHostList(host, username, password):
    content = getVmwareContent(host, username, password)
    if content is None:
        return None
    return content.viewManager.CreateContainerView(content.rootFolder, [vim.HostSystem], True).view

存储

def getVmwareDatastoreList(host, username, password):
    content = getVmwareContent(host, username, password)
    if content is None:
        return None
    return content.viewManager.CreateContainerView(content.rootFolder, [vim.Datastore], True).view

网络

def getVmwareNetworkList(host, username, password):
    content = getVmwareContent(host, username, password)
    if content is None:
        return None
    return content.viewManager.CreateContainerView(content.rootFolder, [vim.Network], True).view

虚拟机

def getVmwareVirtualMachinekList(host, username, password):
    content = getVmwareContent(host, username, password)
    if content is None:
        return None
    return content.viewManager.CreateContainerView(content.rootFolder, [vim.VirtualMachine], True).view

虚拟机开关机

host = "192.168.1.252"
user = "root"
pwd = "xxx"
port = 443
ip = "192.168.3.111"

SI = None
try:
    SI = connect.SmartConnectNoSSL(host=host,
                                   user=user,
                                   pwd=pwd,
                                   port=port)

    atexit.register(connect.Disconnect, SI)
except IOError as ex:
    pass

if not SI:
    raise SystemExit("Unable to connect to host with supplied info.")
VM = None
if ARGS.uuid:
    VM = SI.content.searchIndex.FindByUuid(None, uuid,
                                           True,
                                           True)
elif ARGS.name:
    VM = SI.content.searchIndex.FindByDnsName(None, name,
                                              True)
elif ARGS.ip:
    VM = SI.content.searchIndex.FindByIp(None, ip, True)

if VM is None:
    raise SystemExit("Unable to locate VirtualMachine.")

print("Found: {0}".format(VM.name))
print("The current powerState is: {0}".format(VM.runtime.powerState))
TASK = VM.ResetVM_Task()
# TASK = VM.PowerOnVM_Task()
# TASK = VM.PowerOffVM_Task()
tasks.wait_for_tasks(SI, [TASK])
print("its done.")

其他更多实例

pyVmiom实例

Last updated

Was this helpful?