Python pyVmomi.vmodl.MethodFault() Examples

The following are 30 code examples of pyVmomi.vmodl.MethodFault(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module pyVmomi.vmodl , or try the search function .
Example #1
Source File: vmware_exporter.py    From vmware_exporter with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def connection(self):
        """
        Connect to Vcenter and get connection
        """
        context = None
        if self.ignore_ssl:
            context = ssl._create_unverified_context()

        try:
            vmware_connect = yield threads.deferToThread(
                connect.SmartConnect,
                host=self.host,
                user=self.username,
                pwd=self.password,
                sslContext=context,
            )
            return vmware_connect

        except vmodl.MethodFault as error:
            logging.error("Caught vmodl fault: {error}".format(error=error.msg))
            return None 
Example #2
Source File: vmware_host.py    From Trillian with Apache License 2.0 6 votes vote down vote up
def process_state(self):
        try:
            # Currently state_update_dvs is not implemented.
            host_states = {
                'absent': {
                    'present': self.state_remove_host,
                    'absent': self.state_exit_unchanged,
                },
                'present': {
                    'present': self.state_exit_unchanged,
                    'absent': self.state_add_host,
                }
            }

            host_states[self.state][self.check_host_state()]()

        except vmodl.RuntimeFault as runtime_fault:
            self.module.fail_json(msg=runtime_fault.msg)
        except vmodl.MethodFault as method_fault:
            self.module.fail_json(msg=method_fault.msg)
        except Exception as e:
            self.module.fail_json(msg=str(e)) 
Example #3
Source File: vmware-datacenter.py    From Trillian with Apache License 2.0 6 votes vote down vote up
def destroy_datacenter(context, module):
    result = None

    try:
        datacenter = get_datacenter(context, module)
        if datacenter:
            changed = True
            if not module.check_mode:
                task = datacenter.Destroy_Task()
                changed, result = wait_for_task(task)
        module.exit_json(changed=changed, result=result)
    except vim.fault.VimFault as vim_fault:
        module.fail_json(msg=vim_fault.msg)
    except vmodl.RuntimeFault as runtime_fault:
        module.fail_json(msg=runtime_fault.msg)
    except vmodl.MethodFault as method_fault:
        module.fail_json(msg=method_fault.msg) 
Example #4
Source File: vmware-datacenter.py    From Trillian with Apache License 2.0 6 votes vote down vote up
def create_datacenter(context, module):
    datacenter_name = module.params.get('datacenter_name')
    folder = context.rootFolder

    try:
        datacenter = get_datacenter(context, module)
        if not datacenter:
            changed = True
            if not module.check_mode:
                folder.CreateDatacenter(name=datacenter_name)
        module.exit_json(changed=changed)
    except vim.fault.DuplicateName:
        module.fail_json(msg="A datacenter with the name %s already exists" % datacenter_name)
    except vim.fault.InvalidName:
        module.fail_json(msg="%s is an invalid name for a cluster" % datacenter_name)
    except vmodl.fault.NotSupported:
        # This should never happen
        module.fail_json(msg="Trying to create a datacenter on an incorrect folder object")
    except vmodl.RuntimeFault as runtime_fault:
        module.fail_json(msg=runtime_fault.msg)
    except vmodl.MethodFault as method_fault:
        module.fail_json(msg=method_fault.msg) 
Example #5
Source File: vmware_exporter.py    From vmware_exporter with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _vmware_connect(self, vsphere_host, section):
        """
        Connect to Vcenter and get connection
        """
        vsphere_user = self.config[section].get('vsphere_user')
        vsphere_password = self.config[section].get('vsphere_password')

        context = None
        if self.config[section].get('ignore_ssl') and \
                hasattr(ssl, "_create_unverified_context"):
            context = ssl._create_unverified_context()

        try:
            vmware_connect = connect.Connect(vsphere_host, 443,
                                             vsphere_user,
                                             vsphere_password,
                                             sslContext=context
                                             )

            return vmware_connect

        except vmodl.MethodFault as error:
            log("Caught vmodl fault: " + error.msg)
            return None 
Example #6
Source File: deploy_ova.py    From pyvmomi-community-samples with Apache License 2.0 6 votes vote down vote up
def upload_disks(self, lease, host):
        """
        Uploads all the disks, with a progress keep-alive.
        """
        self.lease = lease
        try:
            self.start_timer()
            for fileItem in self.spec.fileItem:
                self.upload_disk(fileItem, lease, host)
            lease.Complete()
            print("Finished deploy successfully.")
            return 0
        except vmodl.MethodFault as e:
            print("Hit an error in upload: %s" % e)
            lease.Abort(e)
        except Exception as e:
            print("Lease: %s" % lease.info)
            print("Hit an error in upload: %s" % e)
            lease.Abort(vmodl.fault.SystemError(reason=str(e)))
            raise
        return 1 
Example #7
Source File: vsphere-monitor.py    From vsphere-monitor with Apache License 2.0 5 votes vote down vote up
def hello_vcenter(vchost,username,password,port):
    try:
        si = SmartConnectNoSSL(
            host=vchost,
            user=username,
            pwd=password,
            port=port)

        atexit.register(Disconnect, si)
        return True, "ok"
    except vmodl.MethodFault as error:
        return False, error.msg
    except Exception as e:
        return False, str(e) 
Example #8
Source File: vmware-datacenter.py    From Trillian with Apache License 2.0 5 votes vote down vote up
def get_datacenter(context, module):
    try:
        datacenter_name = module.params.get('datacenter_name')
        datacenter = find_datacenter_by_name(context, datacenter_name)
        return datacenter
    except vmodl.RuntimeFault as runtime_fault:
        module.fail_json(msg=runtime_fault.msg)
    except vmodl.MethodFault as method_fault:
        module.fail_json(msg=method_fault.msg) 
Example #9
Source File: vsphere.py    From ocs-ci with MIT License 5 votes vote down vote up
def _get_service_instance(self):
        """
        Gets the service instance

        Returns:
            vim.ServiceInstance: Service Instance for Host

        """
        try:
            smart_stub = SmartStubAdapter(
                host=self._host,
                port=int(self._port),
                sslContext=self.sslContext,
                connectionPoolTimeout=0
            )
            session_stub = VimSessionOrientedStub(
                smart_stub,
                VimSessionOrientedStub.makeUserLoginMethod(self._user, self._password))
            service_instance = vim.ServiceInstance('ServiceInstance', session_stub)

            # Ensure connection to server is closed on program exit
            atexit.register(Disconnect, service_instance)
            return service_instance
        except vmodl.MethodFault as error:
            logger.error(f"Caught vmodl fault : {error.msg}")
            raise 
Example #10
Source File: hello_world_vcenter_with_yaml_recorder.py    From pyvmomi-community-samples with Apache License 2.0 5 votes vote down vote up
def main():
    """
    Simple command-line program for listing the virtual machines on a system.
    """

    args = get_args()

    try:
        my_vcr = vcr.VCR()
        # use the vcr instance to setup an instance of service_instance
        with my_vcr.use_cassette('hello_world_vcenter.yaml',
                                 record_mode='all'):
            service_instance = connect.SmartConnect(host=args.host,
                                                    user=args.user,
                                                    pwd=args.password,
                                                    port=int(args.port))
            # the recording will show up in the working directory

        atexit.register(connect.Disconnect, service_instance)

        print "\nHello World!\n"
        print "If you got here, you authenticted into vCenter."
        print "The server is {0}!".format(args.host)
        # NOTE (hartsock): only a successfully authenticated session has a
        # session key aka session id.
        session_id = service_instance.content.sessionManager.currentSession.key
        print "current session id: {0}".format(session_id)
        print "Well done!"
        print "\n"
        print "Download, learn and contribute back:"
        print "https://github.com/vmware/pyvmomi-community-samples"
        print "\n\n"

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

    return 0

# Start program 
Example #11
Source File: waitforupdates.py    From pyvmomi-community-samples with Apache License 2.0 5 votes vote down vote up
def main():
    """
    Sample Python program for monitoring property changes to objects of
    one or more types to stdout
    """

    args = get_args()

    if args.password:
        password = args.password
    else:
        password = getpass.getpass(prompt='Enter password for host %s and '
                                   'user %s: ' % (args.host, args.user))

    try:
        if args.disable_ssl_warnings:
            from requests.packages import urllib3
            urllib3.disable_warnings()

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

        if not si:
            print >>sys.stderr, "Could not connect to the specified host ' \
                                'using specified username and password"
            raise

        atexit.register(Disconnect, si)

        propspec = parse_propspec(args.propspec)

        print "Monitoring property changes.  Press ^C to exit"
        monitor_property_changes(si, propspec, args.iterations)

    except vmodl.MethodFault, e:
        print >>sys.stderr, "Caught vmodl fault :\n%s" % str(e)
        raise 
Example #12
Source File: hello_world_vcenter.py    From pyvmomi-community-samples with Apache License 2.0 5 votes vote down vote up
def main():
    """
    Simple command-line program for listing the virtual machines on a system.
    """

    args = 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)

        print "\nHello World!\n"
        print "If you got here, you authenticted into vCenter."
        print "The server is {}!".format(args.host)
        # NOTE (hartsock): only a successfully authenticated session has a
        # session key aka session id.
        session_id = service_instance.content.sessionManager.currentSession.key
        print "current session id: {}".format(session_id)
        print "Well done!"
        print "\n"
        print "Download, learn and contribute back:"
        print "https://github.com/vmware/pyvmomi-community-samples"
        print "\n\n"

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

    return 0

