Pyvmomi - List of all virtual machines

I have a lot of VMs (shipping with 2 hosts) and I would like to list them all.

To do this, I use this:

atexit.register(connect.Disconnect, self.si)
content = self.si.RetrieveContent()
children = content.rootFolder.childEntity

    for child in content.rootFolder.childEntity:

        if hasattr(child, 'vmFolder'):
            datacenter = child
            vmFolder = datacenter.vmFolder
            vmList = vmFolder.childEntity

        for vm in vmList:
            self._getInfosVms(vm)

      

For my main method using this method:

 def _getInfosVms(self, vm, depth = 1, i = 0):
        maxdepth = 10

        if hasattr(vm, 'childEntity'):
            if depth > maxdepth:
                return
            vmList = vm.childEntity
            for c in vmList:
                self._getInfosVms(c, depth+1)
            return

        print(vm.summary)

      

This code lists all the basic information about vms, but for some vm I have an error. I cannot display vm.summry, but I can print vm.

Mistake:

File "/python_project/packages/pyVmomi/VmomiSupport.py", line 560, in the call

 return self.f(*args, **kwargs)

      

File "/python_project/packages/pyVmomi/VmomiSupport.py", line 383, in _InvokeAccessor

 return self._stub.InvokeAccessor(self, info)

      

File "/python_project/packages/pyVmomi/StubAdapterAccessorImpl.py", line 42, in InvokeAccessor

 options=self._pcType.RetrieveOptions(maxObjects=1))

      

File "/python_project/packages/pyVmomi/VmomiSupport.py", line 566, at

 self.f(*(self.args + (obj,) + args), **kwargs)

      

File "/python_project/packages/pyVmomi/VmomiSupport.py", line 375, in _InvokeMethod

 return self._stub.InvokeMethod(self, info, args)

      

File "/python_project/packages/pyVmomi/SoapAdapter.py", line 1291, in InvokeMethod

     raise exc

pyVmomi.SoapAdapter.ParserError: 'xml document:
\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x03\xedZ[o\xe3\xba\x11~\xdf_A\xf8\xa9\x05"\xcb\xb2|I\x0c\xae\x0e\x12\xc7\xd9\x04\x8d\xb3\x86\x9d\r\x82S\x14\x05-\xd11\x1b\x89\xd4!);>\xbf\xbeCJ\xf2J\xbe\x9d\x05Z\xbf\xe5\xc9\xe2\xcc7\x17\x0e\x87\xd4\x0ce\xfc\xdbG\x12\xa3\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\x02\xa7Fp\xac\xc0\xce\xb5\xf5\x92\xdf\x05\x7f\x8f\xb3\xab\x92\xb9\x0f5\xe1\xab^Mx\x1f\x01k\x0f\xfb,\xdc\xd1\xda\xed\xf4M\xd4\x0fp\n\xfc\xbe"\xcf\xeb\xb5J\x99\x03fR\xc9\xe0\x9dLs\x0e\x94$\x9e\xc9\xdb*\t\xe7\xf9Q\x8cz](qk\x14\xac\xd6\x90\xf1\xdb\xa1\xb1U#\xe0\xb99\xc7\x05\xaf"vI\xf6\xde*
KhT^\xe6\x95\xeet\xf3{\xab\x03,\xbc\xd0\x8f\xe2\xed\x06rd\xcd"\xbd\x0c\x1cp|\x87\x04\x90\x19\x05\xf1\x88\xc8\xcd#L\x88\x87\x9b\x02\xb6G6\xda\xf2\xc7mR\x90\x8dUX\xa3\x9a}\x98\x9a\x12\xad:\x99=\x1a\xceR{\xa1l\x8d@\x85\xe2\x99\xadc\xbeF\xd4\xe9X\xa9h\xb6\x17\xbb]\x1av\x0f\xec\xadz\xe6\xd6\x89\xb6\xc8\xcfO\x9f\xfc\xdf$\xee\xf6\x7f(n\xe5\xcf)\xee\xa9?\xb6\x04_\xb0\xbb\xf3?\x18w\xf7O@\xc1\x7f\x01\xf4\x96\x1dv>$\x00\x00
parse error at: line:1, col:0'

      

Thanks for ur help.

+3


source to share


2 answers


It looks like you have picked up some sample code that I suspect for multiple host configurations is a little naive and confusing. Anyway, this hasattr (XX, 'vmFolder) approach is a little different from IMHO, and I prefer to be explicit about the types. I noticed that even though you can rep () objects and they print what they are, I haven't found a way to do something like:

if type(object) == type(vim.Folder):

      

Because I couldn't get to the corresponding classes in the RHS of this comparison as some lazy type evaluation is happening.

You can use the _wsdlName attribute and it seems to work, then you can work with it, for example, have all your machines do something like this:

def Walk(root):
  if root._wsdlName == "Folder":
    for child in root.childEntity:
      Walk(child)
  elif root._wsdlName == "Datacenter":
    for child in root.vmFolder.childEntity:
      Walk(child)
  elif root._wsdlName == "VirtualMachine":
    print root.name
  elif root._wsdlName == "VirtualApp":
    pass
  else:
    raise VSError("Unable to recognise node type '%s'" % root._wsdlName)

      



And then:

Walk(content.rootFolder)

      

However, you will most likely complete the enumeration faster with something like:

container = content.viewManager.CreateContainerView(content.rootFolder, vimtype, True)
for c in container.view:
  print c.name

      

If you are looking for just one type, I found that the second way lists them about half the time. YMMV.

+2


source


I wanted to do some sort of hierarchical tree view of virtual machines in a specific folder, so this is what I wrote (I also had to disable ssl certificate validation).

#!/usr/bin/env python

import atexit
import ssl
import tools.cli as cli
from pyVim import connect
from pyVmomi import vmodl
from pyVmomi import vim


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

    args = cli.get_args()

    try:
        context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
        context.verify_mode = ssl.CERT_NONE
        service_instance = connect.SmartConnect(host=args.host,
                                                user=args.user,
                                                pwd=args.password,
                                                port=int(args.port),
                                                sslContext=context)

        atexit.register(connect.Disconnect, service_instance)


        for datacenter in service_instance.content.rootFolder.childEntity:
            print("datacenter: ", datacenter.name)

            if (datacenter.name == "Cambridge"):
                print ("Found Cambridge datacenter")

                folders1 = datacenter.vmFolder.childEntity
                for folder1 in folders1:
                    print("{}/".format(folder1.name))
                    if folder1.name != "Engineering":
                        print("    -Ignored")
                    if folder1.name == "Engineering":

                        folders2 = folder1.childEntity
                        for folder2 in folders2:
                            print("    {}/{}/".format(folder1.name, folder2.name))

                            folders3 = folder2.childEntity
                            for folder3 in folders3:
                                print("        {}/{}/{}".format(folder1.name, folder2.name, folder3.name))

        connect.Disconnect

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

    return 0

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

# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4

      



apologies for the hacky nature of the script, it's not generic, just something I needed to rush, but I hope this is helpful.

0


source







All Articles