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
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 __init__(self, hostname: str, username: str, password: str, datacenter: str = None, cluster: str = None, port: int = 443): """ Create a VcCluster instance """ # Instance variables self.hostname = hostname self.username = username self.password = password self.port = port # Instance parameters self.ssl_context = unverified_ssl_context() self.timeout = 0 try: # Connect using a session oriented connection # Ref. https://github.com/vmware/pyvmomi/issues/347 self.si = None credentials = VimSessionOrientedStub.makeUserLoginMethod(self.username, self.password) smart_stub = SmartStubAdapter(host=self.hostname, port=self.port, sslContext=self.ssl_context, connectionPoolTimeout=self.timeout) self.session_stub = VimSessionOrientedStub(smart_stub, credentials) self.si = vim.ServiceInstance('ServiceInstance', self.session_stub) if not self.si: msg = f'Could not connect to the specified host using the specified username and password' raise ValueError(msg) except socket.gaierror as e: msg = f'Connection: failed ({e.strerror})' raise ValueError(msg) except IOError as e: raise e except Exception as e: raise e self.host_type = self.si.content.about.apiType if self.host_type != 'VirtualCenter': raise ValueError(f'Host is not a vCenter: {self.host_type}') self.api_version = self.si.content.about.apiVersion if int(self.api_version.split('.')[0]) < 6: raise RuntimeError(f'API version less than 6.0.0 is not supported: {self.api_version}') # Get objects self.datacenter = self.__get_datacenter(name=datacenter) self.cluster = self.__get_cluster(name=cluster) self.hosts = self.get_cluster_hosts()
def ConnectToVC(vchost, vcport, vcuser, vcpassword): si = SmartConnectNoSSL(host=vchost, user=vcuser, pwd=vcpassword, port=vcport) stub = VimSessionOrientedStub( si._stub, VimSessionOrientedStub.makeUserLoginMethod(vcuser, vcpassword)) si = vim.ServiceInstance("ServiceInstance", stub) atexit.register(Disconnect, si) return si
def CreateHostdSoapStub(host, username, password): stub = pyVim.connect.SmartStubAdapter(host=host, preferredApiVersions=HBR_VIM_VERSIONS, sslContext=ssl._create_unverified_context()) # Create a hostd connection using the more robust SessionOrientedStub loginMethod = VimSessionOrientedStub.makeUserLoginMethod(username, password) return VimSessionOrientedStub(stub, loginMethod, retryDelay=0.5, retryCount=20)
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 _connect(self): print("Connecting to %s as %s" % (self._vm_host["name"], self._request["host_authentication"]["username"])) smart_stub = SmartStubAdapter( host=self._vm_host["name"], port=443, sslContext=ssl._create_unverified_context(), connectionPoolTimeout=0) self._session_stub = VimSessionOrientedStub( smart_stub, VimSessionOrientedStub.makeUserLoginMethod( self._request["host_authentication"]["username"], self._request["host_authentication"]["password"])) si = vim.ServiceInstance('ServiceInstance', self._session_stub) if not si: raise Exception("Could not connect to %s" % self._vm_host["name"]) return si
def _SmartSessionOrientedConnect(host, username, password): """Create a new session oriented stub that will automatically login when used. """ # create a smart stub that will connect using the latest known # VIM version stub = SmartStubAdapter(host, sslContext=ssl._create_unverified_context()) # login with username and password loginMethod = VimSessionOrientedStub.makeUserLoginMethod( username, password) # and make the stub session oriented sessOrientedStub = VimSessionOrientedStub(stub, loginMethod, retryDelay=0.5, retryCount=20) si = vim.ServiceInstance("ServiceInstance", sessOrientedStub) return si
def _connect(self): # https://github.com/vmware/pyvmomi/issues/347#issuecomment-297591340 smart_stub = SmartStubAdapter( host=self._request[ self._side]["authentication"]["host"]["hostname"], port=443, sslContext=ssl._create_unverified_context(), connectionPoolTimeout=0) session_stub = VimSessionOrientedStub( smart_stub, VimSessionOrientedStub.makeUserLoginMethod( self._request[ self._side]["authentication"]["host"]["username"], self._request[self._side]["authentication"]["host"] ["password"], )) conn = vim.ServiceInstance('ServiceInstance', session_stub) if not conn: raise Exception("Could not connect to vCenter") return conn