# Start program 
Example #13
Source File: configure_dvs_port_group.py    From pyvmomi-community-samples with Apache License 2.0 5 votes vote down vote up
def main():

    args = get_args()

    try:
        if args.disable_ssl_verification:
            service_instance = SmartConnectNoSSL(host=args.host,
                                                 user=args.user,
                                                 pwd=args.password,
                                                 port=args.port)
        else:
            service_instance = SmartConnect(host=args.host,
                                            user=args.user,
                                            pwd=args.password,
                                            port=args.port)

        atexit.register(Disconnect, service_instance)

        # call configuration of dvs port group
        configure_dvs_pg(service_instance, args.dvs_name, args.dvs_pg_name)

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

    return 0


# Start program 
Example #14
Source File: list_datastore_cluster.py    From pyvmomi-community-samples with Apache License 2.0 5 votes vote down vote up
def main():
    """
   Simple command-line program for listing Datastores in Datastore Cluster
   """

    args = 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()
        # Search for all Datastore Clusters aka StoragePod
        obj_view = content.viewManager.CreateContainerView(content.rootFolder,
                                                           [vim.StoragePod],
                                                           True)
        ds_cluster_list = obj_view.view
        obj_view.Destroy()

        for ds_cluster in ds_cluster_list:
            if ds_cluster.name == args.dscluster:
                datastores = ds_cluster.childEntity
                print "Datastores: "
                for datastore in datastores:
                    print datastore.name

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

    return 0

