def main(): """ Simple command-line program for creating a snapshot of a first class disk. """ parser = cli.Parser() parser.add_required_arguments(cli.Argument.DATASTORE_NAME, cli.Argument.FIRST_CLASS_DISK_NAME, cli.Argument.SNAPSHOT_NAME) args = parser.get_args() si = service_instance.connect(args) try: content = si.RetrieveContent() # Retrieve Datastore Object datastore = pchelper.get_obj(content, [vim.Datastore], args.datastore_name) # Retrieve FCD Object vdisk = disk.retrieve_fcd(content, datastore, args.fcd_name) # Create FCD Snapshot storage = content.vStorageObjectManager task = storage.VStorageObjectCreateSnapshot_Task( vdisk.config.id, datastore, args.snapshot_name) tasks.wait_for_tasks(si, [task]) print("FCD snapshot created!") except vmodl.MethodFault as error: print("Caught vmodl fault : " + error.msg) return -1 return 0
def main(): """ Sample for adding a vm NIC to a Distributed Virtual Switch """ parser = cli.Parser() parser.add_required_arguments(cli.Argument.VM_NAME, cli.Argument.PORT_GROUP, cli.Argument.VM_MAC) args = parser.get_args() si = service_instance.connect(args) content = si.RetrieveContent() print("Search VDS PortGroup by Name ...") portgroup = pchelper.get_obj(content, [vim.dvs.DistributedVirtualPortgroup], args.port_group) if portgroup is None: print("Portgroup not Found in DVS ...") sys.exit(0) print("Search Available(Unused) port for VM...") dvs = portgroup.config.distributedVirtualSwitch port_key = search_port(dvs, portgroup.key) port = port_find(dvs, port_key) print("Search VM by Name ...") vm = None vm = pchelper.get_obj(content, [vim.VirtualMachine], args.vm_name) if vm: print("Find Vm , Add Nic Card ...") add_nic(vm, args.vm_mac, port) else: print("Vm not Found ...")
def main(): parser = cli.Parser() parser.add_required_arguments(cli.Argument.VM_NAME, cli.Argument.DATASTORE_NAME, cli.Argument.ESX_NAME) args = parser.get_args() si = service_instance.connect(args) try: content = si.RetrieveContent() # Assigning destination datastores datastore_dest = args.datastore_name # Target compute resource host_dest = args.esx_name relocate_vm(args.vm_name, content=content, host_dest=host_dest, datastore_dest=datastore_dest) except vmodl.MethodFault as error: print("Caught vmodl fault : " + error.msg) return -1 return 0
def main(): """ Sample for adding a raw disk to vm """ parser = cli.Parser() parser.add_required_arguments(cli.Argument.DEVICE_NAME) parser.add_optional_arguments(cli.Argument.VM_NAME, cli.Argument.UUID, cli.Argument.DISK_MODE, cli.Argument.COMPATIBILITY_MODE) args = parser.get_args() si = service_instance.connect(args) 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 = pchelper.get_obj(content, [vim.VirtualMachine], args.vm_name) if vm: add_raw_disk(vm, si, args.device_name, args.disk_mode, args.disk_compatibility_mode) else: print("VM not found")
def main(): parser = cli.Parser() args = parser.get_args() si = service_instance.connect(args) # Connect to SPBM Endpoint pbm_si, pbm_content = get_pbm_connection(si._stub) pm = pbm_content.profileManager profile_ids = pm.PbmQueryProfile( resourceType=pbm.profile.ResourceType(resourceType="STORAGE"), profileCategory="REQUIREMENT") profiles = [] if len(profile_ids) > 0: profiles = pm.PbmRetrieveContent(profileIds=profile_ids) for profile in profiles: print("Name: %s " % profile.name) print("ID: %s " % profile.profileId.uniqueId) print("Description: %s " % profile.description) if hasattr(profile.constraints, 'subProfiles'): subprofiles = profile.constraints.subProfiles for subprofile in subprofiles: print("RuleSetName: %s " % subprofile.name) capabilities = subprofile.capability show_capabilities(capabilities) print("")
def main(): """ Simple command-line program for listing the virtual machines on a system. """ parser = cli.Parser() args = parser.get_args() si = service_instance.connect(args) try: 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 = si.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
def main(): """ Upgrades the hardware version of a Virtual Machine. """ parser = cli.Parser() parser.add_required_arguments(cli.Argument.VM_NAME) parser.add_custom_argument( '--release', required=False, action='store', default=None, help='Version/release number of the Virtual machine hardware') args = parser.get_args() si = service_instance.connect(args) content = si.RetrieveContent() vm = pchelper.get_obj(content, [vim.VirtualMachine], args.vm_name) if not vm: print("Could not find VM %s" % args.vm_name) else: print("Upgrading VM %s" % args.vm_name) # Set the hardware version to use if specified if args.release is not None: print("New version will be %s" % args.release) version = "vmx-{:02d}".format(args.release) else: version = None # Upgrade the VM try: task.WaitForTask(task=vm.UpgradeVM_Task(version), si=si) print("Upgrade complete") except vim.fault.AlreadyUpgraded: print("VM is already upgraded")
def main(): """ Simple command-line program for listing the virtual machines on a system. """ parser = cli.Parser() args = parser.get_args() try: my_vcr = config.VCR(custom_patches=((SoapAdapter, "_HTTPSConnection", VCRHTTPSConnection), )) # use the vcr instance to setup an instance of service_instance with my_vcr.use_cassette('hello_world_vcenter.yaml', record_mode='all'): si = service_instance.connect(args) 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 = si.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
def main(): parser = cli.Parser() parser.add_required_arguments(cli.Argument.VM_NAME) parser.add_custom_argument('--unitnumber', required=True, help='HDD number to delete.', type=int) parser.add_custom_argument('--yes', help='Confirm disk deletion.', action='store_true') parser.add_custom_argument('--language', default='English', help='Language your vcenter used.') args = parser.get_args() si = service_instance.connect(args) content = si.RetrieveContent() print('Searching for VM {}'.format(args.vm_name)) vm_obj = pchelper.get_obj(content, [vim.VirtualMachine], args.vm_name) if vm_obj: if not args.yes: cli.prompt_y_n_question("Are you sure you want " "to delete HDD " "{}?".format(args.unitnumber), default='no') delete_virtual_disk(si, vm_obj, args.unitnumber, args.language) print('VM HDD "{}" successfully deleted.'.format(args.unitnumber)) else: print('VM not found')
def main(): """ Let this thing fly """ parser = cli.Parser() parser.add_required_arguments(cli.Argument.VM_NAME, cli.Argument.TEMPLATE) # if no locationis provided, thefirst available datacenter, datastore, etc. will be used parser.add_optional_arguments( cli.Argument.DATACENTER_NAME, cli.Argument.VMFOLDER, cli.Argument.DATASTORE_NAME, cli.Argument.DATASTORECLUSTER_NAME, cli.Argument.CLUSTER_NAME, cli.Argument.RESOURCE_POOL, cli.Argument.POWER_ON, cli.Argument.OPAQUE_NETWORK_NAME) args = parser.get_args() si = service_instance.connect(args) content = si.RetrieveContent() template = pchelper.get_obj(content, [vim.VirtualMachine], args.template) if template: clone_vm(content, template, args.vm_name, args.datacenter_name, args.vm_folder, args.datastore_name, args.cluster_name, args.resource_pool, args.power_on, args.datastorecluster_name) if args.opaque_network_name: vm = pchelper.get_obj(content, [vim.VirtualMachine], args.vm_name) add_nic(si, vm, args.opaque_network_name) else: print("template not found")
def main(): """ Simple command-line program for listing Datastores in Datastore Cluster """ parser = cli.Parser() parser.add_required_arguments(cli.Argument.DATASTORECLUSTER_NAME) args = parser.get_args() si = service_instance.connect(args) try: content = si.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.datastorecluster_name: 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
def main(): parser = cli.Parser() parser.add_required_arguments(cli.Argument.ESX_IP) args = parser.get_args() si = service_instance.connect(args) content = si.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_ip: 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(si, [task]) print("Operation complete") return 0
def main(): """ Simple command-line program for listing all snapshots of a fcd """ parser = cli.Parser() parser.add_required_arguments(cli.Argument.DATASTORE_NAME, cli.Argument.FIRST_CLASS_DISK_NAME) args = parser.get_args() si = service_instance.connect(args) try: content = si.RetrieveContent() # Retrieve Datastore Object datastore = pchelper.get_obj(content, [vim.Datastore], args.datastore_name) # Retrieve FCD Object vdisk = disk.retrieve_fcd(content, datastore, args.fcd_name) # Retrieve all Snapshots list_fcd_snapshots(content, vdisk) except vmodl.MethodFault as error: print("Caught vmodl fault : " + error.msg) return -1 return 0
def main(): """ function runs all of the other functions. Some parts of this function are taken from the getallvms.py script from the pyvmomi gihub repo """ parser = cli.Parser() parser.add_optional_arguments(cli.Argument.VM_NAME, cli.Argument.UUID, cli.Argument.PORT_GROUP) args = parser.get_args() si = service_instance.connect(args) try: content = si.RetrieveContent() datacenter = content.rootFolder.childEntity[0] datastores = datacenter.datastore vmfolder = datacenter.vmFolder vmlist = vmfolder.childEntity dsvmkey = [] # each datastore found on ESXi host or vCenter is passed # to the find_vmx and examine_vmx functions to find all # VMX files and search them for datastore in datastores: find_vmx(datastore.browser, "[%s]" % datastore.summary.name, datacenter.name, datastore.summary.name) examine_vmx(datastore.summary.name) updatevmx_path() # each VM found in the inventory is passed to the getvm_info # function to get it's instanceuuid for vm in vmlist: getvm_info(vm) # each key from the DS_VM hashtable is added to a separate # list for comparison later for a in DS_VM.keys(): dsvmkey.append(a) # each uuid in the dsvmkey list is passed to the find_match # function to look for a match print("The following virtual machine(s) do not exist in the " "inventory, but exist on a datastore " "(Display Name, Datastore/Folder name):") for match in dsvmkey: find_match(match) Disconnect(si) except vmodl.MethodFault as ex: print("Caught vmodl fault : " + ex.msg) return -1 except Exception as ex: print("Caught exception : " + str(ex)) return -1 return 0
def main(): parser = cli.Parser() parser.add_optional_arguments(cli.Argument.OVA_PATH, cli.Argument.DATACENTER_NAME, cli.Argument.RESOURCE_POOL, cli.Argument.DATASTORE_NAME) args = parser.get_args() si = service_instance.connect(args) if args.datacenter_name: datacenter = get_dc(si, args.datacenter_name) else: datacenter = si.content.rootFolder.childEntity[0] if args.resource_pool: resource_pool = get_rp(si, datacenter, args.resource_pool) else: resource_pool = get_largest_free_rp(si, datacenter) if args.datastore_name: datastore = get_ds(datacenter, args.datastore_name) else: datastore = get_largest_free_ds(datacenter) ovf_handle = OvfHandler(args.ova_path) ovf_manager = si.content.ovfManager # CreateImportSpecParams can specify many useful things such as # diskProvisioning (thin/thick/sparse/etc) # networkMapping (to map to networks) # propertyMapping (descriptor specific properties) cisp = vim.OvfManager.CreateImportSpecParams() cisr = ovf_manager.CreateImportSpec( ovf_handle.get_descriptor(), resource_pool, datastore, cisp) # These errors might be handleable by supporting the parameters in # CreateImportSpecParams if cisr.error: print("The following errors will prevent import of this OVA:") for error in cisr.error: print("%s" % error) return 1 ovf_handle.set_spec(cisr) lease = resource_pool.ImportVApp(cisr.importSpec, datacenter.vmFolder) while lease.state == vim.HttpNfcLease.State.initializing: print("Waiting for lease to be ready...") time.sleep(1) if lease.state == vim.HttpNfcLease.State.error: print("Lease error: %s" % lease.error) return 1 if lease.state == vim.HttpNfcLease.State.done: return 0 print("Starting deploy...") return ovf_handle.upload_disks(lease, args.host)
def main(): parser = cli.Parser() parser.add_required_arguments(cli.Argument.VSWITCH_NAME) args = parser.get_args() si = service_instance.connect(args) content = si.RetrieveContent() hosts = get_vm_hosts(content) if del_hosts_switch(hosts, args.vswitch_name): print("vSwitch Deleted")
def main(): parser = cli.Parser() parser.add_optional_arguments(cli.Argument.VM_NAME, cli.Argument.DATACENTER_NAME, cli.Argument.DATASTORE_NAME, cli.Argument.ESX_IP) args = parser.get_args() si = service_instance.connect(args) create_vm(si, args.vm_name, args.datacenter_name, args.esx_ip, args.datastore_name)
def main(): parser = cli.Parser() parser.add_required_arguments(cli.Argument.PORT_GROUP) args = parser.get_args() si = service_instance.connect(args) content = si.RetrieveContent() hosts = get_vm_hosts(content) if del_hosts_portgroup(hosts, args.port_group): print('Deleted Port Group')
def main(): global content, hosts, host_pg_dict parser = cli.Parser() args = parser.get_args() si = service_instance.connect(args) content = si.RetrieveContent() hosts = get_vm_hosts(content) host_pg_dict = get_hosts_portgroups(hosts) vms = get_vms(content) for vm in vms: print_vminfo(vm)
def main(): parser = cli.Parser() args = parser.get_args() si = service_instance.connect(args) content = si.RetrieveContent() hosts = get_vm_hosts(content) host_switches_dict = get_hosts_switches(hosts) if host_switches_dict is not None: print("The vSwitches are:\n") for host, vswithes in host_switches_dict.items(): for vswitch in vswithes: print(vswitch.name)
def main(): """ Sample for adding a virtual switch to host """ parser = cli.Parser() parser.add_required_arguments(cli.Argument.VSWITCH_NAME) args = parser.get_args() si = service_instance.connect(args) content = si.RetrieveContent() hosts = get_vm_hosts(content) if add_hosts_switch(hosts, args.vswitch_name): print("vSwitch Added")
def main(): parser = cli.Parser() parser.add_required_arguments(cli.Argument.DATACENTER_NAME) parser.add_custom_argument('--dvswitch-name', required=False, help='name of the dvswitch', default='all') args = parser.get_args() si = service_instance.connect(args) content = si.RetrieveContent() datacenter = pchelper.get_obj(content, [vim.Datacenter], args.datacenter_name) if datacenter is None: print("Failed to find the datacenter %s" % args.datacenter_name) return 0 if args.dvswitch_name == 'all': dvs_lists = pchelper.get_all_obj(content, [vim.DistributedVirtualSwitch], folder=datacenter.networkFolder) else: dvsn = pchelper.search_for_obj(content, [vim.DistributedVirtualSwitch], args.dvswitch_name) if dvsn is None: print("Failed to find the dvswitch %s" % args.dvswitch_name) return 0 dvs_lists = [dvsn] print('Datacenter Name'.ljust(40) + ' :', args.datacenter_name) for dvs in dvs_lists: print(40 * '#') print('Dvswitch Name'.ljust(40) + ' :', dvs.name) print(40 * '#') for dvs_pg in dvs.portgroup: vlan_info = dvs_pg.config.defaultPortConfig.vlan vlan_spec = vim.dvs.VmwareDistributedVirtualSwitch.TrunkVlanSpec if isinstance(vlan_info, vlan_spec): vlanlist = [] for item in vlan_info.vlanId: if item.start == item.end: vlanlist.append(str(item.start)) else: vlanlist.append(str(item.start) + '-' + str(item.end)) vlan_id = " | Trunk | vlan id: " + ','.join(vlanlist) else: vlan_id = " | vlan id: " + str(vlan_info.vlanId) print(dvs_pg.name.ljust(40) + vlan_id) return 0
def main(): """ Iterate through all datacenters and list VM info. """ parser = cli.Parser() parser.add_custom_argument('--json', required=False, action='store_true', help='Write out to json file') parser.add_custom_argument('--jsonfile', required=False, action='store', default='getvmsbycluster.json', help='Filename and path of json file') parser.add_custom_argument('--silent', required=False, action='store_true', help='supress output to screen') args = parser.get_args() si = service_instance.connect(args) outputjson = True if args.json else False content = si.RetrieveContent() children = content.rootFolder.childEntity for child in children: # Iterate though DataCenters datacenter = child data[datacenter.name] = {} # Add data Centers to data dict clusters = datacenter.hostFolder.childEntity for cluster in clusters: # Iterate through the clusters in the DC # Add Clusters to data dict data[datacenter.name][cluster.name] = {} hosts = cluster.host # Variable to make pep8 compliance for host in hosts: # Iterate through Hosts in the Cluster hostname = host.summary.config.name # Add VMs to data dict by config name data[datacenter.name][cluster.name][hostname] = {} vms = host.vm for vm in vms: # Iterate through each VM on the host vmname = vm.summary.config.name data[datacenter.name][cluster.name][hostname][vmname] = {} summary = vmsummary(vm.summary, vm.guest) vm2dict(datacenter.name, cluster.name, hostname, vm, summary) if not args.silent: print(json.dumps(data, sort_keys=True, indent=4)) if outputjson: data2json(data, args)
def main(): parser = cli.Parser() parser.add_required_arguments(cli.Argument.DVS_NAME, cli.Argument.DVS_PORT_GROUP_NAME) args = parser.get_args() si = service_instance.connect(args) try: # call configuration of dvs port group configure_dvs_pg(si, args.dvs_name, args.dvs_pg_name) except vmodl.MethodFault as error: print("Caught vmodl fault : {0}".format(error.msg)) return -1 return 0
def main(): """ Simple command-line program for deleting a snapshot of a first class disk. """ parser = cli.Parser() parser.add_required_arguments(cli.Argument.DATASTORE_NAME, cli.Argument.FIRST_CLASS_DISK_NAME, cli.Argument.SNAPSHOT_NAME) parser.add_custom_argument('--yes', action='store_true', help='Confirm disk deletion.') args = parser.get_args() si = service_instance.connect(args) try: content = si.RetrieveContent() # Retrieve Datastore Object datastore = pchelper.get_obj(content, [vim.Datastore], args.datastore_name) # Retrieve FCD Object vdisk = disk.retrieve_fcd(content, datastore, args.fcd_name) # Retrieve Snapshot Object snapshot = disk.retrieve_fcd_snapshot( content, datastore, vdisk, args.snapshot_name) # Confirming Snapshot deletion if not args.yes: response = cli.prompt_y_n_question("Are you sure you want to " "delete snapshot '" + args.snapshot_name + "'?", default='no') if not response: print("Exiting script. User chose not to delete snapshot.") sys.exit() # Delete FCD Snapshot storage = content.vStorageObjectManager task = storage.DeleteSnapshot_Task( vdisk.config.id, datastore, snapshot) tasks.wait_for_tasks(si, [task]) print("FCD snapshot deleted!") except vmodl.MethodFault as error: print("Caught vmodl fault : " + error.msg) return -1 return 0
def main(): parser = cli.Parser() parser.add_optional_arguments(cli.Argument.DATASTORE_NAME) args = parser.get_args() si = service_instance.connect(args) content = si.RetrieveContent() # Get list of ds mo datastore = pchelper.search_for_obj(content, [vim.Datastore], args.datastore_name) if datastore: ds_obj_list = [datastore] else: ds_obj_list = pchelper.get_all_obj(content, [vim.Datastore]) for ds in ds_obj_list: print_datastore_info(ds)
def main(): """ Sample for adding a port group to a virtual switch """ parser = cli.Parser() parser.add_required_arguments(cli.Argument.VSWITCH_NAME, cli.Argument.PORT_GROUP, cli.Argument.VLAN_ID) parser.add_optional_arguments(cli.Argument.ESX_NAME_REGEX) args = parser.get_args() si = service_instance.connect(args) content = si.RetrieveContent() hosts = get_vm_hosts(content, args.esx_name_regex) if add_hosts_portgroup(hosts, args.vswitch_name, args.port_group, args.vlan_id): print("Added Port group to vSwitch")
def main(): """ Simple command-line program for listing the virtual machines on a host. """ parser = cli.Parser() args = parser.get_args() si = service_instance.connect(args) content = si.RetrieveContent() for child in content.rootFolder.childEntity: if hasattr(child, 'vmFolder'): datacenter = child vmfolder = datacenter.vmFolder vmlist = vmfolder.childEntity for vm in vmlist: print_vminfo(vm)
def main(): parser = cli.Parser() parser.add_required_arguments(cli.Argument.VM_NAME, cli.Argument.DISK_MODE) parser.add_custom_argument('--disk-number', required=True, help='Disk number to change mode.') args = parser.get_args() si = service_instance.connect(args) content = si.RetrieveContent() print('Searching for VM {}'.format(args.vm_name)) vm_obj = pchelper.get_obj(content, [vim.VirtualMachine], args.vm_name) if vm_obj: change_disk_mode(si, vm_obj, args.disk_number, args.disk_mode) print('VM Disk {} successfully changed to mode {}.'.format(args.disk_number, args.disk_mode)) else: print("VM not found.")
def main(): parser = cli.Parser() parser.add_required_arguments(cli.Argument.VM_NAME, cli.Argument.DATACENTER_NAME) parser.add_custom_argument( '--filterUsers', help="Comma-separated list of users to filter on") parser.add_custom_argument('--filterSystemUser', action='store_true', help="Filter system user, defaults to false.") args = parser.get_args() si = service_instance.connect(args) if args.datacenter_name: datacenter = get_dc(si, args.datacenter_name) else: datacenter = si.content.rootFolder.childEntity[0] vm = si.content.searchIndex.FindChild(datacenter.vmFolder, args.vm_name) if vm is None: raise Exception('Failed to find VM %s in datacenter %s' % (datacenter.name, args.vm_name)) by_entity = vim.event.EventFilterSpec.ByEntity(entity=vm, recursion="self") ids = ['VmRelocatedEvent', 'DrsVmMigratedEvent', 'VmMigratedEvent'] filter_spec = vim.event.EventFilterSpec(entity=by_entity, eventTypeId=ids) # Optionally filter by users user_list = [] if args.filterUsers: user_list = re.split('.*,.*', args.filterUsers) if len(user_list) > 0 or args.filterSystemUser: by_user = vim.event.EventFilterSpec.ByUsername(userList=user_list) by_user.systemUser = args.filterSystemUser filter_spec.userName = by_user event_manager = si.content.eventManager events = event_manager.QueryEvent(filter_spec) for event in events: print("%s" % event._wsdlName) print("VM: %s" % event.vm.name) print("User: %s" % event.userName) print("Host: %s -> %s" % (event.sourceHost.name, event.host.name)) print("Datacenter: %s -> %s" % (event.sourceDatacenter.name, event.datacenter.name)) print("Datastore: %s -> %s" % (event.sourceDatastore.name, event.ds.name)) print("%s" % events)