Python pyVim.connect.Disconnect() Examples

The following are 30 code examples of pyVim.connect.Disconnect(). 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 pyVim.connect , or try the search function .
Example #1
Source File: list_dc_datastore_info.py    From pyvmomi-community-samples with Apache License 2.0 7 votes vote down vote up
def main():
    args = get_args()

    # connect to vc
    si = SmartConnect(
        host=args.host,
        user=args.user,
        pwd=args.password,
        port=args.port)
    # disconnect vc
    atexit.register(Disconnect, si)

    content = si.RetrieveContent()
    # Get list of ds mo
    ds_obj_list = get_obj(content, [vim.Datastore], args.name)
    for ds in ds_obj_list:
        print_datastore_info(ds)

# start 
Example #2
Source File: add_portgroup_to_vswitch.py    From pyvmomi-community-samples with Apache License 2.0 7 votes vote down vote up
def main():
    args = get_args()
    if args.skip_verification:
        serviceInstance = SmartConnectNoSSL(host=args.host,
                                            user=args.user,
                                            pwd=args.password,
                                            port=443)
    else:
        serviceInstance = SmartConnect(host=args.host,
                                       user=args.user,
                                       pwd=args.password,
                                       port=443)
    atexit.register(Disconnect, serviceInstance)
    content = serviceInstance.RetrieveContent()

    hosts = GetVMHosts(content, args.regex_esxi)
    AddHostsPortgroup(hosts, args.vswitch, args.portgroup, args.vlanid)


# Main section 
Example #3
Source File: change_disk_mode.py    From pyvmomi-community-samples with Apache License 2.0 6 votes vote down vote up
def main():
    args = get_args()

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

    content = si.RetrieveContent()
    print 'Searching for VM {}'.format(args.vmname)
    vm_obj = get_obj(content, [vim.VirtualMachine], args.vmname)

    if vm_obj:
        change_disk_mode(si, vm_obj, args.disk_number, args.mode)
        print 'VM Disk {} successfully ' \
              'changed to mode {}.'.format(args.disk_number,
                                           args.mode)
    else:
        print "VM not found."

# start 
Example #4
Source File: getvnicinfo.py    From pyvmomi-community-samples with Apache License 2.0 6 votes vote down vote up
def main():
    global content, hosts, hostPgDict
    host, user, password = GetArgs()
    serviceInstance = SmartConnect(host=host,
                                   user=user,
                                   pwd=password,
                                   port=443)
    atexit.register(Disconnect, serviceInstance)
    content = serviceInstance.RetrieveContent()
    hosts = GetVMHosts(content)
    hostPgDict = GetHostsPortgroups(hosts)
    vms = GetVMs(content)
    for vm in vms:
        PrintVmInfo(vm)

# Main section 
Example #5
Source File: parallel.py    From vsphere-automation-sdk-python with MIT License 6 votes vote down vote up
def setup(context=None):
    global vm_name, client, service_instance, cleardata
    if context:
        # Run sample suite via setup script
        client = context.client
        vm_name = testbed.config['VM_NAME_DEFAULT']
        service_instance = context.service_instance
    else:
        # Run sample in standalone mode
        server, username, password, cleardata, skip_verification, vm_name = \
            parse_cli_args_vm(testbed.config['VM_NAME_DEFAULT'])
        session = get_unverified_session() if skip_verification else None
        client = create_vsphere_client(server=server,
                                       username=username,
                                       password=password,
                                       session=session)

        context = None
        if skip_verification:
            context = get_unverified_context()
        service_instance = SmartConnect(host=server,
                                        user=username,
                                        pwd=password,
                                        sslContext=context)
        atexit.register(Disconnect, service_instance) 
