def run(self): # TODO add your sample code here # Using REST API service filter_spec = VM.FilterSpec(names=set([self.vm_name])) vms = self.client.vcenter.VM.list(filter_spec) print(vms)
def get_details(allnames, filename='serverlist.yaml', debugoutput=True): """Get the details""" import sys from com.vmware.vcenter_client import VM from com.vmware.cis.tagging_client import TagAssociation from com.vmware.vapi import std_client vsphere_client = connect_vsphere() names_chunks = chunks(allnames, 100) results = [] for names in names_chunks: names = set(names) vms = vsphere_client.vcenter.VM.list(VM.FilterSpec(names=names)) if debugoutput: sys.stdout.write('-') sys.stdout.flush() for vmserver in vms: if debugoutput: sys.stdout.write('.') sys.stdout.flush() result = {} taglist = TagAssociation(connect_cis()) taglist = taglist.list_attached_tags( std_client.DynamicID(type="VirtualMachine", id=vmserver.vm) ) name = names.pop() result[name] = {} result[name] = taglist write_dict_to_file(result, filename) results.append(result) return results
def get_vms(client, vm_names): """Return identifiers of a list of vms""" vms = client.vcenter.VM.list(VM.FilterSpec(names=vm_names)) if len(vms) == 0: print('No vm found') return None print("Found VMs '{}' ({})".format(vm_names, vms)) return vms
def get_vms(stub_config, vm_names): """Return identifiers of a list of vms""" vm_svc = VM(stub_config) vms = vm_svc.list(VM.FilterSpec(names=vm_names)) if len(vms) == 0: print('No vm found') return None print("Found VMs '{}' ({})".format(vm_names, vms)) return vms
def run(self): # TODO add your sample code here # Using REST API service vm_service = VM(self.service_manager.stub_config) filter_spec = VM.FilterSpec(names=set([self.vm_name])) vms = vm_service.list(filter_spec) print(vms) # Using Vim API service (pyVmomi) current_time = self.service_manager.si.CurrentTime() print(current_time)
def get_vm(client, vm_name): """ Return the identifier of a vm Note: The method assumes that there is only one vm with the mentioned name. """ names = set([vm_name]) vms = client.vcenter.VM.list(VM.FilterSpec(names=names)) if len(vms) == 0: print("VM with name ({}) not found".format(vm_name)) return None vm = vms[0].vm print("Found VM '{}' ({})".format(vm_name, vm)) return vm
session = requests.session() # Disable cert verification for demo purpose. # This is not recommended in a production environment. session.verify = False # Disable the secure connection warning for demo purpose. # This is not recommended in a production environment. urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) # Connect to a vCenter Server using username and password config = VsCreadential.load('.credentials.yaml') client = create_vsphere_client(server=config.hostname, username=config.username, password=config.password, session=session) rac1_vm = client.vcenter.VM.list(VM.FilterSpec(names=set(['RAC1'])))[0] rac1_vm_info = client.vcenter.VM.get(rac1_vm.vm) print(rac1_vm_info) scsi_summaries = client.vcenter.vm.hardware.adapter.Scsi.list(vm=rac1_vm.vm) for s in scsi_summaries: x = client.vcenter.vm.hardware.adapter.Scsi.get(vm=rac1_vm.vm, adapter=s.adapter) print(x) GiB = 1024 * 1024 * 1024 GiBMemory = 1024 def pp(value): """ Utility method used to print the data nicely. """ output = cStringIO() PrettyPrinter(stream=output).pprint(value)
def run(self): # Using vAPI to find VM. filter_spec = VM.FilterSpec(names=set([self.vm_name])) vms = self.client.vcenter.VM.list(filter_spec) if len(vms) != 1: raise Exception('Could not locate the required VM with name ' + self.vm_name + '. Please create the vm first.') if vms[0].power_state != 'POWERED_ON': raise Exception('VM is not powered on: ' + vms[0].power_state) vm_id = vms[0].vm # Check that vmtools svc (non-interactive user) is running. info = self.client.vcenter.vm.guest.Operations.get(vm_id) if info.guest_operations_ready is not True: raise Exception( 'VMware Tools/open-vm-tools is not running as required.') # Establish the user credentials that will be needed for all Guest Ops # APIs. creds = Credentials(interactive_session=False, user_name=self.root_user, password=self.root_passwd, type=Credentials.Type.USERNAME_PASSWORD) # Step 2 - Create a temporary directory from which to run the command # and capture any output tempDir = self.client.vcenter.vm.guest.filesystem.Directories.create_temporary( vm_id, creds, '', '', parent_path=None) # Step 3 - Create temproary files to reveive stdout and stderr # as needed. stdout = self.client.vcenter.vm.guest.filesystem.Files.create_temporary( vm_id, creds, '', '.stdout', parent_path=tempDir) stderr = self.client.vcenter.vm.guest.filesystem.Files.create_temporary( vm_id, creds, '', '.stderr', parent_path=tempDir) # Step 4 - (Optional) copy in the script to be run. # While optional, using this step to demo tranfer of a # file to a guest. scriptPath = self.client.vcenter.vm.guest.filesystem.Files.create_temporary( vm_id, creds, '', '.sh', tempDir) # Create script contents and transfer to the guest. # TODO: Need generic pick up of script content baseFN = os.path.basename(scriptPath) script = ('#! /bin/bash\n' '# ' + baseFN + '\n' '\n' 'sleep 5 # Adding a little length to the process.\n' 'ps -ef\n' 'echo\n' 'rpm -qa | sort\n' '\n') print(script) attr = self._fileAttributeCreateSpec_Linux(size=len(script), overwrite=True, permissions='0755') spec = self._create_transfer_spec(path=scriptPath, attributes=attr) toURL = self.client.vcenter.vm.guest.filesystem.Transfers.create( vm_id, creds, spec) res = self._upload(toURL, script) # Check that the uploaded file size is correct. info = self.client.vcenter.vm.guest.filesystem.Files.get( vm_id, creds, scriptPath) if info.size != len(script): raise Exception('Uploaded file size not as epected.') # Step 5 - Start the program on the guest, capturing stdout and stderr # in the separate temp files obtained earlier. options = (" > " + stdout + " 2> " + stderr) spec = self._process_create_spec(scriptPath, args=options, dir=tempDir) pid = self.client.vcenter.vm.guest.Processes.create(vm_id, creds, spec) print('process created with pid: %s\n' % pid) # Step 6 # Need a loop to wait for the process to finish to handle longer # running processes. while True: time.sleep(1.0) try: # List the single process for pid. result = self.client.vcenter.vm.guest.Processes.get( vm_id, creds, pid) if result.exit_code is not None: print('Command: ' + result.command) print('Exit code: %s\n' % result.exit_code) break if result.finished is None: print('Process with pid %s is still running.' % pid) continue except Exception as e: raise e # Step 7 Copy out the results (stdout). spec = self._create_transfer_spec(path=stdout) # create the download URL fromURL = self.client.vcenter.vm.guest.filesystem.Transfers.create( vm_id, creds, spec) body = self._download(fromURL, expectedLen=info.size) print("----------- stdout ------------------") print(body) print("---------------------------------------") # Optionally the contents of "stderr" could be downloaded. # And finally, clean up the temporary files and directories on the # Linux guest. Deleting the temporary diretory and its contents. self.client.vcenter.vm.guest.filesystem.Directories.delete( vm_id, creds, tempDir, recursive=True)
def _get_vm_filter_spec(self): vm_filter_spec = VM.FilterSpec() datacenters = self.get_option('datacenters') if datacenters: temp_dcs = [] for datacenter_name in datacenters: dc_filter_spec = Datacenter.FilterSpec( names=set([datacenter_name])) datacenter_summaries = self.pyv.rest_content.vcenter.Datacenter.list( dc_filter_spec) if len(datacenter_summaries) > 0: temp_dcs.append(datacenter_summaries[0].datacenter) else: self._handle_error(message="Unable to find datacenter %s" % datacenter_name) vm_filter_spec.datacenters = set(temp_dcs) clusters = self.get_option('clusters') if clusters: temp_clusters = [] for cluster_name in clusters: ccr_filter_spec = Cluster.FilterSpec(names=set([cluster_name])) cluster_summaries = self.pyv.rest_content.vcenter.Cluster.list( ccr_filter_spec) if len(cluster_summaries) > 0: temp_clusters.append(cluster_summaries[0].cluster) else: self._handle_error(message="Unable to find cluster %s" % cluster_name) vm_filter_spec.clusters = set(temp_clusters) folders = self.get_option('folders') if folders: temp_folders = [] for folder_name in folders: folder_filter_spec = Folder.FilterSpec( names=set([folder_name])) folder_summaries = self.pyv.rest_content.vcenter.Folder.list( folder_filter_spec) if len(folder_summaries) > 0: temp_folders.append(folder_summaries[0].folder) else: self._handle_error(message="Unable to find folder %s" % folder_name) vm_filter_spec.folders = set(temp_folders) esxi_hosts = self.get_option('esxi_hostsystems') if esxi_hosts: temp_hosts = [] for esxi_name in esxi_hosts: esxi_filter_spec = Host.FilterSpec(names=set([esxi_name])) esxi_summaries = self.pyv.rest_content.vcenter.Host.list( esxi_filter_spec) if len(esxi_summaries) > 0: temp_hosts.append(esxi_summaries[0].host) else: self._handle_error( message="Unable to find esxi hostsystem %s" % esxi_name) vm_filter_spec.folders = set(temp_hosts) resource_pools = self.get_option('resource_pools') if resource_pools: temp_rps = [] for rp_name in resource_pools: rp_filter_spec = ResourcePool.FilterSpec(names=set([rp_name])) rp_summaries = self.pyv.rest_content.vcenter.ResourcePool.list( rp_filter_spec) if len(rp_summaries) > 0: temp_rps.append(rp_summaries[0].resourcepool) else: self._handle_error( message="Unable to find resource pool %s" % rp_name) vm_filter_spec.folders = set(temp_rps) return vm_filter_spec
session = requests.session() # Disable cert verification for demo purpose. # This is not recommended in a production environment. session.verify = False # Disable the secure connection warning for demo purpose. # This is not recommended in a production environment. urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) # Connect to a vCenter Server using username and password config = VsCreadential.load('.credentials.yaml') client = create_vsphere_client(server=config.hostname, username=config.username, password=config.password, session=session) vm = 'TESTVM' vm = client.vcenter.VM.list(VM.FilterSpec(names=set(['TESTVM'])))[0] vm_info = client.vcenter.VM.get(vm.vm) print('vm.get({}) -> {}'.format(vm, vm_info)) state = client.vcenter.vm.Power.get(vm.vm) if state == Power.Info(state=Power.State.POWERED_ON): client.vcenter.vm.Power.stop(vm.vm) elif state == Power.Info(state=Power.State.SUSPENDED): client.vcenter.vm.Power.start(vm.vm) client.vcenter.vm.Power.stop(vm.vm) client.vcenter.VM.delete(vm.vm) print("Deleted VM -- '{}-({})".format('TESTVM', vm.vm))
Sample Prerequisites: - vCenter """ # Create argument parser for standard inputs: # server, username, password, cleanup and skipverification parser = sample_cli.build_arg_parser() # Add your custom input arguments parser.add_argument('--vm_name', action='store', default='Sample_Default_VM_for_Simple_Testbed', help='Name of the testing vm') args = sample_util.process_cli_args(parser.parse_args()) # Skip server cert verification if needed. # This is not recommended in production code. session = get_unverified_session() if args.skipverification else None # Connect to vSphere client client = create_vsphere_client(server=args.server, username=args.username, password=args.password, session=session) # List VMs filter_spec = VM.FilterSpec(names=set([args.vm_name])) vms = client.vcenter.VM.list(filter_spec) print(vms)