def _GetVsanStub(stub, endpoint=VSAN_API_VC_SERVICE_ENDPOINT, context=None, version='vim.version.version10'): hostname = stub.host.split(':')[0] vsanStub = SoapStubAdapter(host=hostname, path=endpoint, version=version, sslContext=context) vsanStub.cookie = stub.cookie return vsanStub
def ConnectEAM(si, vpxdStub, sslContext): hostname = vpxdStub.host.split(":")[0] eamStub = SoapStubAdapter(host=hostname, version="eam.version.version1", path="/eam/sdk", poolSize=0, sslContext=sslContext) eamStub.cookie = vpxdStub.cookie eamCx = eam.EsxAgentManager("EsxAgentManager", eamStub) return eamCx
def connectToSpbm(stub, context): hostname = stub.host.split(":")[0] sessionCookie = stub.cookie.split('"')[1] VmomiSupport.GetRequestContext()["vcSessionCookie"] = sessionCookie pbmStub = SoapStubAdapter( host=hostname, path="/pbm/sdk", version="pbm.version.version2", sslContext=context, ) pbmStub.cookie = stub.cookie pbmSi = pbm.ServiceInstance("ServiceInstance", pbmStub) return pbmSi
def processRequest(vcIp, vcUser, vcPass, clusterName, goal, startTime, endTime): """ Process the user request with provided credentials """ (si, content) = connectToVimEndpoint(vcIp, vcUser, vcPass) cluster = getClusterInstance(clusterName, si) vhStub = SoapStubAdapter(host=vcIp, version="vsan.version.version7", path="/vsanHealth", poolSize=0) vhStub.cookie = si._stub.cookie vpm = vim.cluster.VsanPerformanceManager('vsan-performance-manager', vhStub) #list of possible diagnostic exceptions exceptionDict = getDiagnosticExceptions(vpm) f = open('result.txt', 'w') if startTime is None: # In this case query for the last hour endTime = datetime.datetime.utcnow() startTime = endTime - datetime.timedelta(0, 3600) diagQueryType = vim.cluster.VsanPerfDiagnosticQueryType(goal) diagQuery = vim.cluster.VsanPerfDiagnoseQuerySpec(startTime=startTime, endTime=endTime, queryType=diagQueryType) print("Starting diagnosis. Will append results in result.txt") beginTime = time.time() try: task = vpm.VsanPerfDiagnoseTask(diagQuery, cluster) vcTask = convertVsanTaskToVcTask(task, si._stub) WaitForTask(vcTask) time.sleep(1) transactionId = vcTask.info.result result = vpm.GetVsanPerfDiagnosisResult(vcTask, cluster) resultList = processResult(exceptionDict, result) for item in resultList: f.write("Issue: %s\nDetails: %s\nURL: %s\nResult: %s\n" % (item[0][0], item[0][1], item[0][2], item[1])) duration = time.time() - beginTime print("Time to run performance diagnostics query is %d seconds. Result" " in result.txt" % duration) except vim.fault.NotFound as ex: logging.error(ex) f.close()
def _GetVsanStub(stub, endpoint=VSAN_API_VC_SERVICE_ENDPOINT, context=None, version='vim.version.version11'): index = stub.host.rfind(':') if valid_ipv6(stub.host[:index][1:-1]): hostname = stub.host[:index][1:-1] else: hostname = stub.host[:index] vsanStub = SoapStubAdapter(host=hostname, path=endpoint, version=version, sslContext=context) vsanStub.cookie = stub.cookie return vsanStub
def check_for_template(server, user, password, name, \ template): """ check if given template exists @params server: vc server @params user: username of the vc @params password: password to login to vc @params name: Name of the datacenter @params template: name of the template @return True if template exists """ stub = SoapStubAdapter(host=server, port=443, path="/sdk", \ version="vim.version.version7") serviceInstance = Vim.ServiceInstance("ServiceInstance", stub) content = serviceInstance.RetrieveContent() content.sessionManager.Login(user, password) datacenters = content.rootFolder.childEntity for datacenter in datacenters: if datacenter.name == name: vmFolder = datacenter.vmFolder.childEntity for folder in vmFolder: if folder.name == "nimbus": templates = folder.childEntity for vm in templates: if vm.name == template: return True return None
def pbm_connect(stub_adapter, disable_ssl_verification=False): """Connect to the VMware Storage Policy Server :param stub_adapter: The ServiceInstance stub adapter :type stub_adapter: SoapStubAdapter :param disable_ssl_verification: A flag used to skip ssl certificate verification (default is False) :type disable_ssl_verification: bool :returns: A VMware Storage Policy Service content object :rtype: ServiceContent """ if disable_ssl_verification: import ssl if hasattr(ssl, '_create_unverified_context'): ssl_context = ssl._create_unverified_context() else: ssl_context = None else: ssl_context = None VmomiSupport.GetRequestContext()["vcSessionCookie"] = \ stub_adapter.cookie.split('"')[1] hostname = stub_adapter.host.split(":")[0] pbm_stub = SoapStubAdapter(host=hostname, version="pbm.version.version1", path="/pbm/sdk", poolSize=0, sslContext=ssl_context) pbm_si = pbm.ServiceInstance("ServiceInstance", pbm_stub) pbm_content = pbm_si.RetrieveContent() return pbm_content
def test_simple_request_serializer(self): def request_matcher(r1, r2): soap_msg = ('<soapenv:Body>' '<RetrieveServiceContent xmlns="urn:vim25">' '<_this type="ServiceInstance">' 'ServiceInstance' '</_this>' '</RetrieveServiceContent>' '</soapenv:Body>') if soap_msg in r1.body: return True raise SystemError('serialization error occurred') my_vcr = vcr.VCR() my_vcr.register_matcher('request_matcher', request_matcher) with my_vcr.use_cassette( 'test_simple_request_serializer.yaml', cassette_library_dir=tests.fixtures_path, record_mode='none', match_on=['request_matcher']) as cass: host = 'vcsa' port = 443 stub = SoapStubAdapter(host, port) si = vim.ServiceInstance("ServiceInstance", stub) content = si.RetrieveContent() self.assertTrue(content is not None) self.assertTrue( '<_this type="ServiceInstance">ServiceInstance</_this>' in cass.requests[0].body)
def main(_args): # logging.basicConfig(level=logging.DEBUG) rc = os.fork() if rc == 0: serialKiller() else: try: # Create the communication stub. soapStub = SoapStubAdapter(host="127.0.0.1", port=-PORT, version="vim.version.version9") # Create a stub to check that the wrapper is not silently eating # login-related any exceptions. badSessionStub = VimSessionOrientedStub( soapStub, VimSessionOrientedStub.makeUserLoginMethod( "Mallory", "vmware"), retryDelay=0.1, retryCount=100000) try: si = Vim.ServiceInstance("ServiceInstance", badSessionStub) print(si.content.sessionManager) assert False, "able to login as Mallory?" except Vim.fault.InvalidLogin: # XXX Is it wrong, perhaps even immoral, for a non-Login method # to raise an InvalidLogin exception? pass # Create a session stub that should work correctly. We set the # retryCount really high so that no method calls should ever fail. sessionStub = VimSessionOrientedStub( soapStub, VimSessionOrientedStub.makeUserLoginMethod("alice", "vmware"), retryDelay=0.05, retryCount=1000) si = Vim.ServiceInstance("ServiceInstance", sessionStub) # Sit in a loop and do RPCs. while True: try: print(si.content.sessionManager.sessionList) try: # Make sure regular method calls can throw exceptions # through the wrapper. si.content.rootFolder.CreateFolder("Test") assert False, "duplicate name fault wasn't thrown?" except Vim.fault.DuplicateName: pass except (socket.error, httplib.HTTPException): logging.exception("cannot get sessionList") time.sleep(0.1) except KeyboardInterrupt: logging.info("got interrupt") except: logging.exception("goodbye!") finally: os.kill(0, signal.SIGTERM)
def CreateHbrsrvSoapStub(host, port=DEFAULT_VMODL_PORT, version=HBR_CURRENT_VMODL_VERSION, username=None, password=None, keyFile=None, certFile=None, reliableCnx=False): soapStub = SoapStubAdapter(host=host, port=port, version=version, path='/', certFile=certFile, certKeyFile=keyFile, sslContext=ssl._create_unverified_context()) if not reliableCnx: return soapStub if keyFile is not None and certFile is not None: loginMethod = HbrsrvSessionOrientedStub.MakeThumbprintLoginMethod() logger.debug('Creating a new SOAP stub using thumbprint authentication') elif username is not None and password is not None: loginMethod = HbrsrvSessionOrientedStub.MakeUserPasswordLoginMethod(username, password) logger.debug('Creating a new SOAP stub using user/password authentication') else: raise pyHbr.exceptions.ConnectionError('Missing credentials.') soapStub = HbrsrvSessionOrientedStub(soapStub, loginMethod, retryDelay=0.1, retryCount=4) return soapStub
def get_esx_host_content(esx_ip, esx_user, esx_password): """ function to get content object of given esx host @param esx_ip: IP of esx on which vm is running @param esx_user: User of esx on which vm is running @param esx_password: Password of esx on which vm is running @return esx host content object """ log = logging.getLogger('vdnet') if esx_user is None: log.info("Using default username 'root' for esx") esx_user = '******' if esx_password is None: log.info("Using default password 'ca$hc0w' for esx") esx_password = '******' stub = SoapStubAdapter(host=esx_ip, port=443, path="/sdk", version="vim.version.version7") service_instance = Vim.ServiceInstance("ServiceInstance", stub) if not service_instance: log.info("serviceInstance not defined for esx %s" % esx_ip) content = service_instance.RetrieveContent() if not content: log.info("content not defined for esx %s" % esx_ip) content.sessionManager.Login(esx_user, esx_password) return content
def SmartStubAdapter(host='localhost', port=443, path='/sdk', url=None, sock=None, poolSize=5, certFile=None, certKeyFile=None, httpProxyHost=None, httpProxyPort=80, sslProxyPath=None, thumbprint=None, cacertsFile=None, preferredApiVersions=None, acceptCompressedResponses=True, connectionPoolTimeout=CONNECTION_POOL_IDLE_TIMEOUT_SEC, samlToken=None, sslContext=None): """ Determine the most preferred API version supported by the specified server, then create a soap stub adapter using that version The parameters are the same as for pyVmomi.SoapStubAdapter except for version which is renamed to prefferedApiVersions @param preferredApiVersions: Acceptable API version(s) (e.g. vim.version.version3) If a list of versions is specified the versions should be ordered from most to least preferred. If None is specified, the list of versions support by pyVmomi will be used. @type preferredApiVersions: string or string list """ if preferredApiVersions is None: preferredApiVersions = GetServiceVersions('vim25') supportedVersion = __FindSupportedVersion('https' if port > 0 else 'http', host, port, path, preferredApiVersions, sslContext) if supportedVersion is None: raise Exception("%s:%s is not a VIM server" % (host, port)) return SoapStubAdapter(host=host, port=port, path=path, url=url, sock=sock, poolSize=poolSize, certFile=certFile, certKeyFile=certKeyFile, httpProxyHost=httpProxyHost, httpProxyPort=httpProxyPort, sslProxyPath=sslProxyPath, thumbprint=thumbprint, cacertsFile=cacertsFile, version=supportedVersion, acceptCompressedResponses=acceptCompressedResponses, connectionPoolTimeout=connectionPoolTimeout, samlToken=samlToken, sslContext=sslContext)
def ConnectToHost(hostRef): hostname = hostRef.name stub = SoapStubAdapter(host=hostname, path='/vsan', version='vim.version.version9', sslContext=ssl._create_unverified_context()) token = hostRef.configManager.vsanSystem.FetchVsanSharedSecret() return VimSessionOrientedStub(stub, _makeHostLoginMethod(hostname, token))
def __RetrieveContent(host, port, adapter, version, path, keyFile, certFile, thumbprint, sslContext, connectionPoolTimeout=CONNECTION_POOL_IDLE_TIMEOUT_SEC): """ Retrieve service instance for connection. @param host: Which host to connect to. @type host: string @param port: Port @type port: int @param adapter: Adapter @type adapter: string @param version: Version @type version: string @param path: Path @type path: string @param keyFile: ssl key file path @type keyFile: string @param certFile: ssl cert file path @type certFile: string @param connectionPoolTimeout: Timeout in secs for idle connections to close, specify negative numbers for never closing the connections @type connectionPoolTimeout: int """ # XXX remove the adapter and service arguments once dependent code is fixed if adapter != "SOAP": raise ValueError(adapter) # Create the SOAP stub adapter stub = SoapStubAdapter(host, port, version=version, path=path, certKeyFile=keyFile, certFile=certFile, thumbprint=thumbprint, sslContext=sslContext, connectionPoolTimeout=connectionPoolTimeout) # Get Service instance si = vim.ServiceInstance("ServiceInstance", stub) content = None try: content = si.RetrieveContent() except vmodl.MethodFault: raise except ParserError: raise except Exception as e: # NOTE (hartsock): preserve the traceback for diagnostics # pulling and preserving the traceback makes diagnosing connection # failures easier since the fault will also include where inside the # library the fault occurred. Without the traceback we have no idea # why the connection failed beyond the message string. (type, value, traceback) = sys.exc_info() if traceback: fault = vim.fault.HostConnectFault(msg=str(e)) reraise(vim.fault.HostConnectFault, fault, traceback) else: raise vim.fault.HostConnectFault(msg=str(e)) return content, si, stub
def create(args): ''' create vmfs volumes on an esx host ''' ipaddr = args['ipaddr'] user = args['username'] password = args['password'] free_luns = args['free_luns'] diskpattern = args['diskpattern'] prefix = args['prefix'] stub = SoapStubAdapter(host=ipaddr, port=443, path="/sdk", version="vim.version.version7") serviceInstance = Vim.ServiceInstance("ServiceInstance", stub) content = serviceInstance.RetrieveContent() content.sessionManager.Login(user, password) if serviceInstance: hostsystem = _hostsystem(serviceInstance) hostsystem.configManager.storageSystem.RescanVmfs() datastoreSystem = hostsystem.configManager.datastoreSystem uuids_before = [ x.info.vmfs.uuid for x in datastoreSystem.datastore if hasattr(x.info, 'vmfs') ] available_disks = [ x.devicePath for x in datastoreSystem.QueryAvailableDisksForVmfs() if not x.ssd ] available_disks = [ x for x in available_disks if re.compile(diskpattern).search(x) ] specs = [] for disk in available_disks: specs += datastoreSystem.QueryVmfsDatastoreCreateOptions(disk, 5) uuids_created = [] label_index = 0 for spec in specs: if len(uuids_created) >= len(specs) - free_luns: break while True: label_index = label_index + 1 spec.spec.vmfs.volumeName = "%s%d" % (prefix, label_index) try: datastore = datastoreSystem.CreateVmfsDatastore(spec.spec) uuids_created += [datastore.info.vmfs.uuid] except Vim.Fault.DuplicateName, ex: # duplicate name, pick another continue except Vim.Fault.PlatformConfigFault, ex: # weird python error; does not happen with rbvmomi LOGGER.debug(str(ex)) break
def connect_ticket(self, host, ticket): if ticket: try: stub = SoapStubAdapter(host, HOSTD_PORT, VIM_NAMESPACE) si = vim.ServiceInstance("ServiceInstance", stub) si.RetrieveContent().sessionManager.CloneSession(ticket) return si except httplib.HTTPException as http_exception: self._logger.info("Failed to login hostd with ticket: %s" % http_exception) raise AcquireCredentialsException(http_exception)
def get_pbm_connection(self, vpxd_stub): VmomiSupport.GetRequestContext()["vcSessionCookie"] = \ vpxd_stub.cookie.split('"')[1] hostname = vpxd_stub.host.split(":")[0] pbm_stub = SoapStubAdapter( host=hostname, version="pbm.version.version11", path="/pbm/sdk", poolSize=0, sslContext=ssl._create_unverified_context()) pbm_si = pbm.ServiceInstance("ServiceInstance", pbm_stub) pbm_content = pbm_si.RetrieveContent() return pbm_content
def get_service_instance(self): # create a connection to hostd. request = ServiceTicketRequest(ServiceType.VIM) response = self.host_client.get_service_ticket(request) self.assertEqual(response.result, ServiceTicketResultCode.OK) hostd_port = 443 vim_namespace = "vim25/5.0" stub = SoapStubAdapter(self.server, hostd_port, vim_namespace) si = vim.ServiceInstance("ServiceInstance", stub) si.RetrieveContent().sessionManager.CloneSession(response.vim_ticket) connect.SetSi(si) return si
def connectToVimEndpoint(host, username, password, version='vim.version.version6'): """ Get a service instance """ context = None ssl._create_default_https_context = ssl._create_unverified_context stub = SoapStubAdapter(host=host, path="/sdk", poolSize=0, version=version) si = vim.ServiceInstance('ServiceInstance', stub) content = si.content logging.info(str([username, password])) content.sessionManager.Login(userName=username, password=password) return si, content
def IsVCWindows(vcHost, log, vcHttpsPort=443): '''Check if the VC Platform is Windows.''' from pyVmomi import Vim, SoapStubAdapter, SoapAdapter try: soapStub = SoapStubAdapter(vcHost, port=vcHttpsPort) vcSi = Vim.ServiceInstance("ServiceInstance", soapStub) siContent = vcSi.RetrieveContent() osType = siContent.about.osType return bool(re.match('^win', osType.lower())) except AttributeError: log.info("Unable to get the VC platform for VC host %s" % vcHost) raise except Exception as e: log.info("Unable to connect to VC host %s : %s" % (vcHost, str(e))) raise
def __Login(host, port, user, pwd, service, adapter, version, path, keyFile, certFile): """ Private method that performs the actual Connect and returns a connected service instance object. @param host: Which host to connect to. @type host: string @param port: Port @type port: int @param user: User @type user: string @param pwd: Password @type pwd: string @param service: Service @type service: string @param adapter: Adapter @type adapter: string @param version: Version @type version: string @param path: Path @type path: string @param keyFile: ssl key file path @type keyFile: string @param certFile: ssl cert file path @type certFile: string """ # XXX remove the adapter and service arguments once dependent code is fixed if adapter != "SOAP": raise ValueError(adapter) # Create the SOAP stub adapter stub = SoapStubAdapter(host, port, version=version, path=path, certKeyFile=keyFile, certFile=certFile) # Get Service instance si = vim.ServiceInstance("ServiceInstance", stub) try: content = si.RetrieveContent() except vmodl.MethodFault: raise except Exception, e: raise vim.fault.HostConnectFault(msg=str(e))
def GetStorageManager(vcHost): smsStub = None vpxdStub = connect.GetStub() sessionCookie = vpxdStub.cookie.split('"')[1] httpContext = VmomiSupport.GetHttpContext() cookie = Cookie.SimpleCookie() cookie["vmware_soap_session"] = sessionCookie httpContext["cookies"] = cookie VmomiSupport.GetRequestContext()["vcSessionCookie"] = sessionCookie smsStub = SoapStubAdapter(host=vcHost, ns = "sms/4.0", path = "/sms/sdk", poolSize=0) si = Sms.ServiceInstance("ServiceInstance", smsStub) return si.QueryStorageManager()
def connect(host, port, user, pwd, adapter="SOAP"): if adapter == None: adapter = "SOAP" if host == None: host = "localhost" if port == None: port = 443 if user == None: user = os.getlogin() print "Connecting to :", host, "at", port, "as", user, "over", adapter # Create the VMDB stub adapter stub = SoapStubAdapter(host, port) # Get Service instance si = Vim.ServiceInstance("ServiceInstance", stub) content = si.RetrieveContent() sessionManager = content.GetSessionManager() # Login locally if pwd == None: localTicket = sessionManager.AcquireLocalTicket(user) user = localTicket.GetUserName() passwordFile = localTicket.GetPasswordFilePath() try: fd = open(passwordFile, "r") pwd = fd.readline() fd.close() except Exception: msg = "Failed to read password file. A password is required to " + \ "connect remotely." raise Exception(msg) # Login try: x = sessionManager.Login(user, pwd, None); except Vim.Fault.InvalidLogin: print "Invalid login:"******"Failed to login as ", user sys.exit() return si
def __Login(self): print("INFO: connecting to hostd using '%s'" % (self._protocol)) self._cnx = SoapStubAdapter(self._host, self._port, self._namespace) self._si = Vim.ServiceInstance("ServiceInstance", self._cnx) self._content = self._si.RetrieveContent() self._pc = self._content.GetPropertyCollector() self._sm = self._content.GetSessionManager() self._us = self._sm.Login(self._user, self._pswd, None) # report if anyone else is logged in sessionList = self._sm.GetSessionList() if (len(sessionList) > 1): self._MsgUpdated = True self._sm.UpdateMessage( "Integration Tests are running on this system") print("WARNING: more than one operator online during test run") for item in sessionList: print("%s login: %s last active: %s" % \ (item.GetFullName(), item.GetLoginTime(), item.GetLastActiveTime()))
def main(): ssl._create_default_https_context = ssl._create_unverified_context supportedArgs = [(["s:", "server="], "localhost", "Host name", "server")] supportedToggles = [(["usage", "help"], False, "Show usage information", "usage")] args = arguments.Arguments(sys.argv, supportedArgs, supportedToggles) if args.GetKeyValue("usage") == True: args.Usage() sys.exit(0) try: host = args.GetKeyValue("server") stub = SoapStubAdapter(host, 443, "vim25/2.5", "/sdk") si = Vim.ServiceInstance("ServiceInstance", stub) sc = si.RetrieveContent() print sc.about.build except Exception, e: print e sys.exit(1)
def get_vc_content(options): """ function to get content object of given vc @param options cli options to this script @return vc content object """ vc_ip = options.vc vc_user = options.vc_user vc_password = options.vc_password stub = SoapStubAdapter(host=vc_ip, port=443, path="/sdk", version="vim.version.version7") service_instance = Vim.ServiceInstance("ServiceInstance", stub) if not service_instance: print("serviceInstance not defined") ssl._create_default_https_context = ssl._create_unverified_context content = service_instance.RetrieveContent() if not content: print("content not defined") content.sessionManager.Login(vc_user, vc_password) return content
def test1_Login2HostdOverSOAPandSSL(self): """ Verify protocol login to hostd over vmdb over ssl over tcp. """ self._cnx = SoapStubAdapter(self._host, self._port, ns=self._ver) si = Vim.ServiceInstance("ServiceInstance", self._cnx) self.failUnless(isinstance(si, Vim.ServiceInstance), "expected Vim.ServiceInstance, got %s" % \ si.__class__.__name__) content = si.RetrieveContent() self.failUnless(isinstance(content, Vim.ServiceInstanceContent), "expected Vim.ServiceInstanceContent, got %s" % \ content.__class__.__name__) sm = content.GetSessionManager() self.failUnless(isinstance(sm, Vim.SessionManager), "expected Vim.SessionManager, got %s" % \ sm.__class__.__name__) us = sm.Login(self._user.encode('utf8'), self._pswd.encode('utf8'), None) result = isinstance(us, Vim.UserSession) self.failUnless(result, "expected Vim.UserSesion, got %s" % \ us.__class__.__name__)
def _service_instance(self): stub = SoapStubAdapter("localhost", HOSTD_PORT) return vim.ServiceInstance("ServiceInstance", stub)
from pyVmomi import Vim, SoapStubAdapter from pyVim import arguments from pyVim import folder, vm from pyVim.helpers import Log supportedArgs = [(["t:", "ticket="], "", "ticket", "ticket")] supportedToggles = [(["usage", "help"], False, "usage information", "usage")] args = arguments.Arguments(sys.argv, supportedArgs, supportedToggles) if args.GetKeyValue("usage") == True: args.Usage() sys.exit(0) ticket = args.GetKeyValue("ticket") host = 'localhost' stub = SoapStubAdapter(host=host, version="vim.version.version10") newsi = Vim.ServiceInstance("ServiceInstance", stub) # Try to acquire a clone ticket on a un-authenticated session. Should fail. try: newsi.GetContent().GetSessionManager().AcquireCloneTicket() except: pass newsm = newsi.GetContent().GetSessionManager().CloneSession(ticket) for vm1 in folder.GetVmAll(si=newsi): print vm1 try: Log("Power Off (should pass)") vm1.PowerOff()
def __Login(host, port, user, pwd, service, adapter, version, path, keyFile, certFile, sslContext): """ Private method that performs the actual Connect and returns a connected service instance object. @param host: Which host to connect to. @type host: string @param port: Port @type port: int @param user: User @type user: string @param pwd: Password @type pwd: string @param service: Service @type service: string @param adapter: Adapter @type adapter: string @param version: Version @type version: string @param path: Path @type path: string @param keyFile: ssl key file path @type keyFile: string @param certFile: ssl cert file path @type certFile: string @param sslContext: SSL Context describing the various SSL options. It is only supported in Python 2.7.9 or higher. @type sslContext: SSL.Context """ # XXX remove the adapter and service arguments once dependent code is fixed if adapter != "SOAP": raise ValueError(adapter) # Create the SOAP stub adapter stub = SoapStubAdapter(host, port, version=version, path=path, certKeyFile=keyFile, certFile=certFile, sslContext=sslContext) # Get Service instance si = vim.ServiceInstance("ServiceInstance", stub) try: content = si.RetrieveContent() except vmodl.MethodFault: raise except Exception as e: # NOTE (hartsock): preserve the traceback for diagnostics # pulling and preserving the traceback makes diagnosing connection # failures easier since the fault will also include where inside the # library the fault occurred. Without the traceback we have no idea # why the connection failed beyond the message string. (type, value, traceback) = sys.exc_info() if traceback: fault = vim.fault.HostConnectFault(msg=str(e)) reraise(vim.fault.HostConnectFault, fault, traceback) else: raise vim.fault.HostConnectFault(msg=str(e)) # Get a ticket if we're connecting to localhost and password is not specified if host == 'localhost' and not pwd: try: (user, pwd) = GetLocalTicket(si, user) except: pass # This is not supported against vCenter, and connecting # with an empty password is fine in debug builds # Login try: x = content.sessionManager.Login(user, pwd, None) except vim.fault.InvalidLogin: raise except Exception as e: raise return si, stub