def set_network_security_policy(options): """ Function to configure security policy on the network to work in nested environment @param options cli options to this script @return None """ network = get_network_on_vc(options) name = get_network_name(options) config_spec = Vim.Dvs.DistributedVirtualPortgroup.ConfigSpec() config_info = network.GetConfig() config_spec.description = config_info.name config_spec.name = name config_spec.configVersion = config_info.configVersion true_policy = Vim.BoolPolicy() true_policy.value = True dvs_port_setting = Vim.VMwareDVSPortSetting() security_policy = Vim.DVSSecurityPolicy() security_policy.allowPromiscuous = true_policy security_policy.forgedTransmits = true_policy security_policy.macChanges = true_policy security_policy.inherited = False dvs_port_setting.securityPolicy = security_policy config_spec.defaultPortConfig = dvs_port_setting network.ReconfigureDVPortgroup_Task(config_spec)
def TestCreateDir(self): self.banner(self.TestCreateDir) VerboseLog(logTrivia, self._host) scId = self._sc spec = Vim.Host.DatastoreSystem.VvolDatastoreSpec() spec.SetScId(scId) spec.SetName("vvol-test-ds:%s" % random.randint(1,1000)) ret=True try: vvolds = self.CreateDs(spec) session = vimsupport.CreateSession(self._host.GetName(), 443, 'root', '', newestVersions.GetNamespace('vim')) stub = session.GetStub() si = Vim.ServiceInstance('ServiceInstance', stub) isc = si.RetrieveContent() dnm = isc.GetDatastoreNamespaceManager() ds = Vim.Datastore(scId, stub) stableName = dnm.CreateDirectory(ds, ".vSphere-HA") browser = ds.GetBrowser() path = "[" + ds.GetName() + "].vSphere-HA" task = browser.Search(path, None) session.WaitForTask(task) VerboseLog(logVerbose, task.GetInfo()) dnm.DeleteDirectory(stableName) self.removeDs(vvolds) except: VerboseLog(logInfo, traceback.format_exc()) ret=False VerboseLog(logInfo, "passed" if ret else "failed");
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 TestDataObjectAny(): capability = Vim.Capability() capability.SetProvisioningSupported(True) capability.SetMultiHostSupported(True) dynamicProperty = Vim.DynamicProperty() dynamicProperty.SetName("data object name") dynamicProperty.SetVal(capability) print(dynamicProperty)
def configure_vm_reservation(options, vm_name, cpu_reservation=None, memory_reservation=None, mhz_per_core=None): """ Routine to run configure VMs reservations for cpu and memory when given in percents of total allocated @type vm_name: string @param vm_name: name of the VM @type cpu_reservation: int @param cpu_reservation: percent of the CPU to be reserved per allocated @type memory_reservation: int @param memory_reservation: percent of the memory to be reserved per allocated @type mhz_per_core: int @param mhz_per_core: MHz per core as exposed to VM @raise ValueError: if vm is not found @raise Exception: if updating of cpu/memory reservation errors """ log = logging.getLogger('vdnet') vm = nsx_network.get_vm_by_name(options, vm_name) if vm is not None: resource_spec = Vim.ResourceConfigSpec() resource_spec.entity = vm if cpu_reservation is not None: if mhz_per_core is None: mhz_per_core = 1000 # BUG: 1420892 Assuming each core is 1GHz cpu_reservation = int((vm.config.hardware.numCPU * mhz_per_core * int(cpu_reservation)) / 100) resource_spec.cpuAllocation = Vim.ResourceAllocationInfo() resource_spec.cpuAllocation.reservation = cpu_reservation if memory_reservation is not None: memory_reservation = int( (vm.config.hardware.memoryMB * int(memory_reservation)) / 100) resource_spec.memoryAllocation = Vim.ResourceAllocationInfo() resource_spec.memoryAllocation.reservation = memory_reservation if ((cpu_reservation is not None or memory_reservation is not None)): vc_vm_pool = vm.resourcePool try: vc_vm_pool.UpdateChildResourceConfiguration([resource_spec]) except Exception: log.exception( "Failed to update cpu/memory resources for vm %r" % vm_name) raise new_cpu_res = vm.resourceConfig.cpuAllocation.reservation new_memory_res = vm.resourceConfig.memoryAllocation.reservation log.info("Updated %r with reservations: cpu=%sMHz, memory=%sMB" % (vm_name, new_cpu_res, new_memory_res)) else: raise ValueError("Failed to find vm %r for resources allocation" % vm_name)
def RetrieveContent(self): try: retval = Vim.ServiceInstanceContent( about=Vim.AboutInfo(), rootFolder=Vim.Folder("RootFolder"), sessionManager=Vim.SessionManager("SessionManager"), propertyCollector=Vmodl.query.PropertyCollector( "PropertyCollector")) return retval except: logging.exception("retrieve content") return
def CreateLinkedClone(vmRef, lcName, ssName): diskMoveType = Vim.VirtualMachineRelocateDiskMoveOptions.createNewChildDiskBacking snap = FindSnapshot(vmRef, ssName) if snap == None: raise Exception('Failed to find snapshot') profiles = [] vmPolicy = Vim.VirtualMachineDefinedProfileSpec() vmPolicy.profileId = "" vmPolicy.profileData = Vim.VirtualMachineProfileRawData( extensionKey="com.vmware.vim.sps", objectData=None) profiles.append(vmPolicy) specList = [] disks = [ d for d in vmRef.config.hardware.device if isinstance(d, Vim.VirtualDisk) ] for disk in disks: backing = None spec = Vim.VirtualMachineRelocateSpecDiskLocator( diskMoveType=diskMoveType, datastore=disk.backing.datastore, diskId=disk.key, profile=profiles, diskBackingInfo=backing, ) specList.append(spec) spec = Vim.VirtualMachineCloneSpec( location=Vim.VirtualMachineRelocateSpec( diskMoveType=diskMoveType, profile=profiles, disk=None, ), powerOn=False, template=False, config=None, snapshot=snap, ) task = vmRef.CloneVM_Task(folder=vmRef.parent, name=lcName, spec=spec) result = WaitForTask(task, si=si) if result == "error": raise task.info.error else: return task.info.result
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 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 TestRPImportVApp(self, expectedException): # print("RP ImportVApp") """ Real value is not really important here """ spec = Vim.ImportSpec() self.assertRaises(None, self.testRP.ImportVApp, spec)
def remove_virtualcdrom_with_iso(iso_file_name=None, target_vm=None): ''' remove a VirtualCdrom device with the specified iso media file name :param file_name: :param target_vm: ''' logger.info("Looking for VirtualCdrom with iso image %s" % (iso_file_name)) the_device = None for device in target_vm.config.hardware.device: if isinstance(device, Vim.Vm.Device.VirtualCdrom): logger.info(device.deviceInfo.summary) if iso_file_name in device.deviceInfo.summary: logger.info("Found VirtualCdrom with iso image %s" % (iso_file_name)) the_device = device break if the_device is None: logger.info("Failed finding VirtualCdrom with iso image %s" % (iso_file_name)) return logger.info("Deleting VirtualCdrom with iso image %s" % (iso_file_name)) spec = Vim.VirtualDeviceConfigSpec(operation='remove', device=the_device) device_change = [] device_change.append(spec) vm_config_spec = Vim.Vm.ConfigSpec(deviceChange=device_change) task = target_vm.ReconfigVM_Task(vm_config_spec) wait_for_task(task, "RemovingVirtualCdrom") logger.info("Successfully deleted VirtualCdrom with iso image %s" % (iso_file_name)) return
def WaitForTask(task, raiseOnError=True, si=None, pc=None, onProgressUpdate=None): """ Wait for task to complete. @type raiseOnError : bool @param raiseOnError : Any exception thrown is thrown up to the caller if raiseOnError is set to true. @type si : ManagedObjectReference to a ServiceInstance. @param si : ServiceInstance to use. If None, use the information from the task. @type pc : ManagedObjectReference to a PropertyCollector. @param pc : Property collector to use. If None, get it from the ServiceInstance. @type onProgressUpdate : callable @param onProgressUpdate : Callable to call with task progress updates. For example:: def OnTaskProgressUpdate(task, percentDone): print 'Task %s is %d%% complete.' % (task, percentDone) """ if si is None: si = Vim.ServiceInstance("ServiceInstance", task._stub) if pc is None: pc = si.content.propertyCollector progressUpdater = ProgressUpdater(task, onProgressUpdate) progressUpdater.Update('created') filter = CreateFilter(pc, task) version, state = None, None # Loop looking for updates till the state moves to a completed state. while state not in (Vim.TaskInfo.State.success, Vim.TaskInfo.State.error): try: version, state = GetTaskStatus(task, version, pc) progressUpdater.UpdateIfNeeded() except Vmodl.Fault.ManagedObjectNotFound as e: print("Task object has been deleted: %s" % e.obj) break filter.Destroy() if state == "error": progressUpdater.Update('error: %s' % str(task.info.error)) if raiseOnError: raise task.info.error else: print("Task reported error: " + str(task.info.error)) else: progressUpdater.Update('completed') return state
def createResourceConfigSpec(self): spec = Vim.ResourceConfigSpec() spec.cpuAllocation = Vim.ResourceAllocationInfo() spec.cpuAllocation.shares = Vim.SharesInfo() spec.cpuAllocation.shares.level = Vim.SharesInfo.Level.normal spec.cpuAllocation.shares.shares = 4000 spec.cpuAllocation.reservation = long(0) spec.cpuAllocation.limit = long(-1) spec.cpuAllocation.expandableReservation = True spec.memoryAllocation = Vim.ResourceAllocationInfo() spec.memoryAllocation.shares = Vim.SharesInfo() spec.memoryAllocation.shares.level = Vim.SharesInfo.Level.normal spec.memoryAllocation.shares.shares = 4000 spec.memoryAllocation.reservation = long(0) spec.memoryAllocation.limit = long(-1) spec.memoryAllocation.expandableReservation = True return spec
def GenerateNetRMSpec(poolKey, shareLevel, limit, shareVal = 0): allocInfo = Vim.Dvs.NetworkResourcePool.AllocationInfo() shares = Vim.SharesInfo(level = shareLevel, shares = shareVal) allocInfo.SetLimit(limit) allocInfo.SetShares(shares) spec = Vim.Dvs.NetworkResourcePool.ConfigSpec() spec.SetKey(poolKey) spec.SetAllocationInfo(allocInfo) return spec
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 GetHints(hints): """ Get hints suitable for CLI Info """ paramHints = None if hints: if isinstance(hints, dict): paramHints = Vim.KeyValue.Array() for key, value in six.iteritems(hints): paramHints.append(Vim.KeyValue(key=key, value=value)) else: paramHints = hints return paramHints
def Login(self, userName, password, locale): '''Allow anyone but "Mallory" to login to this server.''' self.loggedIn = True if userName == "Mallory": raise Vim.fault.InvalidLogin() return Vim.UserSession(key="hi", userName=userName, fullName=userName, loginTime=datetime.datetime.now(), lastActiveTime=datetime.datetime.now(), locale="en", messageLocale="en")
def GenerateDefaultPortSetting(): """ Generates default port settings for a portgroup matching VCs defaults. """ cfg = Vim.Dvs.VmwareDistributedVirtualSwitch.VmwarePortConfigPolicy() bPolicy = Vim.BoolPolicy(inherited=False, value=False) iPolicy = Vim.IntPolicy(inherited=False, value=10) cfg.SetBlocked(bPolicy) shaping = Vim.Dvs.DistributedVirtualPort.TrafficShapingPolicy( enabled=bPolicy) shaping.SetInherited(False) cfg.SetInShapingPolicy(shaping) cfg.SetOutShapingPolicy(shaping) cfg.SetIpfixEnabled(bPolicy) security = Vim.Dvs.VmwareDistributedVirtualSwitch.SecurityPolicy( allowPromiscuous=bPolicy, forgedTransmits=bPolicy, macChanges=bPolicy) security.SetInherited(False) cfg.SetSecurityPolicy(security) numericRange = Vim.NumericRange(start=1, end=4094) vlan = Vim.Dvs.VmwareDistributedVirtualSwitch.TrunkVlanSpec() vlan.SetInherited(False) vlan.GetVlanId().append(numericRange) cfg.SetVlan(vlan) # Set failover policy bPolicy1 = Vim.BoolPolicy(inherited=False, value=True) failoverPolicy = \ Vim.Dvs.VmwareDistributedVirtualSwitch.UplinkPortTeamingPolicy() failoverPolicy.SetInherited(False) failureCriteria = Vim.Dvs.VmwareDistributedVirtualSwitch.FailureCriteria() failureCriteria.SetInherited(False) sPolicy = Vim.StringPolicy(inherited=False, value="exact") failureCriteria.SetCheckSpeed(sPolicy) failureCriteria.SetFullDuplex(bPolicy1) failureCriteria.SetCheckErrorPercent(bPolicy1) failureCriteria.SetPercentage(iPolicy) failureCriteria.SetSpeed(iPolicy) failoverPolicy.SetFailureCriteria(failureCriteria) cfg.SetUplinkTeamingPolicy(failoverPolicy) return cfg
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 add_virtualcdrom_with_iso(file_name=None, datastore=None, target_vm=None): try: vm_name = target_vm.summary.config.name logger.info( "Adding VirtualCdrom with iso image %s under datastore %s to vm %s" % (file_name, datastore, vm_name)) cdrom = Vim.Vm.Device.VirtualCdrom() dev_backing_info = Vim.Vm.Device.VirtualCdrom.IsoBackingInfo() dev_backing_info.fileName = '[{}] {}'.format(datastore, file_name) cdrom.SetBacking(dev_backing_info) connect_info = Vim.Vm.Device.VirtualDevice.ConnectInfo() connect_info.SetStartConnected(True) connect_info.SetAllowGuestControl(True) connect_info.SetConnected(True) cdrom.SetConnectable(connect_info) ctrls = [] for device in target_vm.config.hardware.device: if isinstance(device, Vim.Vm.Device.VirtualIDEController): ctrls.append(device) break if len(ctrls) == 0: logger.warn( "Failed finding VirtualIDEController to mount the virtualcdrom. Trying AHCI controller." ) for device in target_vm.config.hardware.device: if isinstance(device, Vim.Vm.Device.VirtualAHCIController): ctrls.append(device) break if len(ctrls) == 0: logger.error( "Failed finding any controller device for the virtualcdrom.") return cdrom.SetControllerKey(ctrls[0].GetKey()) conf_spec = Vim.VirtualDeviceConfigSpec(operation='add', device=cdrom) device_change = [] device_change.append(conf_spec) vm_conf_spec = Vim.Vm.ConfigSpec(deviceChange=device_change) task = target_vm.ReconfigVM_Task(vm_conf_spec) wait_for_task(task, "AddingVirtualCdrom") logger.info( "Successfully added VirtualCdrom with iso image %s under datastore %s to vm %s" % (file_name, datastore, vm_name)) except Exception as ex: logger.error(ex.message) raise return
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 runTest(numPair=1, sameVmName=False): try: failoverPair = [] vmName = ("vm-%s" % random.randint(1, 1000)) for i in range(numPair): if not sameVmName: vmName = ("vm-%s" % random.randint(1, 1000)) Log("\nCreating VM pair #%d, vm %s\n" % (i + 1, vmName)) srcMap = getObjMapping(vmName, "Source") global dstMap dstMap = getObjMapping(vmName, "Target") pair = Vim.Datastore.VVolContainerFailoverPair() pair.srcContainer = vvolId pair.tgtContainer = vvolId pair.vvolMapping = [] for key in srcMap.keys(): oneMapping = Vim.KeyValue() oneMapping.key = srcMap[key] oneMapping.value = dstMap[key] pair.vvolMapping.append(oneMapping) failoverPair.append(pair) Log("\nGenerating failoverPair = %s\n" % failoverPair) Log("\nCalling updateVVolVirtualMachineFiles\n") task = InvokeAndTrackWithTask(vvolDs.UpdateVVolVirtualMachineFiles, failoverPair) checkTaskResult(task) except Exception as e: cleanup() raise e
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__)
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() time.sleep(5)
def ServiceInstance(soapCnx): return Vim.ServiceInstance("ServiceInstance", soapCnx)
def CreateFolder(self, name): raise Vim.fault.DuplicateName(name=name, object=Vim.Folder("Original"))
def AddArgument(key, value, args): arg = Vim.KeyValue() arg.key = key arg.value = str(value) args.append(arg)