Python pyVmomi.vim.VirtualMachine() Examples
The following are 30
code examples of pyVmomi.vim.VirtualMachine().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
pyVmomi.vim
, or try the search function
.
Example #1
Source File: vSphere.py From im with GNU General Public License v3.0 | 7 votes |
def attach_volumes(self, conn, node, vm): """ Attach a the required volumes (in the RADL) to the launched instance Arguments: - conn(:py:class:`vim.connect.SmartConnect` ): Connection object. - node(:py:class:`vim.VirtualMachine` ): VM to add the disk. - vm(:py:class:`IM.VirtualMachine`): VM information. """ try: if node.summary.runtime.powerState == "poweredOn" and "volumes" not in vm.__dict__.keys(): # Flag to set that this VM has created (or is creating) the # volumes vm.volumes = True cont = 1 while vm.info.systems[0].getValue("disk." + str(cont) + ".size"): disk_size = vm.info.systems[0].getFeature("disk." + str(cont) + ".size").getValue('G') # disk_device = vm.info.systems[0].getValue("disk." + str(cont) + ".device") self.log_info("Creating a %d GB volume for the disk %d" % (int(disk_size), cont)) self.add_disk(node, conn, disk_size) cont += 1 except Exception: self.log_exception("Error creating or attaching the volume to the instance")
Example #2
Source File: PyvmomiClient.py From katprep with GNU General Public License v3.0 | 6 votes |
def __get_snapshots(self, vm_name): """ Returns a set of all snapshots for a particular VM. :param vm_name: Name of a virtual machine :type vm_name: str """ try: content = self.SESSION.RetrieveContent() container = content.viewManager.CreateContainerView( content.rootFolder, [vim.VirtualMachine], True ) for c in container.view: if c.name == vm_name: snapshots = c.snapshot.rootSnapshotList return snapshots except AttributeError: raise EmptySetException("No snapshots found")
Example #3
Source File: destroy_vm.py From pyvmomi-community-samples with Apache License 2.0 | 6 votes |
def setup_args(): """Adds additional ARGS to allow the vm name or uuid to be set. """ parser = cli.build_arg_parser() # using j here because -u is used for user parser.add_argument('-j', '--uuid', help='BIOS UUID of the VirtualMachine you want ' 'to destroy.') parser.add_argument('-n', '--name', help='DNS Name of the VirtualMachine you want to ' 'destroy.') parser.add_argument('-i', '--ip', help='IP Address of the VirtualMachine you want to ' 'destroy') parser.add_argument('-v', '--vm', help='VM name of the VirtualMachine you want ' 'to destroy.') my_args = parser.parse_args() return cli.prompt_for_password(my_args)
Example #4
Source File: ezmomi.py From ezmomi with MIT License | 6 votes |
def get_vm_failfast(self, name, verbose=False, vm_term='VM', path=""): """ Get a VirtualMachine object fail fast if the object isn't a valid reference """ if verbose: print("Finding VirtualMachine named %s..." % name) if path: vm = self.get_vm(name, path=path) else: vm = self.get_vm(name) if vm is None: print("Error: %s '%s' does not exist" % (vm_term, name)) sys.exit(1) if verbose: print("Found VirtualMachine: %s Name: %s" % (vm, vm.name)) return vm
Example #5
Source File: change_vm_cd_backend.py From pyvmomi-community-samples with Apache License 2.0 | 6 votes |
def main(): args = get_args() # connect to vc si = SmartConnect( host=args.host, user=args.user, pwd=args.password, port=args.port) # disconnect vc atexit.register(Disconnect, si) content = si.RetrieveContent() print 'Searching for VM {}'.format(args.vmname) vm_obj = get_obj(content, [vim.VirtualMachine], args.vmname) if vm_obj: update_virtual_cd_backend_by_obj(si, vm_obj, args.unitnumber, args.iso) device_change = args.iso if args.iso else 'Client Device' print 'VM CD/DVD {} successfully' \ ' state changed to {}'.format(args.unitnumber, device_change) else: print "VM not found" # start
Example #6
Source File: deploy_contrail_vm.py From contrail-server-manager with Apache License 2.0 | 6 votes |
def auto_start_vm(si, args, vm_obj): si_content = si.RetrieveContent() objs = get_objects(si, args) host = objs['host_obj'] vm_obj = get_obj(si_content, [vim.VirtualMachine], args.vm_name) host_settings = vim.host.AutoStartManager.SystemDefaults() host_settings.enabled = True config = host.configManager.autoStartManager.config config.defaults = host_settings auto_power_info = vim.host.AutoStartManager.AutoPowerInfo() auto_power_info.key = vm_obj auto_power_info.startOrder = 1 auto_power_info.startAction = "powerOn" auto_power_info.startDelay = -1 auto_power_info.stopAction = "powerOff" auto_power_info.stopDelay = -1 auto_power_info.waitForHeartbeat = 'no' config.powerInfo = [auto_power_info] host.configManager.autoStartManager.ReconfigureAutostart(config)
Example #7
Source File: vm_listener.py From vsphere-storage-for-docker with Apache License 2.0 | 6 votes |
def create_vm_powerstate_filter(pc, from_node): """ Create a filter spec to list to VM power state changes """ filterSpec = vmodl.query.PropertyCollector.FilterSpec() objSpec = vmodl.query.PropertyCollector.ObjectSpec(obj=from_node, selectSet=vm_folder_traversal()) filterSpec.objectSet.append(objSpec) # Add the property specs propSpec = vmodl.query.PropertyCollector.PropertySpec(type=vim.VirtualMachine, all=False) propSpec.pathSet.append(VM_POWERSTATE) filterSpec.propSet.append(propSpec) try: pcFilter = pc.CreateFilter(filterSpec, True) atexit.register(pcFilter.Destroy) return None except Exception as e: err_msg = "Problem creating PropertyCollector filter: {}".format(str(e)) logging.error(err_msg) return err_msg
Example #8
Source File: vsphere.py From KubeOperator with Apache License 2.0 | 6 votes |
def get_templates(self, entity): templates = [] if isinstance(entity, vim.Folder): for obj in entity.childEntity: if isinstance(obj, vim.VirtualMachine) and obj.config.template: template = { "image_name": obj.name, "guest_id": obj.guest.guestId } templates.append(template) if isinstance(obj, vim.Folder): tem = self.get_templates(obj) if len(tem) > 0: templates.extend(tem) return templates else: return []
Example #9
Source File: vim_utils.py From vsphere-automation-sdk-python with MIT License | 6 votes |
def poweron_vm(content, mo): """ Powers on a VM and wait for power on operation to complete """ if not isinstance(mo, vim.VirtualMachine): return False print('Powering on vm {0}'.format(mo._GetMoId())) try: wait_for_tasks(content, [mo.PowerOn()]) print('{0} powered on successfully'.format(mo._GetMoId())) except Exception: print('Unexpected error while powering on vm {0}'.format( mo._GetMoId())) return False return True
Example #10
Source File: vim_utils.py From vsphere-automation-sdk-python with MIT License | 6 votes |
def poweroff_vm(content, mo): """ Powers on a VM and wait for power on operation to complete """ if not isinstance(mo, vim.VirtualMachine): return False print('Powering off vm {0}'.format(mo._GetMoId())) try: wait_for_tasks(content, [mo.PowerOff()]) print('{0} powered off successfully'.format(mo._GetMoId())) except Exception: print('Unexpected error while powering off vm {0}'.format( mo._GetMoId())) return False return True
Example #11
Source File: deploy_esxi.py From cot with MIT License | 6 votes |
def lookup_object(self, vimtype, name): """Look up an object by name. Args: vimtype (object): currently only ``vim.VirtualMachine`` name (str): Name of the object to look up. Returns: object: Located object """ content = self.service_instance.RetrieveContent() container = content.viewManager.CreateContainerView( content.rootFolder, [vimtype], True) for item in container.view: if item.name == name: return item return None
Example #12
Source File: PyvmomiClient.py From katprep with GNU General Public License v3.0 | 6 votes |
def powerstate_vm(self, vm_name): """ Returns the power state of a particular virtual machine. :param vm_name: Name of a virtual machine :type vm_name: str """ try: content = self.SESSION.RetrieveContent() vm = self.__get_obj(content, [vim.VirtualMachine], vm_name) if vm.runtime.powerState == vim.VirtualMachinePowerState.poweredOn: return "poweredOn" elif vm.runtime.powerState == vim.VirtualMachinePowerState.poweredOff: return "poweredOff" except AttributeError as err: raise SessionException( "Unable to get power state: '{}'".format(err) ) except ValueError as err: raise SessionException( "Unable to get power state: '{}'".format(err) )
Example #13
Source File: PyvmomiClient.py From katprep with GNU General Public License v3.0 | 6 votes |
def restart_vm(self, vm_name, force=False): """ Restarts a particular VM (default: soft reboot using guest tools). :param vm_name: Name of a virtual machine :type vm_name: str :param force: Flag whether a hard reboot is requested :type force: bool """ try: #get VM content = self.SESSION.RetrieveContent() vm = self.__get_obj(content, [vim.VirtualMachine], vm_name) if force: #kill it with fire vm.ResetVM_Task() else: #killing me softly vm.RebootGuest() except: raise SessionException("Unable to restart VM: '{}'".format( sys.exc_info()[0] ))
Example #14
Source File: PyvmomiClient.py From katprep with GNU General Public License v3.0 | 6 votes |
def get_vm_hosts(self): """ Returns a list of VMs and their hypervisors available through the current connection. """ try: #get _all_ the VMs content = self.SESSION.RetrieveContent() result = {} #create view cotaining VM objects object_view = content.viewManager.CreateContainerView( content.rootFolder, [vim.VirtualMachine], True ) for obj in object_view.view: result[obj.config.name] = { "hypervisor": obj.runtime.host.name } return result except ValueError as err: self.LOGGER.error("Unable to get VM hypervisor information: '%s'", err) raise SessionException(err)
Example #15
Source File: deploy_vsphere_template_with_nuage.py From vspk-examples with BSD 3-Clause "New" or "Revised" License | 5 votes |
def find_vm(vc, logger, name): """ Find a virtual machine by its name and return it """ content = vc.content obj_view = content.viewManager.CreateContainerView(content.rootFolder, [vim.VirtualMachine], True) vm_list = obj_view.view for vm in vm_list: logger.debug('Checking virtual machine %s' % vm.name) if vm.name == name: logger.debug('Found virtual machine %s' % vm.name) return vm return None
Example #16
Source File: vsphere_client.py From vmware_guest_auth_bypass with Apache License 2.0 | 5 votes |
def list_vms(self): return self._list_objects(vim.VirtualMachine)
Example #17
Source File: vm_power_ops.py From vmware-pyvmomi-examples with Apache License 2.0 | 5 votes |
def main(): try: si = None try: print "Trying to connect to VCENTER SERVER . . ." si = connect.Connect(inputs['vcenter_ip'], 443, inputs['vcenter_user'], inputs['vcenter_password']) except IOError, e: pass atexit.register(Disconnect, si) print "Connected to VCENTER SERVER !" content = si.RetrieveContent() if inputs['operation'] == 'stop' or inputs['operation'] == 'suspend': force = inputs['force'] vm = get_obj(content, [vim.VirtualMachine], inputs['vm_name']) #current_state = vm.runtime.powerState if inputs['operation'] == 'start': invoke_and_track(vm.PowerOn, None) elif inputs['operation'] == 'stop': if not force: invoke_and_track(vm.ShutdownGuest) else: invoke_and_track(vm. PowerOff) elif inputs['operation'] == 'suspend': if not force: invoke_and_track(vm.StandbyGuest) else: invoke_and_track(vm. Suspend) #wait_for_task(task, si)
Example #18
Source File: vm.py From ADLES with Apache License 2.0 | 5 votes |
def __init__(self, vm=None, name=None, folder=None, resource_pool=None, datastore=None, host=None): """ :param vm: VM instance to use instead of calling :meth:`create` :type vm: vim.VirtualMachine :param str name: Name of the VM :param folder: Folder in inventory to create the VM in :type folder: vim.Folder :param resource_pool: Resource pool to use for the VM :type resource_pool: vim.ResourcePool :param datastore: Datastore the VM is stored on :type datastore: vim.Datastore :param host: Host the VM runs on :type host: vim.HostSystem """ self._log = logging.getLogger('VM') if vm is not None: self._vm = vm self.name = vm.name self.folder = vm.parent self.resource_pool = vm.resourcePool self.datastore = vm.datastore[0] self.host = vm.summary.runtime.host self.network = vm.network self.runtime = vm.runtime self.summary = vm.summary else: self._vm = None self.name = name self.folder = folder # vim.Folder that will contain the VM self.resource_pool = resource_pool # vim.ResourcePool to use VM self.datastore = datastore # vim.Datastore object to store VM on self.host = host # vim.HostSystem
Example #19
Source File: folder_utils.py From ADLES with Apache License 2.0 | 5 votes |
def retrieve_items(folder, vm_prefix='', folder_prefix='', recursive=False): """ Retrieves VMs and folders from a folder structure. :param folder: Folder to begin search in (Note: it is NOT returned in list of folders) :type folder: vim.Folder :param str vm_prefix: VM prefix to search for :param str folder_prefix: Folder prefix to search for :param bool recursive: Recursively descend into sub-folders .. warning:: This will recurse regardless of folder prefix! :return: The VMs and folders found in the folder :rtype: tuple(list(vim.VirtualMachine), list(vim.Folder)) """ vms = [] folders = [] for item in folder.childEntity: # Iterate through all items in the folder if is_vm(item) and str(item.name).startswith(vm_prefix): vms.append(item) # Add matching vm to the list elif is_folder(item): if str(item.name).startswith(folder_prefix): folders.append(item) # Add matching folder to the list if recursive: # Recurse into sub-folders v, f = retrieve_items(item, vm_prefix, folder_prefix, recursive) vms.extend(v) folders.extend(f) return vms, folders
Example #20
Source File: vsphere_class.py From ADLES with Apache License 2.0 | 5 votes |
def find_by_ip(self, ip, vm_search=True): """ Find a VM or Host using a IP address. :param str ip: IP address string as returned by VMware Tools ipAddress :param vm_search: Search for VMs if True, Hosts if False :return: The VM or host found :rtype: vim.VirtualMachine or vim.HostSystem or None """ return self.search_index.FindByIp(datacenter=self.datacenter, ip=str(ip), vmSearch=vm_search)
Example #21
Source File: folder_utils.py From ADLES with Apache License 2.0 | 5 votes |
def enumerate_folder(folder, recursive=True, power_status=False): """ Enumerates a folder structure and returns the result. as a python object with the same structure :param folder: Folder to enumerate :type folder: vim.Folder :param bool recursive: Whether to recurse into any sub-folders :param bool power_status: Display the power state of the VMs in the folder :return: The nested python object with the enumerated folder structure :rtype: list(list, str) """ children = [] for item in folder.childEntity: if is_folder(item): if recursive: # Recurse into sub-folders and append the sub-tree children.append(enumerate_folder(item, recursive)) else: # Don't recurse, just append the folder children.append('- ' + item.name) elif is_vm(item): if power_status: if item.runtime.powerState == \ vim.VirtualMachine.PowerState.poweredOn: children.append('* ON ' + item.name) elif item.runtime.powerState == \ vim.VirtualMachine.PowerState.poweredOff: children.append('* OFF ' + item.name) elif item.runtime.powerState == \ vim.VirtualMachine.PowerState.suspended: children.append('* SUS ' + item.name) else: logging.error("Invalid power state for VM: %s", item.name) else: children.append('* ' + item.name) else: children.append("UNKNOWN ITEM: %s" % str(item)) return '+ ' + folder.name, children # Return tuple of parent and children # Similar to: https://docs.python.org/3/library/pprint.html
Example #22
Source File: vmware_exporter.py From vmware_exporter with BSD 3-Clause "New" or "Revised" License | 5 votes |
def _vmware_get_vms(self, content, vm_metrics, counter_info): """ Get VM information """ # List of performance counter we want perf_list = [ 'cpu.ready.summation', 'cpu.usage.average', 'cpu.usagemhz.average', 'disk.usage.average', 'disk.read.average', 'disk.write.average', 'mem.usage.average', 'net.received.average', 'net.transmitted.average', ] # Prepare gauges for p in perf_list: p_metric = 'vmware_vm_' + p.replace('.', '_') vm_metrics[p_metric] = GaugeMetricFamily( p_metric, p_metric, labels=['vm_name', 'host_name']) virtual_machines = self._vmware_get_obj(content, [vim.VirtualMachine]) log("Total Virtual Machines: {0}".format(len(virtual_machines))) for virtual_machine in virtual_machines: self.threader.thread_it(self._vmware_get_vm_perf_metrics, [content, counter_info, perf_list, virtual_machine, vm_metrics])
Example #23
Source File: vmware_exporter.py From vmware_exporter with BSD 3-Clause "New" or "Revised" License | 5 votes |
def _vmware_get_snapshots(self, content): """ Get snapshots from all VM """ snapshots_count_table = [] snapshots_age_table = [] virtual_machines = self._vmware_get_obj(content, [vim.VirtualMachine]) for virtual_machine in virtual_machines: if not virtual_machine or virtual_machine.snapshot is None: continue else: self.threader.thread_it(self._vmware_get_snapshot_details, [snapshots_count_table, snapshots_age_table, virtual_machine]) return snapshots_count_table, snapshots_age_table
Example #24
Source File: PyvmomiClient.py From katprep with GNU General Public License v3.0 | 5 votes |
def __manage_power( self, vm_name, action="poweroff" ): """ Powers a particual virtual machine on/off forcefully. :param vm_name: Name of a virtual machine :type vm_name: str :param action: action (poweroff, poweron) :type action: str """ try: content = self.SESSION.RetrieveContent() vm = self.__get_obj(content, [vim.VirtualMachine], vm_name) if action.lower() == "poweroff": #get down with the vickness task = vm.PowerOff() else: #fire it up task = vm.PowerOn() except AttributeError as err: raise SessionException( "Unable to manage power state: '{}'".format(err) ) except ValueError as err: raise SessionException( "Unable to manage power state: '{}'".format(err) ) #Aliases
Example #25
Source File: upgrade_vm.py From pyvmomi-community-samples with Apache License 2.0 | 5 votes |
def get_vm(content, name): """ Gets a named virtual machine. """ virtual_machine = None container = content.viewManager.CreateContainerView(content.rootFolder, [vim.VirtualMachine], True) for item in container.view: if item.name == name: virtual_machine = item break container.Destroy() # Best practice. Frees up resources on host. return virtual_machine
Example #26
Source File: add_nic_to_vm.py From pyvmomi-community-samples with Apache License 2.0 | 5 votes |
def main(): args = get_args() # connect this thing serviceInstance = None if args.no_ssl: serviceInstance = SmartConnectNoSSL( host=args.host, user=args.user, pwd=args.password, port=args.port) else: serviceInstance = SmartConnect( host=args.host, user=args.user, pwd=args.password, port=args.port) # disconnect this thing atexit.register(Disconnect, serviceInstance) vm = None if args.uuid: search_index = serviceInstance.content.searchIndex vm = search_index.FindByUuid(None, args.uuid, True) elif args.vm_name: content = serviceInstance.RetrieveContent() vm = get_obj(content, [vim.VirtualMachine], args.vm_name) if vm: add_nic(serviceInstance, vm, args.port_group) else: print("VM not found") # start this thing
Example #27
Source File: change_vm_cd_backend.py From pyvmomi-community-samples with Apache License 2.0 | 5 votes |
def get_args(): parser = cli.build_arg_parser() parser.add_argument('-n', '--vmname', required=True, help="Name of the VirtualMachine you want to change.") parser.add_argument('-m', '--unitnumber', required=True, help='CD/DVD unit number.', type=int) parser.add_argument('-i', '--iso', required=False, help='Full path to iso. i.e. "[ds1] folder/Ubuntu.iso"' ' If not provided, backend will' ' set to RemotePassThrough') my_args = parser.parse_args() return cli.prompt_for_password(my_args)
Example #28
Source File: vmware.py From RENAT with Apache License 2.0 | 5 votes |
def get_vm_list(self): """ Returns current VM name list of the hypervisor """ conn = self._channels[self._current_name]['connection'] content = conn.content vm_list = content.viewManager.CreateContainerView(content.rootFolder, [vim.VirtualMachine], True) result = [] for vm in vm_list.view: result.append(vm.name) BuiltIn().log('Got VM list(%d)' % len(result)) return result
Example #29
Source File: vmware.py From skylight with GNU General Public License v3.0 | 5 votes |
def find_vm_by_id(content, vm_id, vm_id_type="vm_name", datacenter=None, cluster=None, folder=None, match_first=False): """ UUID is unique to a VM, every other id returns the first match. """ si = content.searchIndex vm = None if vm_id_type == 'dns_name': vm = si.FindByDnsName(datacenter=datacenter, dnsName=vm_id, vmSearch=True) elif vm_id_type == 'uuid': # Search By BIOS UUID rather than instance UUID vm = si.FindByUuid(datacenter=datacenter, instanceUuid=False, uuid=vm_id, vmSearch=True) elif vm_id_type == 'ip': vm = si.FindByIp(datacenter=datacenter, ip=vm_id, vmSearch=True) elif vm_id_type == 'vm_name': folder = None if cluster: folder = cluster elif datacenter: folder = datacenter.hostFolder vm = find_vm_by_name(content, vm_id, folder) elif vm_id_type == 'inventory_path': searchpath = folder # get all objects for this path f_obj = si.FindByInventoryPath(searchpath) if f_obj: if isinstance(f_obj, vim.Datacenter): f_obj = f_obj.vmFolder for c_obj in f_obj.childEntity: if not isinstance(c_obj, vim.VirtualMachine): continue if c_obj.name == vm_id: vm = c_obj if match_first: break return vm
Example #30
Source File: vsphere_class.py From ADLES with Apache License 2.0 | 5 votes |
def get_vm(self, vm_name): """ Finds and returns the named VM. :param str vm_name: Name of the VM :return: The VM found :rtype: vim.VirtualMachine or None """ return self.get_item(vim.VirtualMachine, vm_name)