def main():

    args = cli.get_args()

    try:
        service_instance = connect.SmartConnect(host=args.host,
                                                user=args.user,
                                                pwd=args.password,
                                                port=int(args.port))

        if not service_instance:
            print("Could not connect to the specified host using specified "
                  "username and password")
            return -1

        atexit.register(connect.Disconnect, service_instance)

        content = service_instance.RetrieveContent()
        object_view = content.viewManager.CreateContainerView(content.rootFolder,
                                                              [vim.HostSystem], True)
        for obj in object_view.view:
            host.print_host_info(obj)

        object_view.Destroy()
        return

    except vmodl.MethodFault, e:
        print "Caught vmodl fault : " + e.msg
        return -1
def main():
    """
    Simple command-line program for listing the virtual machines on a system.
    """

    args = cli.get_args()

    try:
        service_instance = connect.SmartConnect(host=args.host,
                                                user=args.user,
                                                pwd=args.password,
                                                port=int(args.port))

        atexit.register(connect.Disconnect, service_instance)

        content = service_instance.RetrieveContent()
        children = content.rootFolder.childEntity
        for child in children:
            if hasattr(child, 'vmFolder'):
                datacenter = child
            else:
                # some other non-datacenter type object
                continue

            vm_folder = datacenter.vmFolder
            vm_list = vm_folder.childEntity
            for virtual_machine in vm_list:
                print_vm_info(virtual_machine, 10)

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

    return 0
Exemple #3
0
def main():

    args = cli.get_args()

    try:
        si = SmartConnectNoSSL(host=args.host,
                               user=args.user,
                               pwd=args.password,
                               port=int(args.port))
        atexit.register(Disconnect, si)

    except IOError as e:
        pass

    if not si:
        raise SystemExit("Unable to connect to host with supplied info.")

    content = si.RetrieveContent()
    containerView = content.viewManager.CreateContainerView(content.rootFolder, [vim.Datacenter], True)
    children = containerView.view

    for datacenter in children:
        if hasattr(datacenter, 'vmFolder'):
            vmFolder = datacenter.vmFolder
            vmList = vmFolder.childEntity
            for vm in vmList:
                PrintVmInfo(vm)
    return 0
def main():
    """
    Simple command-line program for listing the virtual machines on a system.
    """

    args = cli.get_args()

    try:
        service_instance = connect.SmartConnect(host=args.host,
                                                user=args.user,
                                                pwd=args.password,
                                                port=int(args.port))

        if not service_instance:
            print("Could not connect to the specified host using specified "
                  "username and password")
            return -1

        atexit.register(connect.Disconnect, service_instance)

        # ## Do the actual parsing of data ## #
        parse_service_instance(service_instance)

    except vmodl.MethodFault, e:
        print "Caught vmodl fault : " + e.msg
        return -1