Example #6
Source File: change_vm_cd_backend.py    From pyvmomi-community-samples with Apache License 2.0 6 votes vote down vote up
def main():
    args = get_args()

    # connect to vc
    si = SmartConnect(
        host=args.host,
        user=args.user,
        pwd=args.password,
        port=args.port)
    # disconnect vc
    atexit.register(Disconnect, si)

    content = si.RetrieveContent()
    print 'Searching for VM {}'.format(args.vmname)
    vm_obj = get_obj(content, [vim.VirtualMachine], args.vmname)

    if vm_obj:
        update_virtual_cd_backend_by_obj(si, vm_obj, args.unitnumber, args.iso)
        device_change = args.iso if args.iso else 'Client Device'
        print 'VM CD/DVD {} successfully' \
              ' state changed to {}'.format(args.unitnumber, device_change)
    else:
        print "VM not found"

# start 
Example #7
Source File: vcenter_addvmk.py    From ansible-module-chaperone with Apache License 2.0 6 votes vote down vote up
def connect_to_vcenter(module, disconnect_atexit=True):
    hostname = module.params['host']
    username = module.params['login']
    password = module.params['password']
    port = module.params['port']

    try:
        service_instance = connect.SmartConnect(
            host=hostname,
            user=username,
            pwd=password,
            port=port
        )

        if disconnect_atexit:
            atexit.register(connect.Disconnect, service_instance)

        return service_instance.RetrieveContent()
    except vim.fault.InvalidLogin, invalid_login:
        module.fail_json(msg=invalid_login.msg, apierror=str(invalid_login)) 
Example #8
Source File: change_vm_nic_state.py    From pyvmomi-community-samples with Apache License 2.0 6 votes vote down vote up
def main():
    args = get_args()

    # connect to vc
    si = SmartConnect(
        host=args.host,
        user=args.user,
        pwd=args.password,
        port=args.port)
    # disconnect vc
    atexit.register(Disconnect, si)

    content = si.RetrieveContent()
    print 'Searching for VM {}'.format(args.vmname)
    vm_obj = get_obj(content, [vim.VirtualMachine], args.vmname)

    if vm_obj:
        update_virtual_nic_state(si, vm_obj, args.unitnumber, args.state)
        print 'VM NIC {} successfully' \
              ' state changed to {}'.format(args.unitnumber, args.state)
    else:
        print "VM not found"

# start 
Example #9
Source File: Hypervisor.py    From RENAT with Apache License 2.0 6 votes vote down vote up
def close(self):
        """ Closes and disconnects from a hypervisor
        """
        # self._channels[self._current_name]['connection'].Disconnect()
        channel = self._channels[self._current_name]
        Disconnect(channel['connection'])
        channel['ssh'].switch_connection(self._current_name+'_ssh')
        channel['ssh'].close_connection()
        channel['ssh_logger'].flush()
        channel['ssh_logger'].close()
        del(self._channels[self._current_name])

        # choose another active channel
        if len(self._channels) == 0:
            self._current_name = ''
            self._current_id = 0
            self._max_id = 0
        else:
            first = list(self._channels.keys())[0]
            self._current_name = self._channels[first]['name']
            self._current_id = self._channel[first]['id']

        return self._current_name 
Example #10
Source File: get_hosts_vswitch.py    From pyvmomi-community-samples with Apache License 2.0 6 votes vote down vote up
def main():
    args = get_args()
    serviceInstance = SmartConnect(host=args.host,
                                   user=args.user,
                                   pwd=args.password,
                                   port=443)
    atexit.register(Disconnect, serviceInstance)
    content = serviceInstance.RetrieveContent()

    hosts = GetVMHosts(content)
    hostSwitchesDict = GetHostsSwitches(hosts)

    for host, vswithes in hostSwitchesDict.items():
        for v in vswithes:
            print(v.name)


# Main section 
Example #11
Source File: create_dvs_and_dvport_group.py    From vmware-pyvmomi-examples with Apache License 2.0 6 votes vote down vote up
def main():
    try:
        si = None
        try:
            print "Trying to connect to VCENTER SERVER . . ."
            si = connect.Connect(inputs['vcenter_ip'], 443, inputs['vcenter_user'], inputs['vcenter_password'])
        except IOError, e:
            pass
            atexit.register(Disconnect, si)

        print "Connected to VCENTER SERVER !"
        
        content = si.RetrieveContent()
        datacenter = get_obj(content, [vim.Datacenter], inputs['datacenter'])
	cluster = get_obj(content, [vim.ClusterComputeResource], inputs['cluster'])
	network_folder = datacenter.networkFolder
	#Create DV Switch
	dv_switch = create_dvSwitch(si, content, network_folder, cluster)
	#Add port group to this switch
	add_dvPort_group(si, dv_switch) 