# Start program 
Example #15
Source File: 01_get_vmware_vm_info.py    From blueprints with MIT License 5 votes vote down vote up
def makeConnect(parser):
    """
    :return:
    """
    try:
        context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
        context.verify_mode = ssl.CERT_NONE

        service_instance = connect.SmartConnect(
            host=parser.vcenterip,
            user=parser.user,
            pwd=parser.password,
            port=parser.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)

        parse_service_instance(parser.clustername, service_instance)

    except vmodl.MethodFault as e:
        return -1
    return 0 
Example #16
Source File: vmware.py    From DevOps with GNU General Public License v2.0 5 votes vote down vote up
def get_all_vms(self):
        try:
            content = self.service_instance.RetrieveContent()
            container = content.rootFolder
            viewType = [vim.VirtualMachine]
            recursive = True
            containerView = content.viewManager.CreateContainerView(
                container, viewType, recursive
            )
            children = containerView.view
            return children
        except vmodl.MethodFault as error:
            return -1 
Example #17
Source File: vmware.py    From DevOps with GNU General Public License v2.0 5 votes vote down vote up
def get_vm_monitor(self,vm):
        try:
            content = self.service_instance.RetrieveContent()
            perfManager = content.perfManager
            metricId = vim.PerformanceManager.MetricId(counterId=2, instance="*")
            import datetime
            startTime = datetime.datetime.now() - datetime.timedelta(hours=3)
            endTime = datetime.datetime.now()
            # query = vim.PerformanceManager.QuerySpec(maxSample=1,
            #                                          entity=vm,
            #                                          metricId=[metricId],
            #                                          startTime=startTime,
            #                                          endTime=endTime)
            # query = vim.PerformanceManager.QueryAvailablePerfMetric(entity=vm,
            #                                                         startTime=startTime,
            #                                                         endTime=endTime)
            query = perfManager.QueryPerfProviderSummary(entity=vm)
            print(query)
            # print(perfManager.QueryPerf(querySpec=[query]))
            # print(perfManager.QueryPerfCounter(counterId=[24,]))
            # print(perfManager.QueryPerfCounterByLevel(level=1))
            '''
                2 CPU 在该时间间隔内的使用情况(百分比) CPU
                24 内存使用情况,表示为占总的配置或可用内存的百分比 MEMORY
                136 收集时间间隔内每秒钟磁盘平均读取次数 DISK OUT
                137 收集时间间隔内每秒钟磁盘平均写入次数 DISK IN
                146 该时间间隔内收到的数据包数 NETWORK
            '''
        except vmodl.MethodFault as e:
            print("Caught vmodl fault : " + e.msg)
            return -1
        except Exception as e:
            print("Caught exception : " + str(e))
        return -1 
