当前位置: 首页>>代码示例>>Python>>正文


Python vim.VirtualMachine方法代码示例

本文整理汇总了Python中pyVmomi.vim.VirtualMachine方法的典型用法代码示例。如果您正苦于以下问题:Python vim.VirtualMachine方法的具体用法?Python vim.VirtualMachine怎么用?Python vim.VirtualMachine使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在pyVmomi.vim的用法示例。


在下文中一共展示了vim.VirtualMachine方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: attach_volumes

# 需要导入模块: from pyVmomi import vim [as 别名]
# 或者: from pyVmomi.vim import VirtualMachine [as 别名]
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") 
开发者ID:grycap,项目名称:im,代码行数:25,代码来源:vSphere.py

示例2: poweron_vm

# 需要导入模块: from pyVmomi import vim [as 别名]
# 或者: from pyVmomi.vim import VirtualMachine [as 别名]
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 
开发者ID:vmware,项目名称:vsphere-automation-sdk-python,代码行数:18,代码来源:vim_utils.py

示例3: auto_start_vm

# 需要导入模块: from pyVmomi import vim [as 别名]
# 或者: from pyVmomi.vim import VirtualMachine [as 别名]
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) 
开发者ID:Juniper,项目名称:contrail-server-manager,代码行数:21,代码来源:deploy_contrail_vm.py

示例4: get_vm_failfast

# 需要导入模块: from pyVmomi import vim [as 别名]
# 或者: from pyVmomi.vim import VirtualMachine [as 别名]
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 
开发者ID:snobear,项目名称:ezmomi,代码行数:21,代码来源:ezmomi.py

示例5: create_vm_powerstate_filter

# 需要导入模块: from pyVmomi import vim [as 别名]
# 或者: from pyVmomi.vim import VirtualMachine [as 别名]
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 
开发者ID:vmware-archive,项目名称:vsphere-storage-for-docker,代码行数:23,代码来源:vm_listener.py

示例6: get_templates

# 需要导入模块: from pyVmomi import vim [as 别名]
# 或者: from pyVmomi.vim import VirtualMachine [as 别名]
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 [] 
开发者ID:KubeOperator,项目名称:KubeOperator,代码行数:20,代码来源:vsphere.py

示例7: poweroff_vm

# 需要导入模块: from pyVmomi import vim [as 别名]
# 或者: from pyVmomi.vim import VirtualMachine [as 别名]
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 
开发者ID:vmware,项目名称:vsphere-automation-sdk-python,代码行数:18,代码来源:vim_utils.py

示例8: lookup_object

# 需要导入模块: from pyVmomi import vim [as 别名]
# 或者: from pyVmomi.vim import VirtualMachine [as 别名]
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 
开发者ID:glennmatthews,项目名称:cot,代码行数:18,代码来源:deploy_esxi.py

示例9: __get_snapshots

# 需要导入模块: from pyVmomi import vim [as 别名]
# 或者: from pyVmomi.vim import VirtualMachine [as 别名]
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") 
开发者ID:stdevel,项目名称:katprep,代码行数:20,代码来源:PyvmomiClient.py

示例10: get_vm_hosts

# 需要导入模块: from pyVmomi import vim [as 别名]
# 或者: from pyVmomi.vim import VirtualMachine [as 别名]
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) 
开发者ID:stdevel,项目名称:katprep,代码行数:23,代码来源:PyvmomiClient.py

示例11: restart_vm

# 需要导入模块: from pyVmomi import vim [as 别名]
# 或者: from pyVmomi.vim import VirtualMachine [as 别名]
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]
            )) 
开发者ID:stdevel,项目名称:katprep,代码行数:26,代码来源:PyvmomiClient.py

示例12: powerstate_vm

# 需要导入模块: from pyVmomi import vim [as 别名]
# 或者: from pyVmomi.vim import VirtualMachine [as 别名]
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)
            ) 
开发者ID:stdevel,项目名称:katprep,代码行数:25,代码来源:PyvmomiClient.py

示例13: setup_args

# 需要导入模块: from pyVmomi import vim [as 别名]
# 或者: from pyVmomi.vim import VirtualMachine [as 别名]
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) 
开发者ID:vmware,项目名称:pyvmomi-community-samples,代码行数:25,代码来源:destroy_vm.py

示例14: main

# 需要导入模块: from pyVmomi import vim [as 别名]
# 或者: from pyVmomi.vim import VirtualMachine [as 别名]
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 
开发者ID:vmware,项目名称:pyvmomi-community-samples,代码行数:27,代码来源:change_vm_cd_backend.py

示例15: find_vm_by_id

# 需要导入模块: from pyVmomi import vim [as 别名]
# 或者: from pyVmomi.vim import VirtualMachine [as 别名]
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 
开发者ID:mgmt-sa-tiger-team,项目名称:skylight,代码行数:36,代码来源:vmware.py


注:本文中的pyVmomi.vim.VirtualMachine方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。