Example #12
Source File: get_vcenter_id.py    From ansible-module-chaperone with Apache License 2.0 5 votes vote down vote up
def si_connect(module):
    try:
        si = SmartConnect(host=module.params['host'],
                          user=module.params['login'],
                          pwd=module.params['password'],
                          port=module.params['port'])
    except:
        failmsg = "Could not connect to virtualserver"
        module.fail_json(msg=failmsg)

    atexit.register(Disconnect, si)

    return si 
Example #13
Source File: vSphereAutoRestartManager.py    From pyvmomi-community-samples with Apache License 2.0 5 votes vote down vote up
def get_connection(ipadd, user, password):
    try:
        connection = SmartConnect(
            host=ipadd, port=443, user=user, pwd=password)
    except Exception as e:
        print e
        raise SystemExit
    atexit.register(Disconnect, connection)
    return connection 
Example #14
Source File: ezmomi.py    From ezmomi with MIT License 5 votes vote down vote up
def connect(self):
        """Connect to vCenter server"""
        try:
            context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
            if self.config['no_ssl_verify']:
                requests.packages.urllib3.disable_warnings()
                context.verify_mode = ssl.CERT_NONE
                self.si = SmartConnectNoSSL(
                    host=self.config['server'],
                    user=self.config['username'],
                    pwd=self.config['password'],
                    port=int(self.config['port']),
                    certFile=None,
                    keyFile=None,
                )
            else:
                self.si = SmartConnect(
                    host=self.config['server'],
                    user=self.config['username'],
                    pwd=self.config['password'],
                    port=int(self.config['port']),
                    sslContext=context,
                    certFile=None,
                    keyFile=None,
                )
        except Exception as e:
            print('Unable to connect to vsphere server.')
            print(e)
            sys.exit(1)

        # add a clean up routine
        atexit.register(Disconnect, self.si)

        self.content = self.si.RetrieveContent() 
Example #15
Source File: run.py    From vcenter-netbox-sync with Apache License 2.0 5 votes vote down vote up
def authenticate(self):
        """Create a session to vCenter and authenticate against it"""
        log.info(
            "Attempting authentication to vCenter instance '%s'.",
            self.vc_host
            )
        try:
            vc_instance = SmartConnectNoSSL(
                host=self.vc_host,
                port=self.vc_port,
                user=self.vc_user,
                pwd=self.vc_pass,
                )
            atexit.register(Disconnect, vc_instance)
            self.vc_session = vc_instance.RetrieveContent()
            log.info(
                "Successfully authenticated to vCenter instance '%s'.",
                self.vc_host
                )
        except (gaierror, vim.fault.InvalidLogin, OSError) as err:
            if isinstance(err, OSError):
                err = "System unreachable."
            err_msg = (
                "Unable to connect to vCenter instance '{}' on port {}. "
                "Reason: {}".format(self.vc_host, self.vc_port, err)
                )
            log.critical(err_msg)
            raise ConnectionError(err_msg) 