def main():
    """
    Simple command-line program for listing the virtual machines on a system.
    """

    args = cli.get_args()

    try:
        context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
        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)

        if not service_instance:
            print("Could not connect to the specified host using specified "
                  "username and password")
            return -1

        atexit.register(connect.Disconnect, service_instance)

        # ## Do the actual parsing of data ## #
        parse_service_instance(service_instance)

    except vmodl.MethodFault as e:
        print("Caught vmodl fault : {}".format(e.msg))
        return -1

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

    args = cli.get_args()

    try:
        service_instance = connect.SmartConnect(host=args.host,
                                                user=args.user,
                                                pwd=args.password,
                                                port=int(args.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
Exemple #7
0
def main():
    """
    Simple command-line program for listing the virtual machines on a system.
    """

    args = cli.get_args()

    try:
        service_instance = connect.SmartConnect(host=args.host,
                                                user=args.user,
                                                pwd=args.password,
                                                port=int(args.port))

        if not service_instance:
            print(
                "Could not connect to the specified host using specified "
                "username and password")
            return -1

        atexit.register(connect.Disconnect, service_instance)

        # ## Do the actual parsing of data ## #
        parse_service_instance(service_instance)

        with open(csvFile, 'w') as f:
            w = csv.DictWriter(f, lod_vms[1].keys())
            w.writeheader()
            for obj in lod_vms:
                w.writerow(obj)

    except vmodl.MethodFault, e:
        print "Caught vmodl fault : " + e.msg
        return -1
def main():
    """
    Simple command-line program for listing the virtual machines on a system.
    """

    args = cli.get_args()

    try:
        service_instance = connect.SmartConnect(host=args.host, user=args.user, pwd=args.password, port=int(args.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
Exemple #9
0
def main():
    """
    Simple command-line program for listing the virtual machines on a system.
    """

    args = cli.get_args()

    try:
        context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
        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)

        if not service_instance:
            print("Could not connect to the specified host using specified "
                  "username and password")
            return -1

        atexit.register(connect.Disconnect, service_instance)

        # ## Do the actual parsing of data ## #
        parse_service_instance(service_instance)

    except vmodl.MethodFault as e:
        print("Caught vmodl fault : {}".format(e.msg))
        return -1

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

    args = cli.get_args()

    try:
        service_instance = connect.SmartConnect(host=args.host,
                                                user=args.user,
                                                pwd=args.password,
                                                port=int(args.port))

        if not service_instance:
            print("Could not connect to the specified host using specified "
                  "username and password")
            return -1

        atexit.register(connect.Disconnect, service_instance)

        # ## Do the actual parsing of data ## #
        parse_service_instance(service_instance)

        with open(csvFile,'w') as f:
                w = csv.DictWriter(f,lod_vms[1].keys())
                w.writeheader()
                for obj in lod_vms:
                        w.writerow(obj)

    except vmodl.MethodFault, e:
        print "Caught vmodl fault : " + e.msg
        return -1
Exemple #11
0
def main():
    """
    Simple command-line program for listing the virtual machines on a system.
    """

    args = cli.get_args()

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

        if not service_instance:
            print("Could not connect to the specified host using specified "
                  "username and password")
            return -1

        atexit.register(connect.Disconnect, service_instance)

        # ## Do the actual parsing of data ## #
        parse_service_instance(service_instance)

    except vmodl.MethodFault, e:
        print "Caught vmodl fault : " + e.msg
        return -1
def main():

    args = cli.get_args()

    try:
        si = SmartConnectNoSSL(host=args.host,
                               user=args.user,
                               pwd=args.password,
                               port=int(args.port))
        atexit.register(Disconnect, si)

    except IOError as e:
        pass

    if not si:
        raise SystemExit("Unable to connect to host with supplied info.")

    content = si.RetrieveContent()
    perfManager = content.perfManager

    counterInfo = {}
    for c in perfManager.perfCounter:
        prefix = c.groupInfo.key
        fullName = c.groupInfo.key + "." + c.nameInfo.key + "." + c.rollupType
        counterInfo[fullName] = c.key

    dict_to_str = json.dumps(counterInfo)
    dict_to_str = dict_to_str.replace(',', '\n')

    sys.stdout = open('counterInfo.txt', 'w')
    print(dict_to_str)
def main():
    """
    Simple command-line program for listing the virtual machines on a system.
    """

    args = cli.get_args()

    try:
        service_instance = connect.SmartConnect(host=args.host,
                                                user=args.user,
                                                pwd=args.password,
                                                port=int(args.port))

        atexit.register(connect.Disconnect, service_instance)

        content = service_instance.RetrieveContent()
        children = content.rootFolder.childEntity
        for child in children:
            if hasattr(child, 'vmFolder'):
                datacenter = child
            else:
                # some other non-datacenter type object
                continue

            vm_folder = datacenter.vmFolder
            vm_list = vm_folder.childEntity
            for virtual_machine in vm_list:
                print_vm_info(virtual_machine, 10)

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

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

    args = cli.get_args()

    audit = {}
    try:
        service_instance, content = connect_vc(args.host, args.user,
                                               args.password, args.port)

        if sys.stdout.isatty():
            print("vCenter: %s" % args.host)

        content = service_instance.RetrieveContent()

        container = content.rootFolder  # starting point to look into
        datacenters = get_datacenters(content)
        for dc in datacenters:
            datacenters[dc]['clusters'] = get_clusters(datacenters[dc]['dc'])

            datacenters[dc]['vms'] = get_vms(datacenters[dc]['dc'].vmFolder)

            get_nets(dc)
            get_dstores(dc)

        vmcount = 0

        for dc in datacenters:
            for vm in sorted(datacenters[dc]['vms'], key=lambda s: s.lower()):
                vmcount += 1
                v = datacenters[dc]['vms'][vm]
                c = find_cluster(datacenters[dc]['clusters'],
                                 v.runtime.host.name)
                vort = "Template" if v.summary.config.template == True else "VM"
                audit[v.name] = {}
                audit[v.name]['datacenter'] = dc
                audit[v.name]['cluster'] = c
                audit[v.name]['type'] = vort
                audit[v.name]['hostname'] = v.summary.guest.hostName
                audit[v.name]['guestid'] = v.config.guestId
                audit[v.name]['fullname'] = v.summary.config.guestFullName
                audit[v.name]['state'] = v.runtime.powerState
                audit[v.name]['ip'] = v.guest.ipAddress
                if sys.stdout.isatty():
                    print(vmcount, "Guests processed", end='\r')
                    sys.stdout.flush()
#                print("%-15s:%-10s %-8s %-30s %-30s %s %s %s %s" % (dc, c, vort,v.name,v.summary.guest.hostName, v.config.guestId, v.summary.config.guestFullName,v.guest.guestState,v.guest.ipAddress  ))
#print vort, v.name, v.summary.guest.hostName, v.guest.guestId, v.summary.config.guestFullName,v.guest.guestState,v.guest.ipAddress #,v.summary
#        print("\ncount:",vmcount)

        print(json.dumps(audit, indent=4, separators=(',', ': ')))

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

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

    args = cli.get_args()

    try:
        '''
        Fork from 'pyvmomi-community-samples/samples'
        Disabling SSL certificate verification
        in case of error:
        "[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:590)"
        '''
        import ssl
        context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
        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)

        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:
            list_vm = list_vm_info(child)
            list_vms.append(list_vm)

        list_vms_sort = sorted(list_vms, key=lambda result: result[0])
        #        print(list_vms_sort)

        fl = open(csv_file, 'w')

        writer = csv.writer(fl)
        writer.writerow([
            'name', 'ip_address', 'hostName', 'template', 'path', 'mem',
            'cpu_number', 'guest_id', 'guest_name', 'instance_UUID',
            'bios_UUID', 'annotation', 'state', 'tools_version'
        ])
        for values in list_vms_sort:
            writer.writerow(values)
        fl.close()

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

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

    args = cli.get_args()

    try:
        '''
        Fork from 'pyvmomi-community-samples/samples'
        Disabling SSL certificate verification
        in case of error:
        "[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:590)"
        '''
        import ssl
        context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
        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)

        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:
            list_vm = list_vm_info(child)
            list_vms.append(list_vm)

        list_vms_sort = sorted(list_vms, key=lambda result: result[0])
#        print(list_vms_sort)

        fl = open(csv_file, 'w')

        writer = csv.writer(fl)
        writer.writerow(['name', 'ip_address', 'hostName', 'template', 'path', 'mem', 'cpu_number',
                         'guest_id', 'guest_name', 'instance_UUID', 'bios_UUID',
                         'annotation', 'state', 'tools_version'])
        for values in list_vms_sort:
            writer.writerow(values)
        fl.close()

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

    return 0
Exemple #17
0
def main():

    args = cli.get_args()

    # Connect to the host without SSL signing
    try:
        si = SmartConnectNoSSL(host=args.host,
                               user=args.user,
                               pwd=args.password,
                               port=int(args.port))
        atexit.register(Disconnect, si)

    except IOError as e:
        pass

    if not si:
        raise SystemExit("Unable to connect to host with supplied info.")

    content = si.RetrieveContent()
    perfManager = content.perfManager

    # create a list of vim.VirtualMachine objects so
    # that we can query them for statistics
    container = content.rootFolder
    viewType = [vim.HostSystem]
    recursive = True

    containerView = content.viewManager.CreateContainerView(
        container, viewType, recursive)
    children = containerView.view
    #print(children)

    # Loop through all the VMs
    for host in children:
        print("")
        print("----------", host.summary.config.name, "------------")
        print("Host Name : ", host.summary.config.name)
        print("Host Product : ", host.summary.config.product.fullName)
        print("Cpu Model : ", host.summary.hardware.cpuModel)
        #        print("Cpu Cores : ", host.summary.hardware.numCpuCores)
        #        print("Cpu Packages : ", host.summary.hardware.numCpuPkgs)
        print("Cpu Threads : ", host.summary.hardware.numCpuThreads)
        print(
            "CPU Clock :",
            round(((host.hardware.cpuInfo.hz / 1e+9) *
                   host.hardware.cpuInfo.numCpuCores), 0), "GHz")
        print("Memory : ", convertMemory(host.hardware.memorySize))
        print("System Model : ", host.summary.hardware.model)
        print("uuid (BIOS identification) : ", host.summary.hardware.uuid)
        print("vendor : ", host.summary.hardware.vendor)
Exemple #18
0
def main():
    """
    Simple command-line program for listing the virtual machines on a system.
    """

    args = cli.get_args()

    try:
        service_instance = connect.SmartConnect(host=args.host,
                                                user=args.user,
                                                pwd=args.password,
                                                port=int(args.port))

        atexit.register(connect.Disconnect, service_instance)

        content = service_instance.RetrieveContent()
        children = content.rootFolder.childEntity
        """
        Create a csv file and write the header row. lines will be written by print_vm_info.
        If a param is passed to the script it will be used as hte filename of the csv.
        """
        global vmlist
        vmlist = []

        for child in children:
            if hasattr(child, 'vmFolder'):
                datacenter = child
            else:
                # some other non-datacenter type object
                continue

            vm_folder = datacenter.vmFolder
            vm_list = vm_folder.childEntity
            for virtual_machine in vm_list:
                print_vm_info(virtual_machine, 10)

        with open('/tmp/usage_by_folder.csv', 'w') as csvfile:
            fieldnames = ['project', 'vmname', 'disk', 'cpu', 'mem']
            writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
            writer.writeheader()
            writer.writerows(vmlist)

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

    return 0
Exemple #19
0
def main():
    '''
    Main method. For available command line arguments see cli.py
    '''
    log_format = '[%(levelname)s] (#%(lineno)s) %(filename)s->%(funcName)s>>> "%(message)s"'
    args = cli.get_args()
    if args.debug:
        logging.basicConfig(format=log_format, level=logging.DEBUG)
    else:
        logging.basicConfig(format=log_format)
    tree = parser.parse(args.url)
    if tree:
        sm = schemamapper.SchemaMapper(tree)
        schemamodel = sm.map()
        cm = classmapper.ClassMapper(schemamodel)
        classmodel = cm.map()
        renderer.render(classmodel, args.dest, args.lang, args.overwrite)
Exemple #20
0
def main():
    '''
    Main method. For available command line arguments see cli.py
    '''
    log_format = '[%(levelname)s] (#%(lineno)s) %(filename)s->%(funcName)s>>> "%(message)s"'
    args = cli.get_args()
    if args.debug:
        logging.basicConfig(format=log_format, level=logging.DEBUG)
    else:
        logging.basicConfig(format=log_format)
    tree = parser.parse(args.url)
    if tree:
        sm = schemamapper.SchemaMapper(tree)
        schemamodel = sm.map()
        cm = classmapper.ClassMapper(schemamodel)
        classmodel = cm.map()
        renderer.render(classmodel, args.dest, args.lang, args.overwrite)
Exemple #21
0
def main():
    """
    Simple command-line program for listing the virtual machines on a system.
    """
    validate_certs = False
    args = cli.get_args()

    try:
        service_instance = connect.SmartConnect(host=args.host,
                                                user=args.user,
                                                pwd=args.password,
                                                port=int(args.port))
    except (requests.ConnectionError, ssl.SSLError) as connection_error:
        print("catch exception and going next")
        if '[SSL: CERTIFICATE_VERIFY_FAILED]' in str(
                connection_error) and not validate_certs:
            context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
            context.verify_mode = ssl.CERT_NONE
            service_instance = connect.SmartConnect(host=args.host,
                                                    user=args.user,
                                                    pwd=args.password,
                                                    sslContext=context)

        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 child, type(child), dir(child)
            for cnet in child.network:
                print cnet.name, cnet.summary
            print_vm_info(child)

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

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

    args = cli.get_args()

    try:
        '''
        Fork from 'pyvmomi-community-samples/samples'
        Disabling SSL certificate verification
        in case of error:
        "[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:590)"
        '''
        import ssl
        context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
        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)

        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
