Python pyVim.connect.SmartConnect() Examples
The following are 30
code examples of pyVim.connect.SmartConnect().
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 |
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: vSphere.py From im with GNU General Public License v3.0 | 7 votes |
def attach_volumes(self, conn, node, vm): """ Attach a the required volumes (in the RADL) to the launched instance Arguments: - conn(:py:class:`vim.connect.SmartConnect` ): Connection object. - node(:py:class:`vim.VirtualMachine` ): VM to add the disk. - vm(:py:class:`IM.VirtualMachine`): VM information. """ try: if node.summary.runtime.powerState == "poweredOn" and "volumes" not in vm.__dict__.keys(): # Flag to set that this VM has created (or is creating) the # volumes vm.volumes = True cont = 1 while vm.info.systems[0].getValue("disk." + str(cont) + ".size"): disk_size = vm.info.systems[0].getFeature("disk." + str(cont) + ".size").getValue('G') # disk_device = vm.info.systems[0].getValue("disk." + str(cont) + ".device") self.log_info("Creating a %d GB volume for the disk %d" % (int(disk_size), cont)) self.add_disk(node, conn, disk_size) cont += 1 except Exception: self.log_exception("Error creating or attaching the volume to the instance")
Example #3
Source File: add_portgroup_to_vswitch.py From pyvmomi-community-samples with Apache License 2.0 | 7 votes |
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 #4
Source File: vcenter_addvmk.py From ansible-module-chaperone with Apache License 2.0 | 6 votes |
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 #5
Source File: service_manager.py From vsphere-automation-sdk-python with MIT License | 6 votes |
def connect(self): # Connect to vAPI Endpoint on vCenter Server system self.stub_config = vapiconnect.connect(host=self.server_url, user=self.username, pwd=self.password, skip_verification=self.skip_verification) # Connect to VIM API Endpoint on vCenter Server system context = None if self.skip_verification: context = get_unverified_context() self.si = SmartConnect(host=self.server_url, user=self.username, pwd=self.password, sslContext=context) assert self.si is not None # Retrieve the service content self.content = self.si.RetrieveContent() assert self.content is not None self.vim_uuid = self.content.about.instanceUuid
Example #6
Source File: utils_pyvmomi.py From avocado-vt with GNU General Public License v2.0 | 6 votes |
def connect(self): """ Initialize the service instance to the VSphere server """ # Check if an valid connection has already been establised. # If yes, just refresh the connection to keep it alive. # If not, close the old connection and establise a new one. if self.is_conn_dead(): self.close() else: self.keep_alive() return kwargs = self.kwargs if self.insecure: self.service_instance = SmartConnectNoSSL(**kwargs) else: self.service_instance = SmartConnect(**kwargs) if self.service_instance: logging.debug( 'New vsphere connection established: %s (%s)', self.service_instance, id(self.service_instance))
Example #7
Source File: parallel.py From vsphere-automation-sdk-python with MIT License | 6 votes |
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 #8
Source File: change_disk_mode.py From pyvmomi-community-samples with Apache License 2.0 | 6 votes |
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 #9
Source File: getvnicinfo.py From pyvmomi-community-samples with Apache License 2.0 | 6 votes |
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 #10
Source File: __init__.py From kcli with Apache License 2.0 | 6 votes |
def __init__(self, host, user, password, datacenter, cluster, debug=False, filtervms=False, filteruser=False, filtertag=None): # 4-1-CONNECT si = connect.SmartConnect(host=host, port=443, user=user, pwd=password, sslContext=_create_unverified_context()) self.conn = si self.si = si self.vcip = host self.url = "https://%s:%s@%s/sdk" % (user, password, host) self.rootFolder = si.content.rootFolder self.dc = find(si, self.rootFolder, vim.Datacenter, datacenter) self.macaddr = [] self.clu = cluster self.distributed = False self.filtervms = filtervms self.filtervms = filtervms self.filteruser = filteruser self.filtertag = filtertag self.debug = debug return
Example #11
Source File: PyvmomiClient.py From katprep with GNU General Public License v3.0 | 6 votes |
def __connect(self): """This function establishes a connection to the hypervisor.""" global SESSION context = None #skip SSL verification for now if hasattr(ssl, '_create_unverified_context'): context = ssl._create_unverified_context() #try to connect try: self.SESSION = SmartConnect( host=self.HOSTNAME, user=self.USERNAME, pwd=self.PASSWORD, port=self.PORT, sslContext=context ) except vim.fault.InvalidLogin: raise InvalidCredentialsException("Invalid credentials")
Example #12
Source File: vmware_exporter.py From vmware_exporter with BSD 3-Clause "New" or "Revised" License | 6 votes |
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 #13
Source File: change_vm_cd_backend.py From pyvmomi-community-samples with Apache License 2.0 | 6 votes |
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 #14
Source File: waitforupdates.py From pyvmomi-community-samples with Apache License 2.0 | 5 votes |
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 #15
Source File: del_vswitch_from_host.py From pyvmomi-community-samples with Apache License 2.0 | 5 votes |
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) DelHostsSwitch(hosts, args.vswitch) # Main section
Example #16
Source File: del_portgroup_from_vswitch.py From pyvmomi-community-samples with Apache License 2.0 | 5 votes |
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 #17
Source File: hello_world_vcenter_with_yaml_recorder.py From pyvmomi-community-samples with Apache License 2.0 | 5 votes |
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 #18
Source File: hello_world_vcenter.py From pyvmomi-community-samples with Apache License 2.0 | 5 votes |
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 #19
Source File: vSphereAutoRestartManager.py From pyvmomi-community-samples with Apache License 2.0 | 5 votes |
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 #20
Source File: add_raw_disk_to_vm.py From pyvmomi-community-samples with Apache License 2.0 | 5 votes |
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 #21
Source File: vSphere.py From im with GNU General Public License v3.0 | 5 votes |
def get_connection(self, auth_data): """ Get the vSphere connection object from the auth data Arguments: - auth(Authentication): parsed authentication tokens. Returns: a :py:class:`vim.connect.SmartConnect` or None in case of error """ if self.connection: return self.connection else: auth = auth_data.getAuthInfo(self.type) if auth and 'username' in auth[0] and 'password' in auth[0]: connection = SmartConnect(host=self.cloud.server, user=auth[0]['username'], pwd=auth[0]['password'], port=self.cloud.port) self.connection = connection return connection else: self.log_error("No correct auth data has been specified to vSpere: username, password") self.log_debug(auth) raise Exception("No correct auth data has been specified to vSpere: username, password")
Example #22
Source File: create_folder_in_datacenter.py From pyvmomi-community-samples with Apache License 2.0 | 5 votes |
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 #23
Source File: delete_nic_from_vm.py From pyvmomi-community-samples with Apache License 2.0 | 5 votes |
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 #24
Source File: reconfigure_host_for_ha.py From pyvmomi-community-samples with Apache License 2.0 | 5 votes |
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 #25
Source File: get_vcenter_id.py From ansible-module-chaperone with Apache License 2.0 | 5 votes |
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 #26
Source File: get_portgroup.py From pyvmomi-community-samples with Apache License 2.0 | 5 votes |
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 #27
Source File: interactive_wrapper.py From pyvmomi-community-samples with Apache License 2.0 | 5 votes |
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 #28
Source File: vcenter_details.py From pyvmomi-community-samples with Apache License 2.0 | 5 votes |
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 #29
Source File: service_manager_esxtop_in_vc.py From pyvmomi-community-samples with Apache License 2.0 | 5 votes |
def main(): 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)) context = None if hasattr(ssl, "_create_unverified_context"): context = ssl._create_unverified_context() si = SmartConnect(host=args.host, user=args.user, pwd=password, port=int(args.port), sslContext=context) atexit.register(Disconnect, si) # "vmware.host." prefix is required when connecting to VC location = "vmware.host." + args.esxi services = si.content.serviceManager.QueryServiceList( location=[location]) if services: for service in services: if service.serviceName == "Esxtop": results = service.service.ExecuteSimpleCommand( arguments=["CounterInfo"]) print(results) else: print("Unable to retrieve the service list from \ ESXi host. Pleaes ensure --esxi property is the FQDN or IP \ Address of the managed ESXi host in your vCenter Server") # Start program
Example #30
Source File: list_datastore_cluster.py From pyvmomi-community-samples with Apache License 2.0 | 5 votes |
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