Example #18
Source File: relocate_vm.py    From pyvmomi-community-samples with Apache License 2.0 5 votes vote down vote up
def main():

    args = get_args()

    try:
        if args.disable_ssl_verification:
            service_instance = SmartConnectNoSSL(host=args.host,
                                                 user=args.user,
                                                 pwd=args.password,
                                                 port=args.port)
        else:
            service_instance = SmartConnect(host=args.host,
                                            user=args.user,
                                            pwd=args.password,
                                            port=args.port)

        atexit.register(Disconnect, service_instance)

        content = service_instance.RetrieveContent()

        # Assigning destination datastores
        datastore_dest = args.datastore_dest

        # Target compute resource
        host_dest = args.target_esx_host

        relocate_vm(args.vm_name,
                    content=content,
                    host_dest=host_dest,
                    datastore_dest=datastore_dest)

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

    return 0


# Start program 
Example #19
Source File: fcd_list_vdisk_snapshots.py    From pyvmomi-community-samples with Apache License 2.0 5 votes vote down vote up
def main():
    """
    Simple command-line program for listing all snapshots of a fcd
    """

    args = get_args()

    try:
        if args.disable_ssl_verification:
            service_instance = connect.SmartConnectNoSSL(host=args.host,
                                                         user=args.user,
                                                         pwd=args.password,
                                                         port=int(args.port))
        else:
            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()

        # Retrieve Datastore Object
        datastore = disk.get_obj(content, [vim.Datastore], args.datastore)

        # Retrieve FCD Object
        vdisk = disk.retrieve_fcd(content, datastore, args.vdisk)

        # Retrieve all Snapshots
        list_fcd_snapshots(content, vdisk)

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

    return 0


# Start program 
Example #20
Source File: vcenter_details.py    From pyvmomi-community-samples with Apache License 2.0 5 votes vote down vote up
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

# Start program 
Example #21
Source File: fcd_delete_vdisk.py    From pyvmomi-community-samples with Apache License 2.0 4 votes vote down vote up
def main():
    """
    Simple command-line program for deleting a snapshot of a first class disk.
    """

    args = get_args()

    try:
        if args.disable_ssl_verification:
            service_instance = connect.SmartConnectNoSSL(host=args.host,
                                                         user=args.user,
                                                         pwd=args.password,
                                                         port=int(args.port))
        else:
            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()

        # Retrieve Datastore Object
        datastore = disk.get_obj(content, [vim.Datastore], args.datastore)

        # Retrieve FCD Object
        vdisk = disk.retrieve_fcd(content, datastore, args.vdisk)

        # Confirming FCD deletion
        if not args.yes:
            response = cli.prompt_y_n_question("Are you sure you want to "
                                               "delete vdisk '" + args.vdisk +
                                               "'?",
                                               default='no')
            if not response:
                print("Exiting script. User chose not to delete HDD.")
                exit()

        # Delete FCD
        storage = content.vStorageObjectManager
        task = storage.DeleteVStorageObject_Task(vdisk.config.id, datastore)
        tasks.wait_for_tasks(service_instance, [task])

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

    return 0