def auth():
    """
    Authentication to the server
    """

    args = cli.get_args()

    try:
        si = connect.SmartConnect(host=args.host, user=args.user, pwd=args.password, port=int(args.port))

        if not si:
            print ("Could not connect to the specified host using specified " "username and password")
            return None

        atexit.register(connect.Disconnect, si)

    except vmodl.MethodFault, e:
        print "Caught vmodl fault : " + e.msg
        return None
Exemple #24
0
def main():

    args = cli.get_args()

    # Connect to the host without SSL signing
    try:
        si = SmartConnectNoSSL(
            host=args.host,
            user=args.user,
            pwd=args.password,
            port=int(args.port))
        atexit.register(Disconnect, si)

    except IOError as e:
        pass

    if not si:
        raise SystemExit("Unable to connect to host with supplied info.")

    content = si.RetrieveContent()
    perfManager = content.perfManager

    # create a list of vim.VirtualMachine objects so
    # that we can query them for statistics
    container = content.rootFolder
    viewType = [vim.Datastore]
    recursive = True

    containerView = content.viewManager.CreateContainerView(container,
                                                            viewType,
                                                            recursive)
    children = containerView.view

    # Loop through all the VMs
    for datastore in children:
        print("")
        print("---------- DATASTORE : ",datastore.info.name, "------------")
        print("Name : ", datastore.info.name)
        print("Type : ", datastore.summary.type)
        print("Url  : ", datastore.info.url)
        print("Total Space : ", convertSize(datastore.summary.capacity))
        print("Free Space  : ", convertSize(datastore.summary.freeSpace))