Example #16
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 #17
Source File: vmware_walk.py    From ansible-tools with Apache License 2.0 5 votes vote down vote up
def connect_to_api(module, disconnect_atexit=True):

    # https://raw.githubusercontent.com/ansible/ansible/devel/lib/ansible/module_utils/vmware.py

    hostname = module.params['hostname']
    if ':' in hostname:
        hostname,portnumber = hostname.rsplit(':')
        portnumber = int(portnumber)
    else:
        portnumber = 443
    username = module.params['username']
    password = module.params['password']
    validate_certs = module.params['validate_certs']

    if validate_certs and not hasattr(ssl, 'SSLContext'):
        module.fail_json(msg='pyVim does not support changing verification mode with python < 2.7.9. Either update '
                             'python or or use validate_certs=false')

    try:
        service_instance = connect.SmartConnect(host=hostname, port=portnumber, user=username, pwd=password)
    except vim.fault.InvalidLogin as invalid_login:
        module.fail_json(msg=invalid_login.msg, apierror=str(invalid_login))
    except (requests.ConnectionError, ssl.SSLError) as connection_error:
        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=hostname, port=portnumber, user=username, pwd=password, sslContext=context)
        else:
            module.fail_json(msg="Unable to connect to vCenter or ESXi API on TCP/443.", apierror=str(connection_error))
    except Exception as e:
        context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
        context.verify_mode = ssl.CERT_NONE
        service_instance = connect.SmartConnect(host=hostname, port=portnumber, user=username, pwd=password, sslContext=context)

    # Disabling atexit should be used in special cases only.
    # Such as IP change of the ESXi host which removes the connection anyway.
    # Also removal significantly speeds up the return of the module
    if disconnect_atexit:
        atexit.register(connect.Disconnect, service_instance)
    return service_instance.RetrieveContent() 
Example #18
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 #19
Source File: interactive_wrapper.py    From pyvmomi-community-samples with Apache License 2.0 5 votes vote down vote up
def connect(self, username, password=None):
        """
        Connects to the vCenter host encapsulated by this VVC instance.

        - `username` (str) is the username to use for authentication.
        - `password` (str) is the password to use for authentication.
          If the password is not specified, a getpass prompt will be used.
        """
        if not password:
            password = getpass("Password for {0}: ".format(self.hostname))
        self.service_instance = connect.SmartConnect(host=self.hostname,
                                                     user=username,
                                                     pwd=password,
                                                     port=443)
        atexit.register(connect.Disconnect, self.service_instance) 
Example #20
Source File: del_portgroup_from_vswitch.py    From pyvmomi-community-samples with Apache License 2.0 5 votes vote down vote up
def main():
    args = get_args()
    serviceInstance = SmartConnect(host=args.host,
                                   user=args.user,
                                   pwd=args.password,
                                   port=443)
    atexit.register(Disconnect, serviceInstance)
    content = serviceInstance.RetrieveContent()

    hosts = GetVMHosts(content)
    DelHostsPortgroup(hosts, args.portgroup)


# Main section 
Example #21
Source File: vmware-v2.1.py    From Trillian with Apache License 2.0 5 votes vote down vote up
def connect_to_api(module, disconnect_atexit=True):

    hostname = module.params['hostname']
    username = module.params['username']
    password = module.params['password']
    validate_certs = module.params['validate_certs']

    if validate_certs and not hasattr(ssl, 'SSLContext'):
        module.fail_json(msg='pyVim does not support changing verification mode with python < 2.7.9. Either update python or or use validate_certs=false')

    try:
        service_instance = connect.SmartConnect(host=hostname, user=username, pwd=password)
    except vim.fault.InvalidLogin as invalid_login:
        module.fail_json(msg=invalid_login.msg, apierror=str(invalid_login))
    except (requests.ConnectionError, ssl.SSLError) as connection_error:
        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=hostname, user=username, pwd=password, sslContext=context)
        else:
            module.fail_json(msg="Unable to connect to vCenter or ESXi API on TCP/443.", apierror=str(connection_error))

    # Disabling atexit should be used in special cases only.
    # Such as IP change of the ESXi host which removes the connection anyway.
    # Also removal significantly speeds up the return of the module
    if disconnect_atexit:
        atexit.register(connect.Disconnect, service_instance)
    return service_instance.RetrieveContent() 
Example #22
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 #23
Source File: add_vswitch_to_host.py    From pyvmomi-community-samples with Apache License 2.0 5 votes vote down vote up
def main():
    args = get_args()
    serviceInstance = SmartConnect(host=args.host,
                                   user=args.user,
                                   pwd=args.password,
                                   port=443)
    atexit.register(Disconnect, serviceInstance)
    content = serviceInstance.RetrieveContent()

    hosts = GetVMHosts(content)
    AddHostsSwitch(hosts, args.vswitch)


