Search code examples
pythonvmwarepyvmomi

How to get the name and IP of the host of a VMware virtual machine?


My program is running inside a VMware virtual machine, my purpose is to get some information about the machine which this vm is hosted on.

I've already done some googling and find a library called pyVmomi.

But I still can't figure out how to get the information I want.

The samples are almost all about getting all vms or all hosts, and there is not obvious way I can adapt them for getting information about the current machine.


Solution

  • Assuming your VM (that is running this pyVmomi script) is running some version of Linux you could use something like dmidecode to find the UUID.

    import subprocess
    
    from pyVim import connect
    
    proc = subprocess.Popen(["sudo dmidecode|grep UUID|awk '{print $2}'"], stdout=subprocess.PIPE, shell=True)
    (out, err) = proc.communicate()
    uuid = out[:-1]
    
    SI = None
    SI = connect.SmartConnect(host=ARGS.host,
                              user=ARGS.user,
                              pwd=ARGS.password,
                              port=ARGS.port)
    
    VM = SI.content.searchIndex.FindByUuid(None, uuid,
                                           True,
                                           False)
    
    HOST = VM.runtime.host
    
    print "Host name: {}".format(HOST.name)
    

    What this will do is execute a system command on the Linux box to find the UUID. VMWare uses the BIOS UUID as the default UUID so dmidecode should work here. Next it will connect to a given vSphere host (in this example I assume a vCenter, but an ESXi host should provide the same results here). Next it will search the inventory looking for a VM with a matching UUID. From there it calls the runtime.host method which will return the HostSystem for the VM. Please note due to clustering that host could change.