def main():
    """
    Simple command-line program for listing the virtual machines on a system.
    """

    args = cli.get_args()

    try:
        service_instance,content = connect_vc(args.host,args.user,args.password,args.port)

        content = service_instance.RetrieveContent()
        
        

        container = content.rootFolder  # starting point to look into
        datacenters = get_datacenters(content)
        for dc in datacenters:
            datacenters[dc]['vms'] = get_vms(datacenters[dc]['dc'].vmFolder)
             
            get_nets(dc)
            get_dstores(dc)

        vmcount=0
        print("vCenter: %s" % args.host)
        for dc in datacenters:
            for vm in sorted(datacenters[dc]['vms'],key=lambda s: s.lower()):
                vmcount+=1
                v = datacenters[dc]['vms'][vm]
                vort = "Template" if v.summary.config.template == True else "VM      "
                print("%-15s:%-10s %-8s %-30s %-30s %s %s %s %s" % (dc, v.runtime.host.name, vort,v.name,v.summary.guest.hostName, v.config.guestId, v.summary.config.guestFullName,v.guest.guestState,v.guest.ipAddress  ))
                #print vort, v.name, v.summary.guest.hostName, v.guest.guestId, v.summary.config.guestFullName,v.guest.guestState,v.guest.ipAddress #,v.summary
        print "count:",vmcount
                
    
    except vmodl.MethodFault as error:
        print("Caught vmodl fault : " + error.msg)
        return -1

    return 0