# Main section 
Example #24
Source File: add_raw_disk_to_vm.py    From pyvmomi-community-samples with Apache License 2.0 5 votes vote down vote up
def main():
    args = get_args()

    # create the service instance
    si = None
    if args.disable_ssl_verification:
        si = SmartConnectNoSSL(host=args.host,
                               user=args.user,
                               pwd=args.password,
                               port=args.port)
    else:
        si = SmartConnect(host=args.host,
                          user=args.user,
                          pwd=args.password,
                          port=args.port)

    # disconnect the service instance at program exit
    atexit.register(Disconnect, si)

    vm = None
    if args.uuid:
        search_index = si.content.searchIndex
        vm = search_index.FindByUuid(None, args.uuid, True)
    elif args.vm_name:
        content = si.RetrieveContent()
        vm = get_obj(content, [vim.VirtualMachine], args.vm_name)

    if vm:
        add_raw_disk(vm, si, args.device_name,
                     args.disk_mode, args.compatibility_mode)
    else:
        print "VM not found"


# start this thing 
Example #25
Source File: delete_nic_from_vm.py    From pyvmomi-community-samples with Apache License 2.0 5 votes vote down vote up
def main():
    args = get_args()

    # connect this thing
    serviceInstance = SmartConnect(
            host=args.host,
            user=args.user,
            pwd=args.password,
            port=args.port)
    # disconnect this thing
    atexit.register(Disconnect, serviceInstance)

    vm = None
    if args.uuid:
        search_index = serviceInstance.content.searchIndex
        vm = search_index.FindByUuid(None, args.uuid, True)
    elif args.vm_name:
        content = serviceInstance.RetrieveContent()
        vm = get_obj(content, [vim.VirtualMachine], args.vm_name)

    if vm:
        del_nic(serviceInstance, vm, int(args.unit_number))
    else:
        print "VM not found"

# start this thing 
Example #26
Source File: create_folder_in_datacenter.py    From pyvmomi-community-samples with Apache License 2.0 5 votes vote down vote up
def main():
    """
    Simple command-line program for creating host and VM folders in a
    datacenter.
    """
    args = GetArgs()
    if args.password:
        password = args.password
    else:
        password = getpass.getpass(prompt='Enter password for host %s and '
                                   'user %s: ' % (args.host, args.user))

    si = SmartConnect(host=args.host,
                      user=args.user,
                      pwd=password,
                      port=int(args.port))
    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()
    dc = get_obj(content, [vim.Datacenter], args.datacenter)
    if (get_obj(content, [vim.Folder], args.folder)):
        print("Folder '%s' already exists" % args.folder)
        return 0
    create_folder(content, dc.hostFolder, args.folder)
    print("Successfully created the host folder '%s'" % args.folder)
    create_folder(content, dc.vmFolder, args.folder)
    print("Successfully created the VM folder '%s'" % args.folder)
    return 0

# Start program 
Example #27
Source File: reconfigure_host_for_ha.py    From pyvmomi-community-samples with Apache License 2.0 5 votes vote down vote up
def main():
    args = get_args()

    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("Unable to connect with the vCenter Server "
              "using the provided credentials")
        return -1

    atexit.register(connect.Disconnect, service_instance)

    content = service_instance.RetrieveContent()
    object_view = content.viewManager.CreateContainerView(content.rootFolder,
                                                          [vim.HostSystem],
                                                          True)

    host_list = object_view.view
    object_view.Destroy()

    for host in host_list:
        if host.name == args.esx_host:
            esx = host

    print "Proceeding to execute operation 'Reconfigure for HA' in host %s" % \
          esx.name
    reconf_ha = esx.ReconfigureHostForDAS_Task()
    task = reconf_ha
    tasks.wait_for_tasks(service_instance, [task])
    print "Operation complete"

    return 0

# Main execution 
Example #28
Source File: get_portgroup.py    From pyvmomi-community-samples with Apache License 2.0 5 votes vote down vote up
def main():
    """
    Simple command-line program for retrieving a port group
    """

    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()

        # searching for port group
        pg = get_obj(content, [vim.Network], args.portgroupname)
        print(pg)

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

    return 0


# Start program 
Example #29
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 #30
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