# Start program 
Example #22
Source File: detach_disk_from_vm.py    From pyvmomi-community-samples with Apache License 2.0 4 votes vote down vote up
def main():
    """
    Simple command-line program for detaching a disk from a virtual machine.
    """

    args = get_args()

    try:
        if args.disable_ssl_verification:
            service_instance = connect.SmartConnectNoSSL(host=args.host,
                                                         user=args.user,
                                                         pwd=args.password,
                                                         port=int(args.port))
        else:
            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()

        # Retrieve VM
        vm = None
        if args.uuid:
            search_index = content.searchIndex
            vm = search_index.FindByUuid(None, args.uuid, True)
        elif args.vm_name:
            vm = disk.get_obj(content, [vim.VirtualMachine], args.vm_name)

        # Detaching Disk from VM
        if vm:
            task = detach_disk_from_vm(vm, args.disknumber, args.language)
            tasks.wait_for_tasks(service_instance, [task])
        else:
            raise RuntimeError("VM not found.")

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

    return 0


# Start program 
Example #23
Source File: fcd_delete_vdisk_snapshot.py    From pyvmomi-community-samples with Apache License 2.0 4 votes vote down vote up
def main():
    """
    Simple command-line program for deleting a snapshot of a first class disk.
    """

    args = get_args()

    try:
        if args.disable_ssl_verification:
            service_instance = connect.SmartConnectNoSSL(host=args.host,
                                                         user=args.user,
                                                         pwd=args.password,
                                                         port=int(args.port))
        else:
            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()

        # Retrieve Datastore Object
        datastore = disk.get_obj(content, [vim.Datastore], args.datastore)

        # Retrieve FCD Object
        vdisk = disk.retrieve_fcd(content, datastore, args.vdisk)

        # Retrieve Snapshot Object
        snapshot = disk.retrieve_fcd_snapshot(
            content, datastore, vdisk, args.snapshot)

        # Confirming Snapshot deletion
        if not args.yes:
            response = cli.prompt_y_n_question("Are you sure you want to "
                                               "delete snapshot '" +
                                               args.snapshot + "'?",
                                               default='no')
            if not response:
                print("Exiting script. User chose not to delete snapshot.")
                exit()

        # Delete FCD Snapshot
        storage = content.vStorageObjectManager
        task = storage.DeleteSnapshot_Task(
            vdisk.config.id, datastore, snapshot)
        tasks.wait_for_tasks(service_instance, [task])

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

    return 0


# Start program 
Example #24
Source File: fcd_create_vdisk_snapshot.py    From pyvmomi-community-samples with Apache License 2.0 4 votes vote down vote up
def main():
    """
    Simple command-line program for creating a snapshot of a first class disk.
    """

    args = get_args()

    try:
        if args.disable_ssl_verification:
            service_instance = connect.SmartConnectNoSSL(host=args.host,
                                                         user=args.user,
                                                         pwd=args.password,
                                                         port=int(args.port))
        else:
            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()

        # Retrieve Datastore Object
        datastore = disk.get_obj(content, [vim.Datastore], args.datastore)

        # Retrieve FCD Object
        vdisk = disk.retrieve_fcd(content, datastore, args.vdisk)

        # Create FCD Snapshot
        storage = content.vStorageObjectManager
        task = storage.VStorageObjectCreateSnapshot_Task(
            vdisk.config.id, datastore, args.snapshot)
        tasks.wait_for_tasks(service_instance, [task])

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

    return 0


# Start program 
Example #25
Source File: py-vminfo-web.py    From python-vmstats with MIT License 4 votes vote down vote up
def main():
    args = viconfig.GetArgs()
    try:
        vmnames = form['vmname'].value
        si = None
        if args['password']:
            password = args['password']
        else:
            password = getpass.getpass(prompt="Enter password for host {} and user {}: ".format(args['host'], args['user']))
        try:
            context = ssl._create_unverified_context()
            si = SmartConnect(host=args['host'],
                user=args['user'],
                pwd=password,
                port=int(args['port']),
                sslContext=context)
        except IOError as e:
            pass
        if not si:
            print('Could not connect to the specified host using specified username and password')
            return -1

        atexit.register(Disconnect, si)
        content = si.RetrieveContent()
        # Get vCenter date and time for use as baseline when querying for counters
        vchtime = si.CurrentTime()

        # Get all the performance counters
        perf_dict = {}
        perfList = content.perfManager.perfCounter
        for counter in perfList:
            counter_full = "{}.{}.{}".format(counter.groupInfo.key, counter.nameInfo.key, counter.rollupType)
            perf_dict[counter_full] = counter.key

        retProps = GetProperties(content, [vim.VirtualMachine], ['name', 'runtime.powerState'], vim.VirtualMachine)

        #Find VM supplied as arg and use Managed Object Reference (moref) for the PrintVmInfo
        for vm in retProps:
            if (vm['name'] in vmnames) and (vm['runtime.powerState'] == "poweredOn"):
                PrintVmInfo(vm['moref'], content, vchtime, int(form['vminterval'].value), perf_dict)
            elif vm['name'] in vmnames:
                print('ERROR: Problem connecting to Virtual Machine.  {} is likely powered off or suspended'.format(vm['name']))

    except vmodl.MethodFault as e:
        print('Caught vmodl fault : ' + e.msg)
        return -1
    except Exception as e:
        print('Caught exception : ' + str(e))
        return -1

    return 0