def auth():
    """
    Authentication to the server
    """

    args = cli.get_args()

    try:
        si = connect.SmartConnect(host=args.host,
                                  user=args.user,
                                  pwd=args.password,
                                  port=int(args.port))

        if not si:
            print(
                "Could not connect to the specified host using specified "
                "username and password")
            return None

        atexit.register(connect.Disconnect, si)

    except vmodl.MethodFault, e:
        print "Caught vmodl fault : " + e.msg
        return None
def main():
    args = cli.get_args()
    vmip = '10.130.1.200'
    try:
        si = connect.SmartConnect(host=args.host,
                                  user=args.user,
                                  pwd=args.password,
                                  port=int(args.port))

    except:
        print "Failed to connect"
    atexit.register(Disconnect, si)
    content = si.RetrieveContent()
    perf = perfdata()
    counters = perf.perfcounters()

    container = content.rootFolder
    viewType = [vim.VirtualMachine]
    recursive = True

    containerView = content.viewManager.CreateContainerView(
        container, viewType, recursive)
    children = containerView.view
    for child in children:
        search_index = content.searchIndex
        vm = child
        print(vm)
        for counter in counters:
            p = Thread(target=perf.run, args=(
                content,
                vm,
                counter,
            ))
            if vm.summary.runtime.powerState == 'poweredOn':
                p.start()
                time.sleep(.100)