# Start program 
Example #26
Source File: py-vminfo.py    From python-vmstats with MIT License 4 votes vote down vote up
def main():
    args = GetArgs()
    try:
        vmnames = args.vm
        si = None
        if args.password:
            password = args.password
        else:
            password = getpass.getpass(prompt="Enter password for host {} and user {}: ".format(args.host, args.user))
        try:
            if args.cert_check_skip:
                context = ssl._create_unverified_context()
                si = SmartConnect(host=args.host,
                                  user=args.user,
                                  pwd=password,
                                  port=int(args.port),
                                  sslContext=context)
            else:
                si = SmartConnect(host=args.host,
                                  user=args.user,
                                  pwd=password,
                                  port=int(args.port))
        except IOError as e:
            pass
        if not si:
            print('Could not connect to the specified host using specified username and password')
            return -1

        atexit.register(Disconnect, si)
        content = si.RetrieveContent()
        # Get vCenter date and time for use as baseline when querying for counters
        vchtime = si.CurrentTime()

        # Get all the performance counters
        perf_dict = {}
        perfList = content.perfManager.perfCounter
        for counter in perfList:
            counter_full = "{}.{}.{}".format(counter.groupInfo.key, counter.nameInfo.key, counter.rollupType)
            perf_dict[counter_full] = counter.key

        retProps = GetProperties(content, [vim.VirtualMachine], ['name', 'runtime.powerState'], vim.VirtualMachine)

        #Find VM supplied as arg and use Managed Object Reference (moref) for the PrintVmInfo
        for vm in retProps:
            if (vm['name'] in vmnames) and (vm['runtime.powerState'] == "poweredOn"):
                PrintVmInfo(vm['moref'], content, vchtime, args.interval, perf_dict)
            elif vm['name'] in vmnames:
                print('ERROR: Problem connecting to Virtual Machine.  {} is likely powered off or suspended'.format(vm['name']))

    except vmodl.MethodFault as e:
        print('Caught vmodl fault : ' + e.msg)
        return -1
    except Exception as e:
        print('Caught exception : ' + str(e))
        return -1

    return 0

# Start program 
Example #27
Source File: vcenter_addvmk.py    From ansible-module-chaperone with Apache License 2.0 4 votes vote down vote up
def main():
    #argument_spec = vmware_argument_spec()

    argument_spec=dict(
            host=dict(required=True, type='str'),
            login=dict(required=True, type='str'),
            password=dict(required=True, type='str'),
            port=dict(required=True, type='int'),
            esxi_hostname=dict(required=True, type='str'),
            portgroup_name=dict(required=True, type='str'),
            dhcp=dict(required=True, type='bool'),
            ip_address=dict(required=False, type='str'),
            subnet_mask=dict(required=False, type='str'),
            service_type=dict(default=None, required=False, type='str'),
            mtu=dict(required=False, type='int', default=1500),
            state=dict(default='present', choices=['present', 'absent'], type='str'))


    module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=False)

    if not HAS_PYVMOMI:
        module.fail_json(msg='pyvmomi is required for this module')

    try:
        vmk_host_states = {
            'absent': {
                'update': state_delete_vmk_host,
                'present': state_delete_vmk_host,
                'absent': state_exit_unchanged,
            },
            'present': {
                'update': state_update_vmk_host,
                'present': state_exit_unchanged,
                'absent': state_create_vmk_host,
            }
        }

        vmk_host_states[module.params['state']][check_vmk_host_state(module)](module)

    except vmodl.RuntimeFault as runtime_fault:
        module.fail_json(msg=runtime_fault.msg)
    except vmodl.MethodFault as method_fault:
        module.fail_json(msg=method_fault.msg)
    except Exception as e:
        module.fail_json(msg=str(e)) 