Exemple #28
0
def main():

    args = cli.get_args()

    # Connect to the host without SSL signing
    try:
        si = SmartConnectNoSSL(
            host=args.host,
            user=args.user,
            pwd=args.password,
            port=int(args.port))
        atexit.register(Disconnect, si)

    except IOError as e:
        pass

    if not si:
        raise SystemExit("Unable to connect to host with supplied info.")

    content = si.RetrieveContent()
    perfManager = content.perfManager

    # create a mapping from performance stats to their counterIDs
    # counterInfo: [performance stat => counterId]
    # performance stat example: cpu.usagemhz.LATEST
    # counterId example: 6
    counterInfo = {}
    for c in perfManager.perfCounter:
        fullName = c.groupInfo.key + "." + c.nameInfo.key + "." + c.rollupType
        counterInfo[fullName] = c.key

    # create a list of vim.VirtualMachine objects so
    # that we can query them for statistics
    container = content.rootFolder
    viewType = [vim.VirtualMachine]
    recursive = True

    containerView = content.viewManager.CreateContainerView(container,
                                                            viewType,
                                                            recursive)
    children = containerView.view

    # Loop through all the VMs
    for child in children:
        # Get all available metric IDs for this VM
        counterIDs = [m.counterId for m in
                      perfManager.QueryAvailablePerfMetric(entity=child)]

        # Using the IDs form a list of MetricId
        # objects for building the Query Spec
        metricIDs = [vim.PerformanceManager.MetricId(counterId=c,
                                                     instance="*")
                     for c in counterIDs]

        # Build the specification to be used
        # for querying the performance manager
        spec = vim.PerformanceManager.QuerySpec(maxSample=1,
                                                entity=child,
                                                metricId=metricIDs)
        # Query the performance manager
        # based on the metrics created above
        result = perfManager.QueryStats(querySpec=[spec])

        # Loop through the results and print the output
        output = ""
        for r in result:
            output += "name:        " + child.summary.config.name + "\n"
            for val in result[0].value:
                # python3
                if sys.version_info[0] > 2:
                    counterinfo_k_to_v = list(counterInfo.keys())[
                        list(counterInfo.values()).index(val.id.counterId)]
                # python2
                else:
                    counterinfo_k_to_v = counterInfo.keys()[
                        counterInfo.values().index(val.id.counterId)]
                if val.id.instance == '':
                    output += "%s: %s\n" % (
                        counterinfo_k_to_v, str(val.value[0]))
                else:
                    output += "%s (%s): %s\n" % (
                        counterinfo_k_to_v, val.id.instance, str(val.value[0]))

        print(output)
    :return:
    """
    end = clock()
    total = end - START
    print("Completion time: {0} seconds.".format(total))

# List of properties.
# See: http://goo.gl/fjTEpW
# for all properties.
vm_properties = ["name", "config.uuid", "config.hardware.numCPU",
                 "config.hardware.memoryMB", "guest.guestState",
                 "config.guestFullName", "config.guestId",
                 "config.version"]

args = cli.get_args()
service_instance = None
try:
    service_instance = connect.SmartConnect(host=args.host,
                                            user=args.user,
                                            pwd=args.password,
                                            port=int(args.port))
    atexit.register(connect.Disconnect, service_instance)
    atexit.register(endit)
except IOError as e:
    pass

if not service_instance:
    raise SystemExit("Unable to connect to host with supplied info.")

root_folder = service_instance.content.rootFolder
# List of properties.
# See: http://goo.gl/fjTEpW
# for all properties.

vm_properties = [
    "name", "config.hardware.numCPU", "guest.hostName", "guest.toolsVersion",
    "guest.guestFamily", "config.managedBy", "config.hardware.memoryMB",
    "guest.guestState", "summary.config.numVirtualDisks", "runtime.host",
    "config.guestFullName", "config.guestId", "config.version",
    "summary.guest.toolsRunningStatus", "summary.config.numEthernetCards",
    "config.template", "summary.runtime.powerState",
    "summary.config.vmPathName"
]
#"guest.ipStack"
args = cli.get_args()
service_instance = None
try:
    service_instance = connect.SmartConnect(host=args.host,
                                            user=args.user,
                                            pwd=args.password,
                                            port=int(args.port))
    atexit.register(connect.Disconnect, service_instance)
    atexit.register(endit)
except IOError as e:
    pass

if not service_instance:
    raise SystemExit("Unable to connect to host with supplied info.")

content_h = service_instance.RetrieveContent()