Example #28
Source File: getallvms.py    From pyvmomi-community-samples with Apache License 2.0 4 votes vote down vote up
def main():
    """
    Simple command-line program for listing the virtual machines on a system.
    """

    args = get_args()

    try:
        if args.disable_ssl_verification:
            service_instance = connect.SmartConnectNoSSL(host=args.host,
                                                         user=args.user,
                                                         pwd=args.password,
                                                         port=int(args.port))
        else:
            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
        if args.find is not None:
            pat = re.compile(args.find, re.IGNORECASE)
        for child in children:
            if args.find is None:
                print_vm_info(child)
            else:
                if pat.search(child.summary.config.name) is not None:
                    print_vm_info(child)

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

    return 0


# Start program 
Example #29
Source File: waitforupdates.py    From pyvmomi-community-samples with Apache License 2.0 4 votes vote down vote up
def make_property_collector(pc, from_node, props):
    """
    :type pc: pyVmomi.VmomiSupport.vmodl.query.PropertyCollector
    :type from_node: pyVmomi.VmomiSupport.ManagedObject
    :type props: collections.Sequence
    :rtype: pyVmomi.VmomiSupport.vmodl.query.PropertyCollector.Filter
    """

    # Make the filter spec
    filterSpec = vmodl.query.PropertyCollector.FilterSpec()

    # Make the object spec
    traversal = serviceutil.build_full_traversal()

    objSpec = vmodl.query.PropertyCollector.ObjectSpec(obj=from_node,
                                                       selectSet=traversal)
    objSpecs = [objSpec]

    filterSpec.objectSet = objSpecs

    # Add the property specs
    propSet = []
    for motype, proplist in props:
        propSpec = \
            vmodl.query.PropertyCollector.PropertySpec(type=motype, all=False)
        propSpec.pathSet.extend(proplist)
        propSet.append(propSpec)

    filterSpec.propSet = propSet

    try:
        pcFilter = pc.CreateFilter(filterSpec, True)
        atexit.register(pcFilter.Destroy)
        return pcFilter
    except vmodl.MethodFault, e:
        if e._wsdlName == 'InvalidProperty':
            print >> sys.stderr, "InvalidProperty fault while creating " \
                                 "PropertyCollector filter : %s" % e.name
        else:
            print >> sys.stderr, "Problem creating PropertyCollector " \
                                 "filter : %s" % str(e.faultMessage)
        raise 
Example #30
Source File: upload_file_to_vm.py    From pyvmomi-community-samples with Apache License 2.0 4 votes vote down vote up
def main():
    """
    Simple command-line program for Uploading a file from host to guest
    """

    args = get_args()
    vm_path = args.path_inside_vm
    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()

        vm = content.searchIndex.FindByUuid(None, args.vm_uuid, True)
        tools_status = vm.guest.toolsStatus
        if (tools_status == 'toolsNotInstalled' or
                tools_status == 'toolsNotRunning'):
            raise SystemExit(
                "VMwareTools is either not running or not installed. "
                "Rerun the script after verifying that VMWareTools "
                "is running")

        creds = vim.vm.guest.NamePasswordAuthentication(
            username=args.vm_user, password=args.vm_pwd)
        with open(args.upload_file, 'rb') as myfile:
            fileinmemory = myfile.read()

        try:
            file_attribute = vim.vm.guest.FileManager.FileAttributes()
            url = content.guestOperationsManager.fileManager. \
                InitiateFileTransferToGuest(vm, creds, vm_path,
                                            file_attribute,
                                            len(fileinmemory), True)
            # When : host argument becomes https://*:443/guestFile?
            # Ref: https://github.com/vmware/pyvmomi/blob/master/docs/ \
            #            vim/vm/guest/FileManager.rst
            # Script fails in that case, saying URL has an invalid label.
            # By having hostname in place will take take care of this.
            url = re.sub(r"^https://\*:", "https://"+str(args.host)+":", url)
            resp = requests.put(url, data=fileinmemory, verify=False)
            if not resp.status_code == 200:
                print "Error while uploading file"
            else:
                print "Successfully uploaded file"
        except IOError, e:
            print e
    except vmodl.MethodFault as error:
        print "Caught vmodl fault : " + error.msg
        return -1

    return 0

# Start program