예제 #1
0
    def change_mac(vm, service_instance, new_mac=None):
        device_change = []
        if new_mac is None:
            new_mac = VirtualMachine.generate_mac()
        try:
            for device in vm.config.hardware.device:
                if isinstance(device, vim.vm.device.VirtualEthernetCard):
                    nicspec = vim.vm.device.VirtualDeviceSpec()
                    nicspec.operation = \
                        vim.vm.device.VirtualDeviceSpec.Operation.edit

                    nicspec.device = device
                    nicspec.device.macAddress = new_mac
                    nicspec.device.addressType = 'manual'
                    nicspec.device.macAddress = new_mac

                    nicspec.device.connectable = \
                        vim.vm.device.VirtualDevice.ConnectInfo()
                    nicspec.device.connectable.startConnected = True
                    nicspec.device.connectable.allowGuestControl = True
                    device_change.append(nicspec)
                    break

            config_spec = vim.vm.ConfigSpec(deviceChange=device_change)
            task = vm.ReconfigVM_Task(config_spec)
            tasks.wait_for_tasks(service_instance, [task])
            print "Successfully changed network"

        except vmodl.MethodFault as error:
            print "Caught vmodl fault : " + error.msg
            return -1
예제 #2
0
 def create_vm(self, vm_name, vm_folder, resource_pool, datastore_name):
     """
     创建一台不完整的虚拟机
     :param vm_name: 虚拟机名称
     :param vm_folder: 虚拟机文件夹
     :param resource_pool: esxi上资源池
     :param datastore_name: esxi上数据存储名称
     :return:
     """
     # 定义vm存储目录
     datastore_path = '[' + datastore_name + '] ' + vm_name
     # bare minimum VM shell, no disks. Feel free to edit
     vmx_file = vim.vm.FileInfo(logDirectory=None,
                                snapshotDirectory=None,
                                suspendDirectory=None,
                                vmPathName=datastore_path)
     # 配置vm boot配置
     config = vim.vm.ConfigSpec(
         name=vm_name,
         memoryMB=1024,
         numCPUs=4,  # 总核数
         numCoresPerSocket=2,  # 几颗CPU
         files=vmx_file,
         guestId='centos64Guest',
         version='vmx-08')
     # 创建虚拟机
     task = vm_folder.CreateVM_Task(config=config, pool=resource_pool)
     tasks.wait_for_tasks(self.si, [task])
예제 #3
0
def _take_template_snapshot(si, vm):
    if len(vm.rootSnapshot) < 1:
        task = vm.CreateSnapshot_Task(name='test_snapshot',
                                      memory=False,
                                      quiesce=False)
        tasks.wait_for_tasks(si, [task])
        print "Successfully taken snapshot of '{}'".format(vm.name)
예제 #4
0
 def renombrar(self):
     fila = self._ventana.mvTable.currentRow()
     if (fila != -1):
         obj = self._ventana.mvTable.item(fila, 1)
         uid = obj.text()
         try:
             VM = service_instance.content.searchIndex.FindByUuid(
                 None, uid, True, True)  # Objeto a borrar
             new_name = self.nombreBox.text()
             if (new_name.isalpha and new_name != ""):
                 TASK = VM.Rename(new_name)
                 tasks.wait_for_tasks(service_instance, [TASK])
                 self._ventana.refreshWindow()
                 #print("{0}".format(TASK.info.state))
                 self.exit()
                 try:
                     _correctdialog = CorrectDialog()
                     _correctdialog.exec_()
                 except:
                     pass
             else:
                 self._errorConexion = ErrorDialog()
                 self._errorConexion.lineEdit.setPlainText(
                     "Nombre introducido no es alfanumérico. ")
                 self._errorConexion.exec_()
         except:
             self._errorConexion = ErrorDialog()
             self._errorConexion.lineEdit.setPlainText(
                 "Error al buscar {0}. ".format(uid))
             self._errorConexion.exec_()
def del_nic(si, vm, nic_number):
    """ Deletes virtual NIC based on nic number
    :param si: Service Instance
    :param vm: Virtual Machine Object
    :param nic_number: Unit Number
    :return: True if success
    """
    nic_prefix_label = 'Network adapter '
    nic_label = nic_prefix_label + str(nic_number)
    virtual_nic_device = None
    for dev in vm.config.hardware.device:
        if isinstance(dev, vim.vm.device.VirtualEthernetCard)   \
                and dev.deviceInfo.label == nic_label:
            virtual_nic_device = dev

    if not virtual_nic_device:
        raise RuntimeError('Virtual {} could not be found.'.format(nic_label))

    virtual_nic_spec = vim.vm.device.VirtualDeviceSpec()
    virtual_nic_spec.operation = \
        vim.vm.device.VirtualDeviceSpec.Operation.remove
    virtual_nic_spec.device = virtual_nic_device

    spec = vim.vm.ConfigSpec()
    spec.deviceChange = [virtual_nic_spec]
    task = vm.ReconfigVM_Task(spec=spec)
    tasks.wait_for_tasks(si, [task])
    return True
예제 #6
0
 def add_nic(self, vm, network_name):
     """
     添加网卡
     :param network_name: esxi上网卡名称
     :return:
     """
     spec = vim.vm.ConfigSpec()
     nic_spec = vim.vm.device.VirtualDeviceSpec()
     nic_spec.operation = vim.vm.device.VirtualDeviceSpec.Operation.add
     nic_spec.device = vim.vm.device.VirtualVmxnet3()
     nic_spec.device.deviceInfo = vim.Description()
     nic_spec.device.backing = vim.vm.device.VirtualEthernetCard.NetworkBackingInfo(
     )
     nic_spec.device.backing.useAutoDetect = False
     nic_spec.device.backing.network = self.get_obj([vim.Network],
                                                    network_name)
     nic_spec.device.backing.deviceName = network_name
     nic_spec.device.connectable = vim.vm.device.VirtualDevice.ConnectInfo()
     nic_spec.device.connectable.startConnected = True
     nic_spec.device.connectable.startConnected = True
     nic_spec.device.connectable.allowGuestControl = True
     nic_spec.device.connectable.connected = True
     nic_spec.device.connectable.status = 'untried'
     nic_spec.device.wakeOnLanEnabled = True
     nic_spec.device.addressType = 'generated'
     spec.deviceChange = [nic_spec]
     task = vm.ReconfigVM_Task(spec=spec)
     tasks.wait_for_tasks(self.si, [task])
예제 #7
0
 def deleteVm(self):
     fila = self.mvTable.currentRow()
     if (fila != -1):
         try:
             obj = self.mvTable.item(fila, 1)
             _askdialog = AskDialog(
                 "¿Estás seguro de que desea eliminar \"" +
                 self.mvTable.item(fila, 0).text() + "\" ?")
             if (_askdialog.exec_() == QDialog.Accepted):
                 uid = obj.text()
                 try:
                     VM = service_instance.content.searchIndex.FindByUuid(
                         None, uid, True, True)  #Objeto a borrar
                     if format(VM.runtime.powerState) == "poweredOn":
                         #print("MV encendida. Apagando antes de borrar. {0}".format(VM.name))
                         TASK = VM.PowerOffVM_Task()
                         tasks.wait_for_tasks(service_instance, [TASK])
                         #print("{0}".format(TASK.info.state))
                     TASK = VM.Destroy_Task()
                     tasks.wait_for_tasks(service_instance, [TASK])
                     self.refreshWindow()
                     try:
                         _correctdialog = CorrectDialog()
                         _correctdialog.exec_()
                     except:
                         pass
                 except Exception as e:
                     self.exceptTreatment(e)
         except:
             pass
def main():
    args = get_args()
    si = SmartConnect(host=args.host, user=args.user, pwd=args.password, sslContext=context,)
    if args.datacenter:
        dc = get_dc(si, args.datacenter)
    else:
        dc = si.content.rootFolder.childEntity[0]

    vm = si.content.searchIndex.FindChild(dc.vmFolder, args.name)
    if vm is None:
        raise Exception('Failed to find VM %s in datacenter %s' %
                        (dc.name, args.name))

    # configure new telnet serial port
    serial_spec = create_telnet_serial_port(args.telnetport)

    # apply configuration changes
    dev_changes = []
    dev_changes.append(serial_spec)

    # load empty config template applicable to VMs
    spec = vim.vm.ConfigSpec()
    spec.deviceChange = dev_changes
    task = vm.ReconfigVM_Task(spec=spec)
    tasks.wait_for_tasks(si, [task])
def delete_virtual_disk(si, vm_obj, disk_number):
    """ Deletes virtual Disk based on disk number
    :param si: Service Instance
    :param vm_obj: Virtual Machine Object
    :param disk_number: Hard Disk Unit Number
    :return: True if success
    """
    hdd_prefix_label = 'Hard disk '
    hdd_label = hdd_prefix_label + str(disk_number)
    virtual_hdd_device = None
    for dev in vm_obj.config.hardware.device:
        if isinstance(dev, vim.vm.device.VirtualDisk) \
                and dev.deviceInfo.label == hdd_label:
            virtual_hdd_device = dev
    if not virtual_hdd_device:
        raise RuntimeError('Virtual {} could not '
                           'be found.'.format(virtual_hdd_device))

    virtual_hdd_spec = vim.vm.device.VirtualDeviceSpec()
    virtual_hdd_spec.operation = \
        vim.vm.device.VirtualDeviceSpec.Operation.remove
    virtual_hdd_spec.device = virtual_hdd_device

    spec = vim.vm.ConfigSpec()
    spec.deviceChange = [virtual_hdd_spec]
    task = vm_obj.ReconfigVM_Task(spec=spec)
    tasks.wait_for_tasks(si, [task])
    return True
예제 #10
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
예제 #11
0
def create_dummy_vm(name, service_instance, vm_folder, resource_pool,
                    datastore):
    """Creates a dummy VirtualMachine with 1 vCpu, 128MB of RAM.

    :param name: String Name for the VirtualMachine
    :param service_instance: ServiceInstance connection
    :param vm_folder: Folder to place the VirtualMachine in
    :param resource_pool: ResourcePool to place the VirtualMachine in
    :param datastore: DataStrore to place the VirtualMachine on
    """
    vm_name = 'MARVEL-' + name
    datastore_path = '[' + datastore + '] ' + vm_name

    # bare minimum VM shell, no disks. Feel free to edit
    vmx_file = vim.vm.FileInfo(logDirectory=None,
                               snapshotDirectory=None,
                               suspendDirectory=None,
                               vmPathName=datastore_path)

    config = vim.vm.ConfigSpec(name=vm_name,
                               memoryMB=128,
                               numCPUs=1,
                               files=vmx_file,
                               guestId='dosGuest',
                               version='vmx-07')

    print "Creating VM {}...".format(vm_name)
    task = vm_folder.CreateVM_Task(config=config, pool=resource_pool)
    tasks.wait_for_tasks(service_instance, [task])
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
예제 #13
0
def _clone_vm(si, template, vm_name, vm_folder, location):
    clone_spec = vim.vm.CloneSpec(
        powerOn=True, template=False, location=location,
        snapshot=template.snapshot.rootSnapshotList[0].snapshot)
    task = template.Clone(name=vm_name, folder=vm_folder, spec=clone_spec)
    tasks.wait_for_tasks(si, [task])
    print "Successfully cloned and created the VM '{}'".format(vm_name)
예제 #14
0
def change_disk_mode(si, vm_obj, disk_number, mode,
                     disk_prefix_label='Hard disk '):
    """Change the disk mode on a virtual hard disk.
    :param si: Service Instance
    :param vm_obj: Virtual Machine Object
    :param disk_number: Disk number.
    :param mode: New disk mode.
    :param disk_prefix_label: Prefix name of disk.
    :return: True if success
    """
    disk_label = disk_prefix_label + str(disk_number)
    virtual_disk_device = None

    # Find the disk device
    for dev in vm_obj.config.hardware.device:
        if isinstance(dev, vim.vm.device.VirtualDisk) \
                and dev.deviceInfo.label == disk_label:
            virtual_disk_device = dev
    if not virtual_disk_device:
        raise RuntimeError('Virtual {} could not be found.'.format(disk_label))

    virtual_disk_spec = vim.vm.device.VirtualDeviceSpec()
    virtual_disk_spec.operation = \
        vim.vm.device.VirtualDeviceSpec.Operation.edit
    virtual_disk_spec.device = virtual_disk_device
    virtual_disk_spec.device.backing.diskMode = mode

    dev_changes = [virtual_disk_spec]
    spec = vim.vm.ConfigSpec()
    spec.deviceChange = dev_changes
    task = vm_obj.ReconfigVM_Task(spec=spec)
    tasks.wait_for_tasks(si, [task])
    return True
예제 #15
0
def reboot_vm(args, si):
    vm = si.content.searchIndex.FindByDnsName(None, args.vmname, True)
    print("Found: {0}".format(vm.name))
    print("The current powerState is: {0}".format(vm.runtime.powerState))
    task = vm.ResetVM_Task()
    tasks.wait_for_tasks(si, [task])
    print("its done.")
예제 #16
0
def delete_vm_from_server(uuid):
    # Get Server connection
    SI = server_connection()
    if SI is None:
        return "Unable to connect to server"

    search_index = SI.content.searchIndex
    if search_index is None:
        return "Unable to grab search index"

    # Find the vm to delete
    vm = fetch_vm(uuid)

    # Verify we have a vm
    if vm is None:
        return "Unable to locate VM with UUID of " + uuid

    # Ensure VM is powered off
    if format(vm.runtime.powerState) == "poweredOn":
        TASK = vm.PowerOffVM_Task()
        # TODO: verify that this does not cause a full app wait
        tasks.wait_for_tasks(SI, [TASK])

    # Destroy vm
    TASK = vm.Destroy_Task()
    tasks.wait_for_tasks(SI, [TASK])

    return "VM is destroyed"
def create_dummy_vm(name, service_instance, vm_folder, resource_pool,
                    datastore):
    """Creates a dummy VirtualMachine with 1 vCpu, 128MB of RAM.

    :param name: String Name for the VirtualMachine
    :param service_instance: ServiceInstance connection
    :param vm_folder: Folder to place the VirtualMachine in
    :param resource_pool: ResourcePool to place the VirtualMachine in
    :param datastore: DataStrore to place the VirtualMachine on
    """
    vm_name = 'MARVEL-' + name
    datastore_path = '[' + datastore + '] ' + vm_name

    # bare minimum VM shell, no disks. Feel free to edit
    vmx_file = vim.vm.FileInfo(logDirectory=None,
                               snapshotDirectory=None,
                               suspendDirectory=None,
                               vmPathName=datastore_path)

    config = vim.vm.ConfigSpec(name=vm_name, memoryMB=128, numCPUs=1,
                               files=vmx_file, guestId='dosGuest',
                               version='vmx-07')

    print "Creating VM {}...".format(vm_name)
    task = vm_folder.CreateVM_Task(config=config, pool=resource_pool)
    tasks.wait_for_tasks(service_instance, [task])
def change_disk_mode(si, vm_obj, disk_number, mode, disk_prefix_label="Hard disk "):
    """Change the disk mode on a virtual hard disk.
    :param si: Service Instance
    :param vm_obj: Virtual Machine Object
    :param disk_number: Disk number.
    :param mode: New disk mode.
    :param disk_prefix_label: Prefix name of disk.
    :return: True if success
    """
    disk_label = disk_prefix_label + str(disk_number)
    virtual_disk_device = None

    # Find the disk device
    for dev in vm_obj.config.hardware.device:
        if isinstance(dev, vim.vm.device.VirtualDisk) and dev.deviceInfo.label == disk_label:
            virtual_disk_device = dev
    if not virtual_disk_device:
        raise RuntimeError("Virtual {} could not be found.".format(disk_label))

    virtual_disk_spec = vim.vm.device.VirtualDeviceSpec()
    virtual_disk_spec.operation = vim.vm.device.VirtualDeviceSpec.Operation.edit
    virtual_disk_spec.device = virtual_disk_device
    virtual_disk_spec.device.backing.diskMode = mode

    dev_changes = []
    dev_changes.append(virtual_disk_spec)
    spec = vim.vm.ConfigSpec()
    spec.deviceChange = dev_changes
    task = vm_obj.ReconfigVM_Task(spec=spec)
    tasks.wait_for_tasks(si, [task])
    return True
예제 #19
0
def delete_virtual_disk(si, vm_obj, disk_number):
    """ Deletes virtual Disk based on disk number
    :param si: Service Instance
    :param vm_obj: Virtual Machine Object
    :param disk_number: Hard Disk Unit Number
    :return: True if success
    """
    hdd_prefix_label = 'Hard disk '
    hdd_label = hdd_prefix_label + str(disk_number)
    virtual_hdd_device = None
    for dev in vm_obj.config.hardware.device:
        if isinstance(dev, vim.vm.device.VirtualDisk) \
                and dev.deviceInfo.label == hdd_label:
            virtual_hdd_device = dev
    if not virtual_hdd_device:
        raise RuntimeError('Virtual {} could not '
                           'be found.'.format(virtual_hdd_device))

    virtual_hdd_spec = vim.vm.device.VirtualDeviceSpec()
    virtual_hdd_spec.operation = \
        vim.vm.device.VirtualDeviceSpec.Operation.remove
    virtual_hdd_spec.device = virtual_hdd_device

    spec = vim.vm.ConfigSpec()
    spec.deviceChange = [virtual_hdd_spec]
    task = vm_obj.ReconfigVM_Task(spec=spec)
    tasks.wait_for_tasks(si, [task])
    return True
예제 #20
0
def del_nic(si, vm, nic_number):
    """ Deletes virtual NIC based on nic number
    :param si: Service Instance
    :param vm: Virtual Machine Object
    :param nic_number: Unit Number
    :return: True if success
    """
    nic_prefix_label = 'Network adapter '
    nic_label = nic_prefix_label + str(nic_number)
    virtual_nic_device = None
    for dev in vm.config.hardware.device:
        if isinstance(dev, vim.vm.device.VirtualEthernetCard)   \
                and dev.deviceInfo.label == nic_label:
            virtual_nic_device = dev

    if not virtual_nic_device:
        raise RuntimeError('Virtual {} could not be found.'.format(nic_label))

    virtual_nic_spec = vim.vm.device.VirtualDeviceSpec()
    virtual_nic_spec.operation = \
        vim.vm.device.VirtualDeviceSpec.Operation.remove
    virtual_nic_spec.device = virtual_nic_device

    spec = vim.vm.ConfigSpec()
    spec.deviceChange = [virtual_nic_spec]
    task = vm.ReconfigVM_Task(spec=spec)
    tasks.wait_for_tasks(si, [task])
    return True
def create_dummy_vm(name, service_instance, vm_folder, resource_pool,
                    datastore, mem_mb, cpu_num):
    """Creates a dummy VirtualMachine .

    :param name: String Name for the VirtualMachine
    :param service_instance: ServiceInstance connection
    :param vm_folder: Folder to place the VirtualMachine in
    :param resource_pool: ResourcePool to place the VirtualMachine in
    :param datastore: DataStrore to place the VirtualMachine on
    """
    vm_name = 'QingCloud-' + name
    datastore_path = '[' + datastore + '] ' + vm_name

    # bare minimum VM shell, no disks. Feel free to edit
    vmx_file = vim.vm.FileInfo(logDirectory=None,
                               snapshotDirectory=None,
                               suspendDirectory=None,
                               vmPathName=datastore_path)
    tools_info = vim.vm.ToolsConfigInfo(afterPowerOn=True)

    config = vim.vm.ConfigSpec(name=vm_name, memoryMB=int(mem_mb), numCPUs=int(cpu_num),
                               files=vmx_file, guestId='dosGuest',
                               version='vmx-07', tools=tools_info)

    print "Creating VM {}...".format(vm_name)
    task = vm_folder.CreateVM_Task(config=config, pool=resource_pool)
    tasks.wait_for_tasks(service_instance, [task])
예제 #22
0
def main():
    args = get_args()
    if args.date:
        try:
                dt = datetime.strptime(args.date, '%d/%m/%Y %H:%M')
        except ValueError:
                print('Unrecognized date format')
                raise
                return -1

    if args.password:
        password = args.password
    else:
        password = getpass.getpass(prompt='Enter password for host %s and '
                                   'user %s: ' % (args.host, args.user))

    # try:
    #     si = connect.SmartConnectNoSSL(host=args.host,
    #                                    user=args.user,
    #                                    pwd=password,
    #                                    port=int(args.port))
    # except vim.fault.InvalidLogin:
    #     print("Could not connect to the specified host using specified "
    #           "username and password")
    #     return -1
    si = connect.SmartConnectNoSSL(host=args.host,
                                   user=args.user,
                                   pwd=password,
                                   port=int(args.port))

    atexit.register(connect.Disconnect, si)
    # vm = None
    #
    view = si.content.viewManager.CreateContainerView(si.content.rootFolder,
                                                      [vim.VirtualMachine],
                                                      True)
    vms = [vm for vm in view.view if vm.name == args.vmname]

    if not vms:
        print('VM not found')
        connect.Disconnect(si)
        return -1
    vm = vms[0]

    # vm = si.content.searchIndex.FindByDnsName(None, args.vmname,
    #                                           True)

    # spec = vim.scheduler.ScheduledTaskSpec()
    # spec.name = 'PowerOff vm %s' % args.vmname
    # spec.description = 'poweroff vm machine'
    # spec.scheduler = vim.scheduler.OnceTaskScheduler()
    # spec.scheduler.runAt = dt
    # spec.action = vim.action.MethodAction()
    # spec.action.name = vim.VirtualMachine.PowerOff
    # spec.enabled = True

    # si.content.scheduledTaskManager.CreateScheduledTask(vm, spec)

    TASK = vm.PowerOff()
    tasks.wait_for_tasks(si, [TASK])
예제 #23
0
 def add_floppy(self, vm):
     # 查找设备控制器
     for dev in vm.config.hardware.device:
         if isinstance(dev, vim.vm.device.VirtualIDEController):
             # If there are less than 2 devices attached, we can use it.
             if len(dev.device) < 2:
                 controller = dev
             else:
                 controller = None
     spec = vim.vm.ConfigSpec()
     floppy_spec = vim.vm.device.VirtualDeviceSpec()
     floppy_spec.operation = vim.vm.device.VirtualDeviceSpec.Operation.add
     floppy_spec.device = vim.vm.device.VirtualFloppy()
     floppy_spec.device.deviceInfo = vim.Description()
     floppy_spec.device.backing = vim.vm.device.VirtualFloppy.RemoteDeviceBackingInfo(
     )
     floppy_spec.device.connectable = vim.vm.device.VirtualDevice.ConnectInfo(
     )
     floppy_spec.device.connectable.allowGuestControl = True
     floppy_spec.device.connectable.startConnected = False
     floppy_spec.device.controllerKey = controller.key
     floppy_spec.device.key = 8000
     spec.deviceChange = [floppy_spec]
     task = vm.ReconfigVM_Task(spec=spec)
     tasks.wait_for_tasks(self.si, [task])
예제 #24
0
 def powerVm(self):
     fila = self.mvTable.currentRow()
     if (fila != -1):
         obj = self.mvTable.item(fila, 1)
         uid = obj.text()
         try:
             VM = service_instance.content.searchIndex.FindByUuid(
                 None, uid, True, True)  # Objeto a borrar
             if format(VM.runtime.powerState) == "poweredOn":  #Encendida
                 #print("MV encendida. Apagando. {0}".format(VM.name))
                 TASK = VM.PowerOffVM_Task()
                 tasks.wait_for_tasks(service_instance, [TASK])
                 self.refreshWindow()
                 #print("{0}".format(TASK.info.state))
             else:  #Apagada
                 #print("MV apagada. Encendiendo. {0}".format(VM.name))
                 TASK = VM.PowerOnVM_Task()
                 tasks.wait_for_tasks(service_instance, [TASK])
                 self.refreshWindow()
                 #print("{0}".format(TASK.info.state))
             try:
                 _correctdialog = CorrectDialog()
                 _correctdialog.exec_()
             except:
                 pass
         except Exception as e:
             self.exceptTreatment(e)
예제 #25
0
def delete_vm_from_server(uuid):
    # Get Server connection
    SI = server_connection()
    if SI is None:
        return "Unable to connect to server"

    search_index = SI.content.searchIndex
    if search_index is None:
        return "Unable to grab search index"

    # Find the vm to delete
    vm = search_index.FindByUuid(None, uuid, True, True)

    # Verify we have a vm
    if vm is None:
        return "Unable to locate VM with UUID of " + uuid

    # Ensure VM is powered off
    if format(vm.runtime.powerState) == "poweredOn":
        TASK = vm.PowerOffVM_Task()
        # TODO: verify that this does not cause a full app wait
        tasks.wait_for_tasks(SI, [TASK])

    # Destroy vm
    TASK = vm.Destroy_Task()
    tasks.wait_for_tasks(SI, [TASK])

    return "VM is destroyed"
예제 #26
0
def main():
    """
    Simple command-line program for creating a first class disk.
    """

    args = get_args()

    try:
        if args.disable_ssl_verification:
            service_instance = connect.SmartConnectNoSSL(host=args.host,
                                                         user=args.user,
                                                         pwd=args.password,
                                                         port=int(args.port))
        else:
            service_instance = connect.SmartConnect(host=args.host,
                                                    user=args.user,
                                                    pwd=args.password,
                                                    port=int(args.port))

        atexit.register(connect.Disconnect, service_instance)

        content = service_instance.RetrieveContent()

        # Connect to SPBM Endpoint
        pbmSi = pbmhelper.create_pbm_session(service_instance._stub)
        pbmContent = pbmSi.RetrieveContent()

        # Retrieving Storage Policy
        if args.policy:
            policy = pbmhelper.retrieve_storage_policy(pbmContent, args.policy)
        else:
            policy = None

        # Retrieve Datastore Object
        datastore = disk.get_obj(content, [vim.Datastore], args.datastore)

        # Setting FCD Specifications
        spec = vim.vslm.CreateSpec()
        spec.name = args.name
        spec.capacityInMB = args.capacityInGB * 1024
        if args.keepAfterDeleteVm:
            spec.keepAfterDeleteVm = True
        spec.backingSpec = vim.vslm.CreateSpec.DiskFileBackingSpec()
        spec.backingSpec.provisioningType = "thin"
        spec.backingSpec.datastore = datastore
        if policy:
            spec.profile = [
                vim.vm.DefinedProfileSpec(profileId=policy.profileId.uniqueId)
            ]

        # Create FCD
        storage = content.vStorageObjectManager
        task = storage.CreateDisk_Task(spec)
        tasks.wait_for_tasks(service_instance, [task])

    except vmodl.MethodFault as error:
        print("Caught vmodl fault : " + error.msg)
        return -1

    return 0
def main():
    """
    Simple command-line program for creating a first class disk.
    """

    args = get_args()

    try:
        if args.disable_ssl_verification:
            service_instance = connect.SmartConnectNoSSL(host=args.host,
                                                         user=args.user,
                                                         pwd=args.password,
                                                         port=int(args.port))
        else:
            service_instance = connect.SmartConnect(host=args.host,
                                                    user=args.user,
                                                    pwd=args.password,
                                                    port=int(args.port))

        atexit.register(connect.Disconnect, service_instance)

        content = service_instance.RetrieveContent()

        # Connect to SPBM Endpoint
        pbmSi = pbmhelper.create_pbm_session(service_instance._stub)
        pbmContent = pbmSi.RetrieveContent()

        # Retrieving Storage Policy
        if args.policy:
            policy = pbmhelper.retrieve_storage_policy(pbmContent, args.policy)
        else:
            policy = None

        # Retrieve Datastore Object
        datastore = disk.get_obj(content, [vim.Datastore], args.datastore)

        # Setting FCD Specifications
        spec = vim.vslm.CreateSpec()
        spec.name = args.name
        spec.capacityInMB = args.capacityInGB * 1024
        if args.keepAfterDeleteVm:
            spec.keepAfterDeleteVm = True
        spec.backingSpec = vim.vslm.CreateSpec.DiskFileBackingSpec()
        spec.backingSpec.provisioningType = "thin"
        spec.backingSpec.datastore = datastore
        if policy:
            spec.profile = [vim.vm.DefinedProfileSpec(
                profileId=policy.profileId.uniqueId)]

        # Create FCD
        storage = content.vStorageObjectManager
        task = storage.CreateDisk_Task(spec)
        tasks.wait_for_tasks(service_instance, [task])

    except vmodl.MethodFault as error:
        print("Caught vmodl fault : " + error.msg)
        return -1

    return 0
예제 #28
0
파일: vms.py 프로젝트: iceworld/aci
def powerOnAll(si, VMs):
    task = []
    for vm in VMs:
        #power on machine
        try:
            task = vm.PowerOnVM_Task()
            tasks.wait_for_tasks(si, [task])
        except Exception, e:
            pass
예제 #29
0
def change_vm_pg(vmUuid):
    # Hardcoding VDS type.
    is_VDS = True
    try:
        vm = content.searchIndex.FindByUuid(None, vmUuid, True)
        # This code is for changing only one Interface. For multiple Interface
        # Iterate through a loop of network names.
        device_change = []
        for device in vm.config.hardware.device:
            if isinstance(device, vim.vm.device.VirtualEthernetCard):
                nicspec = vim.vm.device.VirtualDeviceSpec()
                nicspec.operation = \
                    vim.vm.device.VirtualDeviceSpec.Operation.edit
                nicspec.device = device
                nicspec.device.wakeOnLanEnabled = True

                if not is_VDS:
                    nicspec.device.backing = \
                        vim.vm.device.VirtualEthernetCard.NetworkBackingInfo()
                    nicspec.device.backing.network = \
                        get_obj(content, [vim.Network], sel_pg)
                    nicspec.device.backing.deviceName = sel_pg
                else:
                    network = get_obj(content, [vim.dvs.DistributedVirtualPortgroup], sel_pg)
                    dvs_port_connection = vim.dvs.PortConnection()
                    dvs_port_connection.portgroupKey = network.key
                    dvs_port_connection.switchUuid = \
                        network.config.distributedVirtualSwitch.uuid
                    nicspec.device.backing = \
                        vim.vm.device.VirtualEthernetCard. \
                        DistributedVirtualPortBackingInfo()
                    nicspec.device.backing.port = dvs_port_connection
                # moving indent to right; was aligned under 'else'.
                    nicspec.device.connectable = vim.vm.device.VirtualDevice.ConnectInfo()
                    nicspec.device.connectable.startConnected = True
                    nicspec.device.connectable.allowGuestControl = True
                    nicspec.device.connectable.connected = True
                    device_change.append(nicspec)
                    #print "DONE WITH CONNECTED SECTION"
                    break

        config_spec = vim.vm.ConfigSpec(deviceChange=device_change)
        task = vm.ReconfigVM_Task(config_spec)
        tasks.wait_for_tasks(SI, [task])
        print ">> Changed VM: %s, to Network PORT GROUP: %s " % (vm.name, sel_pg)
        print ">>> Completed."
        print ""
        print "#" * 120


    except vmodl.MethodFault as error:
        print "Caught vmodl fault : " + error.msg
        return -1

    return 0
def main():
    """
    Simple command-line program for deleting a snapshot of a first class disk.
    """

    args = get_args()

    try:
        if args.disable_ssl_verification:
            service_instance = connect.SmartConnectNoSSL(host=args.host,
                                                         user=args.user,
                                                         pwd=args.password,
                                                         port=int(args.port))
        else:
            service_instance = connect.SmartConnect(host=args.host,
                                                    user=args.user,
                                                    pwd=args.password,
                                                    port=int(args.port))

        atexit.register(connect.Disconnect, service_instance)

        content = service_instance.RetrieveContent()

        # Retrieve Datastore Object
        datastore = disk.get_obj(content, [vim.Datastore], args.datastore)

        # Retrieve FCD Object
        vdisk = disk.retrieve_fcd(content, datastore, args.vdisk)

        # Retrieve Snapshot Object
        snapshot = disk.retrieve_fcd_snapshot(
            content, datastore, vdisk, args.snapshot)

        # Confirming Snapshot deletion
        if not args.yes:
            response = cli.prompt_y_n_question("Are you sure you want to "
                                               "delete snapshot '" +
                                               args.snapshot + "'?",
                                               default='no')
            if not response:
                print("Exiting script. User chose not to delete snapshot.")
                exit()

        # Delete FCD Snapshot
        storage = content.vStorageObjectManager
        task = storage.DeleteSnapshot_Task(
            vdisk.config.id, datastore, snapshot)
        tasks.wait_for_tasks(service_instance, [task])

    except vmodl.MethodFault as error:
        print("Caught vmodl fault : " + error.msg)
        return -1

    return 0
예제 #31
0
def main():
    ARGS = GetArgs()
    CONN = None

    if ARGS.password:
        P = ARGS.password
    else:
        P = getpass.getpass(prompt='Password: '******'_create_unverified_context'):
        context = ssl._create_unverified_context()
    else:
        context = None

    try:
        CONN = SmartConnect(host=ARGS.host,
                            user=ARGS.user,
                            pwd=P,
                            port=ARGS.port,
                            sslContext=context)
        atexit.register(Disconnect, CONN)
    except IOError as ex:
        raise SystemExit("Failed connection to {0}:{1}".format(
            ARGS.host, ARGS.port))
    except vim.fault.InvalidLogin:
        raise SystemExit("{0} login failure".format(ARGS.user))

    CONTENTS = CONN.RetrieveContent()
    VMs = DISCOVER(CONTENTS)
    VMs = sorted(set(VMs))

    NOTFOUND, VMBYDISK = DISKHUNT(CONN, VMs)

    if ARGS.disks is None:
        print('Discovered datastores: ')
        for datastore, vm in VMBYDISK.iteritems():
            print('{0} contains:'.format(datastore))
            for v in vm:
                print(v.name)
            print()
    elif ARGS.disks in VMBYDISK:
        print(ARGS.disks)
        for v in VMBYDISK[ARGS.disks]:
            print("rebooting {0}".format(v.name))
            # print("{0} status: {1}".format(v.name, v.runtime.powerState))
            STATUS = str(v.runtime.powerState)
            if STATUS == 'poweredOn':
                TASK = v.ResetVM_Task()
                tasks.wait_for_tasks(CONN, [TASK])
    else:
        print('{0} was not found!'.format(ARGS.disks))
        print('Available datastores:')
        for datastore in VMBYDISK:
            print(datastore)
예제 #32
0
def main():
    """
    Simple command-line program for deleting a snapshot of a first class disk.
    """

    args = get_args()

    try:
        if args.disable_ssl_verification:
            service_instance = connect.SmartConnectNoSSL(host=args.host,
                                                         user=args.user,
                                                         pwd=args.password,
                                                         port=int(args.port))
        else:
            service_instance = connect.SmartConnect(host=args.host,
                                                    user=args.user,
                                                    pwd=args.password,
                                                    port=int(args.port))

        atexit.register(connect.Disconnect, service_instance)

        content = service_instance.RetrieveContent()

        # Retrieve Datastore Object
        datastore = disk.get_obj(content, [vim.Datastore], args.datastore)

        # Retrieve FCD Object
        vdisk = disk.retrieve_fcd(content, datastore, args.vdisk)

        # Retrieve Snapshot Object
        snapshot = disk.retrieve_fcd_snapshot(content, datastore, vdisk,
                                              args.snapshot)

        # Confirming Snapshot deletion
        if not args.yes:
            response = cli.prompt_y_n_question("Are you sure you want to "
                                               "delete snapshot '" +
                                               args.snapshot + "'?",
                                               default='no')
            if not response:
                print("Exiting script. User chose not to delete snapshot.")
                exit()

        # Delete FCD Snapshot
        storage = content.vStorageObjectManager
        task = storage.DeleteSnapshot_Task(vdisk.config.id, datastore,
                                           snapshot)
        tasks.wait_for_tasks(service_instance, [task])

    except vmodl.MethodFault as error:
        print("Caught vmodl fault : " + error.msg)
        return -1

    return 0
예제 #33
0
def update_virtual_cd_backend_by_obj(si,
                                     vm_obj,
                                     cdrom_number,
                                     full_path_to_iso=None):
    """ Updates Virtual Machine CD/DVD backend device
    :param vm_obj: virtual machine object vim.VirtualMachine
    :param cdrom_number: CD/DVD drive unit number
    :param si: Service Instance
    :param full_path_to_iso: Full path to iso
    :return: True or false in case of success or error
    """

    cdrom_prefix_label = 'CD/DVD drive '
    cdrom_label = cdrom_prefix_label + str(cdrom_number)
    virtual_cdrom_device = None
    for dev in vm_obj.config.hardware.device:
        if isinstance(dev, vim.vm.device.VirtualCdrom) \
                and dev.deviceInfo.label == cdrom_label:
            virtual_cdrom_device = dev

    if not virtual_cdrom_device:
        raise RuntimeError('Virtual {} could not '
                           'be found.'.format(cdrom_label))
    if virtual_cdrom_device.connectable.connected:
        raise RuntimeError('CDrom is connected.')

    virtual_cd_spec = vim.vm.device.VirtualDeviceSpec()
    virtual_cd_spec.operation = vim.vm.device.VirtualDeviceSpec.Operation.edit
    virtual_cd_spec.device = vim.vm.device.VirtualCdrom()
    virtual_cd_spec.device.controllerKey = virtual_cdrom_device.controllerKey
    virtual_cd_spec.device.key = virtual_cdrom_device.key
    virtual_cd_spec.device.connectable = \
        vim.vm.device.VirtualDevice.ConnectInfo()
    # if full_path_to_iso is provided it will mount the iso
    if full_path_to_iso:
        virtual_cd_spec.device.backing = \
            vim.vm.device.VirtualCdrom.IsoBackingInfo()
        virtual_cd_spec.device.backing.fileName = full_path_to_iso
        virtual_cd_spec.device.connectable.connected = True
        virtual_cd_spec.device.connectable.startConnected = True
    else:
        virtual_cd_spec.device.backing = \
            vim.vm.device.VirtualCdrom.RemotePassthroughBackingInfo()
    # Allowing guest control
    virtual_cd_spec.device.connectable.allowGuestControl = True

    dev_changes = []
    dev_changes.append(virtual_cd_spec)
    spec = vim.vm.ConfigSpec()
    spec.deviceChange = dev_changes
    task = vm_obj.ReconfigVM_Task(spec=spec)
    tasks.wait_for_tasks(si, [task])
    return True
예제 #34
0
def create_new_vm(specs):
    """Creates a dummy VirtualMachine with 1 vCpu, 128MB of RAM.
    :param name: String Name for the VirtualMachine
    :param SI: ServiceInstance connection
    :param vm_folder: Folder to place the VirtualMachine in
    :param resource_pool: ResourcePool to place the VirtualMachine in
    :param datastore: DataStrore to place the VirtualMachine on
    """
    SI = server_connection()
    content = SI.RetrieveContent()
    datacenter = content.rootFolder.childEntity[0]
    vm_folder = datacenter.vmFolder
    hosts = datacenter.hostFolder.childEntity
    resource_pool = hosts[0].resourcePool
    datastore = specs['datastore']

    vm_name = specs['name']
    datastore_path = '[' + datastore + '] ' + vm_name

    # bare minimum VM shell creation
    vmx_file = vim.vm.FileInfo(logDirectory=None, snapshotDirectory=None, suspendDirectory=None,
                               vmPathName=datastore_path)

    config = vim.vm.ConfigSpec(name=specs['name'], memoryMB=long(specs['mem']),
                               numCPUs=int(specs['cpus']), files=vmx_file,
                               guestId=specs['guestid'], version=str(specs['vm_version']))

    print("Creating VM {0}...".format(vm_name))
    task = vm_folder.CreateVM_Task(config=config, pool=resource_pool)
    tasks.wait_for_tasks(SI, [task])
    path = datastore_path + '/' + vm_name + '.vmx'

    # Verify the shell was created
    new_vm = content.searchIndex.FindByDatastorePath(datacenter, path)
    if new_vm is not None:
        # Now that the vm shell is created, add a disk to it
        # If the user requested a specific size, use that, otherwise use
        # default
        if hasattr(specs, 'disk_size'):
            add_disk(vm=new_vm, si=SI, disk_size=specs['disk_size'])
        else:
            add_disk(vm=new_vm, si=SI)

        # Add a network to the vm
        add_network(vm=new_vm, si=SI, content=content)

        # Power on the vm
        new_vm.PowerOnVM_Task()

        # Respond with the vm summary
        return print_short_detail_list(new_vm.summary)
    else:
        return "Could not create vm"
예제 #35
0
def clone_vm(content, template, si, datacenter_name, username, password,
             cluster_name, resource_pool, power_on, host_address, tem_name):
    # if none get the first one
    datacenter = get_obj(content, [vim.Datacenter], datacenter_name)
    destfolder = datacenter.vmFolder

    # if None, get the first one
    cluster = get_obj(content, [vim.ClusterComputeResource], cluster_name)

    if resource_pool:
        resource_pool = get_obj(content, [vim.ResourcePool], resource_pool)
    else:
        resource_pool = cluster.resourcePool

    vmconf = vim.vm.ConfigSpec()
    now = int(round(time.time() * 1000))
    now02 = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(now / 1000))
    my_annotation = "Here is a BOINC-deployed VM created by ProjectTides at " + now02 + " with BOINC unstarted"
    vmconf.annotation = my_annotation

    # set relospec
    relospec = vim.vm.RelocateSpec()
    relospec.datastore = None
    relospec.pool = resource_pool

    clonespec = vim.vm.CloneSpec(powerOn=power_on,
                                 template=False,
                                 location=relospec)
    clonespec.config = vmconf
    vm_name = 'tides_worker-' + ''.join(
        random.sample(string.ascii_letters + string.digits, 8))
    print("cloning VM...")
    task = template.Clone(folder=destfolder, name=vm_name, spec=clonespec)
    wait_for_task(task)
    # time.sleep(120)
    VM = get_obj(content, [vim.VirtualMachine], vm_name)
    while VM.summary.guest.ipAddress is None:
        pass
    print(VM.summary.guest.ipAddress)
    send_account(host_address, VM.summary.guest.ipAddress, tem_name, username,
                 password)

    spec = vim.vm.ConfigSpec()
    old_ann = VM.summary.config.annotation
    now = int(round(time.time() * 1000))
    now02 = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(now / 1000))
    annotation_add = "started at " + now02
    print(old_ann)
    spec.annotation = old_ann.replace("unstarted", annotation_add)

    task = VM.ReconfigVM_Task(spec)
    tasks.wait_for_tasks(si, [task])
    print("Done.")
예제 #36
0
 def kill(self, VM):
     print("Found: {0}".format(VM.name))
     print("The current powerState is: {0}".format(VM.runtime.powerState))
     if format(VM.runtime.powerState) == "poweredOn":
         print("Attempting to power off {0}".format(VM.name))
         TASK = VM.PowerOffVM_Task()
         tasks.wait_for_tasks(self.si, [TASK])
         print("{0}".format(TASK.info.state))
     else:
         TASK = VM.PowerOnVM_Task()
         tasks.wait_for_tasks(self.si, [TASK])
         print("{0}".format(TASK.info.state))
예제 #37
0
def create_vm(name, si, vm_folder, resource_pool, datastore, network):
    vm_name = name
    datastore_path = "[" + datastore + "]/" + vm_name + "/" + vm_name + ".vmx"
    vmx_file = vim.vm.FileInfo(logDirectory=None,
                               snapshotDirectory=None,
                               suspendDirectory=None,
                               vmPathName=datastore_path)
    configspec = vim.vm.ConfigSpec(name=vm_name,
                                   memoryMB=int(guest['ramsize']),
                                   numCPUs=int(guest['vcpus']),
                                   guestId=guest['guestID'],
                                   version=guest['version'],
                                   files=vmx_file,
                                   cpuHotAddEnabled=True,
                                   memoryHotAddEnabled=True)
    ##添加虚拟设备nic
    nic_spec = vim.vm.device.VirtualDeviceSpec()
    nic_spec.operation = vim.vm.device.VirtualDeviceSpec.Operation.add
    nic_spec.device = vim.vm.device.VirtualE1000()
    nic_spec.device.deviceInfo = vim.Description()
    nic_spec.device.backing = \
     vim.vm.device.VirtualEthernetCard.NetworkBackingInfo()
    nic_spec.device.backing.useAutoDetect = False
    content = si.RetrieveContent()
    nic_spec.device.backing.network = get_obj(content, [vim.Network], network)
    nic_spec.device.backing.deviceName = network
    nic_spec.device.connectable = vim.vm.device.VirtualDevice.ConnectInfo()
    nic_spec.device.connectable.startConnected = True
    nic_spec.device.connectable.allowGuestControl = True
    nic_spec.device.connectable.connected = False
    nic_spec.device.connectable.status = 'untried'
    nic_spec.device.wakeOnLanEnabled = True
    nic_spec.device.addressType = 'assigned'
    configspec.deviceChange.append(nic_spec)
    print("网卡添加成功")
    ##添加sisc控制器
    scsictl_spec = vim.vm.device.VirtualDeviceSpec()
    scsictl_spec.operation = vim.vm.device.VirtualDeviceSpec.Operation.add
    scsictl_spec.device = vim.vm.device.VirtualLsiLogicController()
    scsictl_spec.device.deviceInfo = vim.Description()
    scsictl_spec.device.slotInfo = vim.vm.device.VirtualDevice.PciBusSlotInfo()
    scsictl_spec.device.slotInfo.pciSlotNumber = 16
    scsictl_spec.device.controllerKey = 100
    scsictl_spec.device.unitNumber = 3
    scsictl_spec.device.busNumber = 0
    scsictl_spec.device.hotAddRemove = True
    scsictl_spec.device.sharedBus = 'noSharing'
    scsictl_spec.device.scsiCtlrUnitNumber = 7
    configspec.deviceChange.append(scsictl_spec)
    print("scsi控制器添加成功")
    print("Creating VM{}...".format(vm_name))
    task = vm_folder.CreateVM_Task(config=configspec, pool=resource_pool)
    tasks.wait_for_tasks(si, [task])
예제 #38
0
def main():
    """
    Let this thing fly
    """
    args = get_args()

    # connect this thing
    si = vmware_lib.connect(args.host, args.user, args.password, args.port,
                            args.insecure)
    content = si.RetrieveContent()

    if args.vm:
        if args.cold_migrate:
            vm = vmware_lib.get_obj(content, [vmware_lib.vim.VirtualMachine],
                                    args.vm)
            if vm.runtime.powerState == 'poweredOn':
                print 'Powering off {}'.format(args.vm)
                task = vm.PowerOffVM_Task()
                tasks.wait_for_tasks(si, [task])

        print 'Migrating VM'
        result = vmware_lib.migrate_vm(content,
                                       args.vm,
                                       rebalance=False,
                                       limit=90)
        if args.cold_migrate:
            print 'Powering on VM'
            task = vm.PowerOnVM_Task()
            tasks.wait_for_tasks(si, [task])
        return result

    if args.esxi_host:
        host = vmware_lib.get_obj(content, [vmware_lib.vim.HostSystem],
                                  args.esxi_host)
        if host:
            if args.migrate_vms:
                vmware_lib.migrate_host_vms(content, host, args.skip,
                                            args.rebalance, args.limit)

            if args.maintenance_mode or args.maintenance_mode == False:
                vmware_lib.maintenance_mode(host, args.maintenance_mode)
            if args.reboot:
                print 'Rebooting {}'.format(host.name)
                vmware_lib.wait_for_task(host.Reboot(force=False))
            if args.reconnect:
                vmware_lib.reconnect_host(host, args.host_user,
                                          args.host_password)
        else:
            print 'Cannot find host {}'.format(args.esxi_host)
            sys.exit(1)
def update_virtual_cd_backend_by_obj(si, vm_obj, cdrom_number,
                                     full_path_to_iso=None):
    """ Updates Virtual Machine CD/DVD backend device
    :param vm_obj: virtual machine object vim.VirtualMachine
    :param cdrom_number: CD/DVD drive unit number
    :param si: Service Instance
    :param full_path_to_iso: Full path to iso
    :return: True or false in case of success or error
    """

    cdrom_prefix_label = 'CD/DVD drive '
    cdrom_label = cdrom_prefix_label + str(cdrom_number)
    virtual_cdrom_device = None
    for dev in vm_obj.config.hardware.device:
        if isinstance(dev, vim.vm.device.VirtualCdrom) \
                and dev.deviceInfo.label == cdrom_label:
            virtual_cdrom_device = dev

    if not virtual_cdrom_device:
        raise RuntimeError('Virtual {} could not '
                           'be found.'.format(cdrom_label))

    virtual_cd_spec = vim.vm.device.VirtualDeviceSpec()
    virtual_cd_spec.operation = vim.vm.device.VirtualDeviceSpec.Operation.edit
    virtual_cd_spec.device = vim.vm.device.VirtualCdrom()
    virtual_cd_spec.device.controllerKey = virtual_cdrom_device.controllerKey
    virtual_cd_spec.device.key = virtual_cdrom_device.key
    virtual_cd_spec.device.connectable = \
        vim.vm.device.VirtualDevice.ConnectInfo()
    # if full_path_to_iso is provided it will mount the iso
    if full_path_to_iso:
        virtual_cd_spec.device.backing = \
            vim.vm.device.VirtualCdrom.IsoBackingInfo()
        virtual_cd_spec.device.backing.fileName = full_path_to_iso
        virtual_cd_spec.device.connectable.connected = True
        virtual_cd_spec.device.connectable.startConnected = True
    else:
        virtual_cd_spec.device.backing = \
            vim.vm.device.VirtualCdrom.RemotePassthroughBackingInfo()
    # Allowing guest control
    virtual_cd_spec.device.connectable.allowGuestControl = True

    dev_changes = []
    dev_changes.append(virtual_cd_spec)
    spec = vim.vm.ConfigSpec()
    spec.deviceChange = dev_changes
    task = vm_obj.ReconfigVM_Task(spec=spec)
    tasks.wait_for_tasks(si, [task])
    return True
def main():
    """
    Simple command-line program for attaching a first class disk to a vm.
    """

    args = get_args()

    try:
        if args.disable_ssl_verification:
            service_instance = connect.SmartConnectNoSSL(host=args.host,
                                                         user=args.user,
                                                         pwd=args.password,
                                                         port=int(args.port))
        else:
            service_instance = connect.SmartConnect(host=args.host,
                                                    user=args.user,
                                                    pwd=args.password,
                                                    port=int(args.port))

        atexit.register(connect.Disconnect, service_instance)

        content = service_instance.RetrieveContent()

        # Retrieve Datastore Object
        datastore = disk.get_obj(content, [vim.Datastore], args.datastore)

        # Retrieve FCD Object
        vdisk = disk.retrieve_fcd(content, datastore, args.vdisk)

        # Retrieve VM
        vm = None
        if args.uuid:
            search_index = content.searchIndex
            vm = search_index.FindByUuid(None, args.uuid, True)
        elif args.vm_name:
            vm = disk.get_obj(content, [vim.VirtualMachine], args.vm_name)

        # Attaching FCD to VM
        if vm:
            task = attach_fcd_to_vm(vm, vdisk, datastore)
            tasks.wait_for_tasks(service_instance, [task])
        else:
            raise RuntimeError("VM not found.")

    except vmodl.MethodFault as error:
        print("Caught vmodl fault : " + error.msg)
        return -1

    return 0
예제 #41
0
def _clone_vm(si, template, vm_name, vm_folder, location):

    #Get the name of current snapshot
    current_snap_obj = get_current_snap_obj(template.snapshot.rootSnapshotList,
                                            template.snapshot.currentSnapshot)
    print("Will use current snapshot named '{}'".format(
        current_snap_obj[0].name))

    clone_spec = vim.vm.CloneSpec(powerOn=True,
                                  template=False,
                                  location=location,
                                  snapshot=template.snapshot.currentSnapshot)
    task = template.Clone(name=vm_name, folder=vm_folder, spec=clone_spec)
    tasks.wait_for_tasks(si, [task])
    print("Successfully cloned and created the VM '{}'".format(vm_name))
def update_virtual_nic_state(si, vm_obj, nic_number, new_nic_state):
    """
    :param si: Service Instance
    :param vm_obj: Virtual Machine Object
    :param nic_number: Network Interface Controller Number
    :param new_nic_state: Either Connect, Disconnect or Delete
    :return: True if success
    """
    nic_prefix_label = 'Network adapter '
    nic_label = nic_prefix_label + str(nic_number)
    virtual_nic_device = None
    for dev in vm_obj.config.hardware.device:
        if isinstance(dev, vim.vm.device.VirtualEthernetCard) \
                and dev.deviceInfo.label == nic_label:
            virtual_nic_device = dev
    if not virtual_nic_device:
        raise RuntimeError('Virtual {} could not be found.'.format(nic_label))

    virtual_nic_spec = vim.vm.device.VirtualDeviceSpec()
    virtual_nic_spec.operation = \
        vim.vm.device.VirtualDeviceSpec.Operation.remove \
        if new_nic_state == 'delete' \
        else vim.vm.device.VirtualDeviceSpec.Operation.edit
    virtual_nic_spec.device = virtual_nic_device
    virtual_nic_spec.device.key = virtual_nic_device.key
    virtual_nic_spec.device.macAddress = virtual_nic_device.macAddress
    virtual_nic_spec.device.backing = virtual_nic_device.backing
    virtual_nic_spec.device.backing.port = \
        virtual_nic_device.backing.port
    virtual_nic_spec.device.wakeOnLanEnabled = \
        virtual_nic_device.wakeOnLanEnabled
    connectable = vim.vm.device.VirtualDevice.ConnectInfo()
    if new_nic_state == 'connect':
        connectable.connected = True
        connectable.startConnected = True
    elif new_nic_state == 'disconnect':
        connectable.connected = False
        connectable.startConnected = False
    else:
        connectable = virtual_nic_device.connectable
    virtual_nic_spec.device.connectable = connectable
    dev_changes = []
    dev_changes.append(virtual_nic_spec)
    spec = vim.vm.ConfigSpec()
    spec.deviceChange = dev_changes
    task = vm_obj.ReconfigVM_Task(spec=spec)
    tasks.wait_for_tasks(si, [task])
    return True
예제 #43
0
def create_scsi_controller(vm, si):
    spec = vim.vm.ConfigSpec()
    dev_changes = []
    controller_spec = vim.vm.device.VirtualDeviceSpec()
    controller_spec.operation = vim.vm.device.VirtualDeviceSpec.Operation.add
    controller_spec.device = vim.vm.device.VirtualLsiLogicController()
    controller_spec.device.sharedBus = vim.vm.device.VirtualSCSIController.Sharing.noSharing
    dev_changes.append(controller_spec)
    spec.deviceChange = dev_changes
    task = []
    task.append(vm.ReconfigVM_Task(spec=spec))
    tasks.wait_for_tasks(si, task)
    for dev in vm.config.hardware.device:
        if isinstance(dev, vim.vm.device.VirtualSCSIController):
            print("Found our controller")
            return dev
예제 #44
0
def change_vm_stats(uuid, specs):
    # Get server object
    SI = server_connection()

    # Find the vm to change
    VM = SI.content.searchIndex.FindByUuid(None, uuid, True, True)

    if 'cpu' in specs:
        task = VM.ReconfigVM_Task(vim.vm.ConfigSpec(numCPUs=int(specs['cpu'])))
        tasks.wait_for_tasks(SI, [task])

    if 'mem' in specs:
        task = VM.ReconfigVM_Task(
            vim.vm.ConfigSpec(memoryMB=long(specs['mem'])))
        tasks.wait_for_tasks(SI, [task])

    return "I fixed it!"
def addPropertiesToVM(si, vm, options_values):
    spec = vim.vm.ConfigSpec()
    opt = vim.option.OptionValue()
    spec.extraConfig = []

    for k, v in options_values.iteritems():
        opt.key = k
        opt.value = v
        spec.extraConfig.append(opt)
        opt = vim.option.OptionValue()

    task = vm.ReconfigVM_Task(spec)
    tasks.wait_for_tasks(si, [task])
    print("Done setting values.")
    print("time to get them")
    keys_and_vals = vm.config.extraConfig
    for opts in keys_and_vals:
        print("key: {0} => {1}".format(opts.key, opts.value))
    print("done.")
def main():
    """
    Simple command-line program for detaching a disk from a virtual machine.
    """

    args = get_args()

    try:
        if args.disable_ssl_verification:
            service_instance = connect.SmartConnectNoSSL(host=args.host,
                                                         user=args.user,
                                                         pwd=args.password,
                                                         port=int(args.port))
        else:
            service_instance = connect.SmartConnect(host=args.host,
                                                    user=args.user,
                                                    pwd=args.password,
                                                    port=int(args.port))

        atexit.register(connect.Disconnect, service_instance)

        content = service_instance.RetrieveContent()

        # Retrieve VM
        vm = None
        if args.uuid:
            search_index = content.searchIndex
            vm = search_index.FindByUuid(None, args.uuid, True)
        elif args.vm_name:
            vm = disk.get_obj(content, [vim.VirtualMachine], args.vm_name)

        # Detaching Disk from VM
        if vm:
            task = detach_disk_from_vm(vm, args.disknumber, args.language)
            tasks.wait_for_tasks(service_instance, [task])
        else:
            raise RuntimeError("VM not found.")

    except vmodl.MethodFault as error:
        print("Caught vmodl fault : " + error.msg)
        return -1

    return 0
예제 #47
0
def add_network(vm, si, content, netName="VM Network"):
    spec = vim.vm.ConfigSpec()
    dev_changes = []
    network_spec = vim.vm.device.VirtualDeviceSpec()
    network_spec.operation = vim.vm.device.VirtualDeviceSpec.Operation.add
    network_spec.device = vim.vm.device.VirtualVmxnet3()
    # network_spec.device.addressType = "GeneratedAutomatically"
    print("Getting a network...")
    # Get network type
    for net in content.rootFolder.childEntity[0].network:
        if net.name == netName:
            if isinstance(net, vim.dvs.DistributedVirtualPortgroup):
                # Run portgroup code
                pg_obj = get_obj(
                    content, [vim.dvs.DistributedVirtualPortgroup], netName)
                dvs_port_connection = vim.dvs.PortConnection()
                dvs_port_connection.portgroupKey = pg_obj.key
                dvs_port_connection.switchUuid = pg_obj.config.distributedVirtualSwitch.uuid
                network_spec.device.backing = vim.vm.device.VirtualEthernetCard.DistributedVirtualPortBackingInfo()
                network_spec.device.backing.port = dvs_port_connection
                break
            elif isinstance(net, vim.Network):
                # Run plain network code
                network_spec.device.backing = vim.vm.device.VirtualEthernetCard.NetworkBackingInfo()
                network_spec.device.backing.network = get_obj(
                    content, [vim.Network], netName)
                network_spec.device.backing.deviceName = netName
                break
            else:
                print("This name is not a network")

    # Allow the network card to be hot swappable
    network_spec.device.connectable = vim.vm.device.VirtualDevice.ConnectInfo()
    network_spec.device.connectable.startConnected = True
    network_spec.device.connectable.allowGuestControl = True

    dev_changes.append(network_spec)
    spec.deviceChange = dev_changes
    task = []
    task.append(vm.ReconfigVM_Task(spec=spec))
    tasks.wait_for_tasks(si, task)
def main():
    args = get_args()

    context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
    context.verify_mode = ssl.CERT_NONE

    service_instance = connect.SmartConnect(host=args.host,
                                            user=args.user,
                                            pwd=args.password,
                                            port=int(args.port),
                                            sslContext=context)
    if not service_instance:
        print("Unable to connect with the vCenter Server "
              "using the provided credentials")
        return -1

    atexit.register(connect.Disconnect, service_instance)

    content = service_instance.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_host:
            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(service_instance, [task])
    print "Operation complete"

    return 0
def main():
    """
    Simple command-line program for changing network virtual machines NIC
    that includes NSX-T opeque switch.
    """

    args = get_args()
    sslContext = None

    if args.disable_ssl_verification:
        sslContext = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
        sslContext.verify_mode = ssl.CERT_NONE

    try:
        service_instance = connect.SmartConnect(host=args.host,
                                                user=args.user,
                                                pwd=args.password,
                                                port=int(args.port),
                                                sslContext=sslContext)
        if not service_instance:
            print("Could not connect to the specified host using specified "
                  "username and password")
            return -1

        atexit.register(connect.Disconnect, service_instance)
        content = service_instance.RetrieveContent()
        vm = get_obj(content, [vim.VirtualMachine], args.vm_name)
        # This code is for changing only one Interface. For multiple Interface
        # Iterate through a loop of network names.
        device_change = []
        for device in vm.config.hardware.device:
            if isinstance(device, vim.vm.device.VirtualEthernetCard):
                nicspec = vim.vm.device.VirtualDeviceSpec()
                nicspec.operation = \
                    vim.vm.device.VirtualDeviceSpec.Operation.edit
                nicspec.device = device
                nicspec.device.wakeOnLanEnabled = True

                # NSX-T Logical Switch
                if isinstance(get_obj(content,
                                      [vim.Network],
                                      args.network_name), vim.OpaqueNetwork):
                    network = \
                        get_obj(content, [vim.Network], args.network_name)
                    nicspec.device.backing = \
                        vim.vm.device.VirtualEthernetCard. \
                        OpaqueNetworkBackingInfo()
                    network_id = network.summary.opaqueNetworkId
                    network_type = network.summary.opaqueNetworkType
                    nicspec.device.backing.opaqueNetworkType = network_type
                    nicspec.device.backing.opaqueNetworkId = network_id

                # vSphere Distributed Virtual Switch
                elif hasattr(get_obj(content,
                                     [vim.Network],
                                     args.network_name), 'portKeys'):
                    network = get_obj(content,
                                      [vim.dvs.DistributedVirtualPortgroup],
                                      args.network_name)
                    dvs_port_connection = vim.dvs.PortConnection()
                    dvs_port_connection.portgroupKey = network.key
                    dvs_port_connection.switchUuid = \
                        network.config.distributedVirtualSwitch.uuid
                    nicspec.device.backing = \
                        vim.vm.device.VirtualEthernetCard. \
                        DistributedVirtualPortBackingInfo()
                    nicspec.device.backing.port = dvs_port_connection

                # vSphere Standard Switch
                else:
                    nicspec.device.backing = \
                        vim.vm.device.VirtualEthernetCard.NetworkBackingInfo()
                    nicspec.device.backing.network = \
                        get_obj(content, [vim.Network], args.network_name)
                    nicspec.device.backing.deviceName = args.network_name

                nicspec.device.connectable = \
                    vim.vm.device.VirtualDevice.ConnectInfo()
                nicspec.device.connectable.startConnected = True
                nicspec.device.connectable.allowGuestControl = True
                nicspec.device.connectable.connected = True
                device_change.append(nicspec)
                break

        config_spec = vim.vm.ConfigSpec(deviceChange=device_change)
        task = vm.ReconfigVM_Task(config_spec)
        tasks.wait_for_tasks(service_instance, [task])
        print("Successfully changed network")

    except vmodl.MethodFault as error:
        print("Caught vmodl fault : " + error.msg)
        return -1

    return 0
예제 #50
0
def create_new_vm(specs):
    """Creates a dummy VirtualMachine with 1 vCpu, 128MB of RAM.
    :param name: String Name for the VirtualMachine
    :param SI: ServiceInstance connection
    :param vm_folder: Folder to place the VirtualMachine in
    :param resource_pool: ResourcePool to place the VirtualMachine in
    :param datastore: DataStrore to place the VirtualMachine on
    """
    SI = server_connection()
    content = SI.RetrieveContent()
    datastore = specs['datastore']

    print("Finding the resource pool")
    # Find the api resource pool
    datacenters = content.rootFolder.childEntity
    loopbreak = False
    for dc in datacenters:
        for host in dc.hostFolder.childEntity:
            for pool in host.resourcePool.resourcePool:
                if pool.name == resource_pool_name:
                    resource_pool = pool
                    datacenter = dc
                    print("Got the resource pool and dc...")
                    loopbreak = True
                    break
            if loopbreak:
                break
        if loopbreak:
            break

    # Find the api vm folder
    for folder in datacenter.vmFolder.childEntity:
        if folder.name == vm_folder_name:
            print("Got the vm folder...")
            vm_folder = folder
            break

    vm_name = specs['name']
    datastore_path = '[' + datastore + '] ' + vm_name

    # bare minimum VM shell creation
    vmx_file = vim.vm.FileInfo(logDirectory=None, snapshotDirectory=None, suspendDirectory=None,
                               vmPathName=datastore_path)

    config = vim.vm.ConfigSpec(name=specs['name'], memoryMB=long(specs['mem']),
                               numCPUs=int(specs['cpus']), files=vmx_file,
                               guestId=specs['guestid'], version=str(specs['vm_version']))

    # Add custom tags
    config.extraConfig = []
    opt = vim.option.OptionValue()
    options_values = {}
    # if hasattr(specs, "user"):
    if 'user' in specs:
        print("Got user: {0}".format(specs['user']))
        options_values.update({"User": specs['user']})
    # if hasattr(specs, "language"):
    if 'language' in specs:
        print("Got language: {0}".format(specs['language']))
        options_values.update({"Language": specs['language']})
    if 'application' in specs:
        print("Got application: {0}".format(specs['application']))
        options_values.update({"Application": specs['application']})

    for k, v in options_values.iteritems():
        opt.key = k
        opt.value = v
        config.extraConfig.append(opt)
        opt = vim.option.OptionValue()

    # Send off creeation task
    print("Creating VM {0}...".format(vm_name))
    task = vm_folder.CreateVM_Task(config=config, pool=resource_pool)
    print("Sending to the text manager")
    tasks.wait_for_tasks(SI, [task])
    print("Done...now to find it...")
    path = datastore_path + '/' + vm_name + '.vmx'

    # Verify the shell was created
    new_vm = content.searchIndex.FindByDatastorePath(datacenter, path)
    if new_vm is not None:
        # Now that the vm shell is created, add a disk to it
        # If the user requested a specific size, use that, otherwise use
        # default
        print("Found it...now adding a disk...")
        if hasattr(specs, 'disk_size'):
            add_disk(vm=new_vm, si=SI, disk_size=specs['disk_size'])
        else:
            add_disk(vm=new_vm, si=SI)

        # Add a network to the vm
        print("...adding the network...")
        add_network(vm=new_vm, si=SI, content=content)

        # Power on the vm
        print("...and powering it on!")
        new_vm.PowerOnVM_Task()

        # Respond with the vm summary
        return print_short_detail_list(new_vm)
    else:
        return "Could not create vm"
예제 #51
0
            # Create VMDK file
            disk_filename = datastore_path + '/' + deploy_settings["new_vm_name"] + '-' + str(key + 1) + '.vmdk'
            capacity_kb = int(size) * 1024 * 1024 # Size in arg is in GB 

            disk_manager = content.virtualDiskManager

            disk_spec = vim.VirtualDiskManager.FileBackedVirtualDiskSpec()
            #disk_spec.diskType = 'eagerZeroedThick'
            disk_spec.diskType = 'preallocated'
            disk_spec.adapterType = 'lsiLogic'
            disk_spec.capacityKb = capacity_kb

            # VMDK Creation 
            print "Creating VMDK {}...".format(disk_filename)
            task2 = disk_manager.CreateVirtualDisk(disk_filename, datacenter, disk_spec)
            tasks.wait_for_tasks(si, [task2])

            # Connect additionals disks  to the VM

            # Get the newly created VM
            vmxfile = datastore_path + '/' + deploy_settings["new_vm_name"] + '.vmx'
            search = content.searchIndex
            vm = search.FindByDatastorePath(datacenter, vmxfile)

            # Get controller SCSI  
            controller = None
            devices = vm.config.hardware.device
            for device in devices:
                if 'SCSI controller 0' in device.deviceInfo.label:
                    controller = device
    pass

if not SI:
    raise SystemExit("Unable to connect to host with supplied info.")
VM = None
if ARGS.uuid:
    VM = SI.content.searchIndex.FindByUuid(None, ARGS.uuid,
                                           True,
                                           True)
elif ARGS.name:
    VM = SI.content.searchIndex.FindByDnsName(None, ARGS.name,
                                              True)
elif ARGS.ip:
    VM = SI.content.searchIndex.FindByIp(None, ARGS.ip, True)

if VM is None:
    raise SystemExit("Unable to locate VirtualMachine.")

print("Found: {0}".format(VM.name))
print("The current powerState is: {0}".format(VM.runtime.powerState))
if format(VM.runtime.powerState) == "poweredOn":
    print("Attempting to power off {0}".format(VM.name))
    TASK = VM.PowerOffVM_Task()
    tasks.wait_for_tasks(SI, [TASK])
    print("{0}".format(TASK.info.state))

print("Destroying VM from vSphere.")
TASK = VM.Destroy_Task()
tasks.wait_for_tasks(SI, [TASK])
print("Done.")
spec = vim.vm.ConfigSpec()
opt = vim.option.OptionValue()
spec.extraConfig = []

options_values = {
    "custom_key1": "Ive tested very large xml and json, and base64 values here"
                   " and they work",
    "custom_key2": "Ive tested very large xml and json, and base64 values here"
                   " and they work",
    "custom_key3": "Ive tested very large xml and json, and base64 values here"
                   " and they work",
    "custom_key4": "Ive tested very large xml and json, and base64 values here"
                   " and they work"
}

for k, v in options_values.iteritems():
    opt.key = k
    opt.value = v
    spec.extraConfig.append(opt)
    opt = vim.option.OptionValue()

task = vm.ReconfigVM_Task(spec)
tasks.wait_for_tasks(si, [task])
print("Done setting values.")
print("time to get them")
keys_and_vals = vm.config.extraConfig
for opts in keys_and_vals:
    print("key: {0} => {1}".format(opts.key, opts.value))
print("done.")
def main():
    """
    Simple command-line program for changing network virtual machines NIC.
    """

    args = get_args()

    try:
        service_instance = connect.SmartConnect(host=args.host,
                                                user=args.user,
                                                pwd=args.password,
                                                port=int(args.port))

        atexit.register(connect.Disconnect, service_instance)
        content = service_instance.RetrieveContent()
        vm = content.searchIndex.FindByUuid(None, args.vm_uuid, True)
        # This code is for changing only one Interface. For multiple Interface
        # Iterate through a loop of network names.
        device_change = []
        for device in vm.config.hardware.device:
            if isinstance(device, vim.vm.device.VirtualEthernetCard):
                nicspec = vim.vm.device.VirtualDeviceSpec()
                nicspec.operation = \
                    vim.vm.device.VirtualDeviceSpec.Operation.edit
                nicspec.device = device
                nicspec.device.wakeOnLanEnabled = True

                if not args.is_VDS:
                    nicspec.device.backing = \
                        vim.vm.device.VirtualEthernetCard.NetworkBackingInfo()
                    nicspec.device.backing.network = \
                        get_obj(content, [vim.Network], args.network_name)
                    nicspec.device.backing.deviceName = args.network_name
                else:
                    network = get_obj(content,
                                      [vim.dvs.DistributedVirtualPortgroup],
                                      args.network_name)
                    dvs_port_connection = vim.dvs.PortConnection()
                    dvs_port_connection.portgroupKey = network.key
                    dvs_port_connection.switchUuid = \
                        network.config.distributedVirtualSwitch.uuid
                    nicspec.device.backing = \
                        vim.vm.device.VirtualEthernetCard. \
                        DistributedVirtualPortBackingInfo()
                    nicspec.device.backing.port = dvs_port_connection

                nicspec.device.connectable = \
                    vim.vm.device.VirtualDevice.ConnectInfo()
                nicspec.device.connectable.startConnected = True
                nicspec.device.connectable.allowGuestControl = True
                device_change.append(nicspec)
                break

        config_spec = vim.vm.ConfigSpec(deviceChange=device_change)
        task = vm.ReconfigVM_Task(config_spec)
        tasks.wait_for_tasks(service_instance, [task])
        print "Successfully changed network"

    except vmodl.MethodFault as error:
        print "Caught vmodl fault : " + error.msg
        return -1

    return 0
예제 #55
0
파일: shell.py 프로젝트: someCorp/pyvshell
    def do_start(self, host):
        """
        Start all VM's on vCenter or ESXi given a uuid file.
        It will ask you an username and valid password.
        Usage example and output:
                                                                               
        (Cmd) start esxi.domain.tld uuidon.txt
        Please enter your username: root


        You can check if it is powered on or not.

        (Cmd) ls esxi.domain.tld on
        Please enter your username: root
        Password: 
        ----------------------------------------------------------------------
        Name:                    DC0_C1_RP0_VM0
        Instance UUID:           503b382f-0ec4-b961-9461-883e0c759b31
        CPUs:                    1
        MemoryMB:                64
        Guest PowerState:        poweredOn
        Guest Full Name:         Microsoft Windows Server 2003 Standard (32-bit)
        Guest Container Type:    winNetStandardGuest
        Container Version:       vmx-07
                                                                               
        """
                                                                               
        self.host = host
        args = host.split()
                                                                               
        if len(args) == 2:
            try:

                user = input("Please enter your username: "******"Password: "******"{0} Its already powered On!!".format(line))


            except vmodl.MethodFault as e:
                print("Caught vmodl fault : ", e)
                return 0


                                                                               
        if len(args) == 1:
            try:
                print("Please enter a file containing uuid to power on!!")

                                                                               
            except vmodl.MethodFault as e:
                print("Caught vmodl fault : ", e)
                return 0
                                                                               
        if len(args) == 0:
            print("Please provide a hostname or IP address")
예제 #56
0
def create_vm(name, service_instance, vm_folder, resource_pool,datastore):
    vm_name = 'VM-' + name
    datastore_path = '[' + datastore + '] ' + vm_name

    # bare minimum VM shell, no disks. Feel free to edit
    vmx_file = vim.vm.FileInfo(logDirectory=None,
                               snapshotDirectory=None,
                               suspendDirectory=None,
                               vmPathName=datastore_path)
    
    spec = vim.vm.ConfigSpec()
    scsi_ctr = vim.vm.device.VirtualDeviceSpec()
    scsi_ctr.operation = vim.vm.device.VirtualDeviceSpec.Operation.add
    scsi_ctr.device = vim.vm.device.VirtualLsiLogicController()
    scsi_ctr.device.deviceInfo = vim.Description()
    scsi_ctr.device.slotInfo = vim.vm.device.VirtualDevice.PciBusSlotInfo()
    scsi_ctr.device.slotInfo.pciSlotNumber = 16
    scsi_ctr.device.controllerKey = 100
    scsi_ctr.device.unitNumber = 3
    scsi_ctr.device.busNumber = 0
    scsi_ctr.device.hotAddRemove = True
    scsi_ctr.device.sharedBus = 'noSharing'
    scsi_ctr.device.scsiCtlrUnitNumber = 7

    unit_number = 0
    controller = scsi_ctr.device
    disk_spec = vim.vm.device.VirtualDeviceSpec()
    disk_spec.fileOperation = "create"
    disk_spec.operation = vim.vm.device.VirtualDeviceSpec.Operation.add
    disk_spec.device = vim.vm.device.VirtualDisk()
    disk_spec.device.backing = vim.vm.device.VirtualDisk.FlatVer2BackingInfo()
    disk_spec.device.backing.thinProvisioned = True
    disk_spec.device.backing.diskMode = 'persistent'
    disk_spec.device.backing.fileName = '%s.vmdk'% vm_name
    disk_spec.device.unitNumber = unit_number
    disk_spec.device.capacityInKB = 1 * 1024 * 1024
    disk_spec.device.controllerKey = controller.key

    #nicspec = vim.vm.ConfigSpec()
    nic_spec = vim.vm.device.VirtualDeviceSpec()
    nic_spec.operation = vim.vm.device.VirtualDeviceSpec.Operation.add
    nic_spec.device = vim.vm.device.VirtualE1000()
    nic_spec.device.deviceInfo = vim.Description()
    nic_spec.device.deviceInfo.summary = 'vCenter API'
    nic_spec.device.backing = vim.vm.device.VirtualEthernetCard.NetworkBackingInfo()
    nic_spec.device.backing.useAutoDetect = False
    nic_spec.device.backing.deviceName = "VM Network"
    #nic_spec.deivce.connectable = vim.vm.device.VirtualDevice.ConnectInfo()
    #nic_spec.device.connectable.startConnected = True
    #nic_spec.device.connectable.allowGuestControl = True
    #nic_spec.device.connectable.connected = False
    #nic_spec.device.connectable.status = 'untried'
    #nic_spec.device.wakeOnLanEnabled = True
    #nic_spec.device.addressType = 'assigned'
    #nic_spec.device.macAddress = mac

    dev_changes = []
    dev_changes.append( scsi_ctr )
    dev_changes.append( disk_spec )
    dev_changes.append( nic_spec )
#    spec.deviceChange = dev_changes

    
 
 
    config = vim.vm.ConfigSpec( 
                                name=vm_name, 
                                memoryMB=128, 
                                numCPUs=1,
                                files=vmx_file, 
				deviceChange=dev_changes,
                                guestId='dosGuest', 
                                version='vmx-07'
                              )

    print "Creating VM {} ...".format(vm_name)
    task = vm_folder.CreateVM_Task(config=config, pool=resource_pool)
    tasks.wait_for_tasks(service_instance, [task])
예제 #57
0
def dvs_quarantine():
    HOST = '10.67.16.198'
    USER = '******'
    PASSWORD = '******'
    PORT = '443'
    VM_UUIDS = ['423ae3f6-bd80-31ad-1d30-55dbbd5e4c35',
                '423aa622-08dc-5560-39dd-01c13e7a550b',
                '423af213-8013-f397-0114-bec8172ec008']

    NETWORK_NAME = 'quarantine'
    is_VDS = True

    try:
        service_instance = connect.SmartConnect(host=HOST,
                                                user=USER,
                                                pwd=PASSWORD,
                                                port=int(PORT))

        atexit.register(connect.Disconnect, service_instance)
        content = service_instance.RetrieveContent()

        for VM_UUID in VM_UUIDS :
            #if VM_UUID == LB:
            #    NETWORK_NAME = 'BB-9|Universe-App|load-balancer'

            vm = content.searchIndex.FindByUuid(None, VM_UUID, True)
            # This code is for changing only one Interface. For multiple Interface
            # Iterate through a loop of network names.
            device_change = []
            for device in vm.config.hardware.device:
                if isinstance(device, vim.vm.device.VirtualEthernetCard):
                    nicspec = vim.vm.device.VirtualDeviceSpec()
                    nicspec.operation = \
                        vim.vm.device.VirtualDeviceSpec.Operation.edit
                    nicspec.device = device
                    nicspec.device.wakeOnLanEnabled = True

                    if not is_VDS:
                        nicspec.device.backing = \
                            vim.vm.device.VirtualEthernetCard.NetworkBackingInfo()
                        nicspec.device.backing.network = \
                            get_obj(content, [vim.Network], NETWORK_NAME)
                        nicspec.device.backing.deviceName = NETWORK_NAME
                    else:
                        network = get_obj(content,
                                          [vim.dvs.DistributedVirtualPortgroup],
                                          NETWORK_NAME)
                        dvs_port_connection = vim.dvs.PortConnection()
                        dvs_port_connection.portgroupKey = network.key
                        dvs_port_connection.switchUuid = \
                            network.config.distributedVirtualSwitch.uuid
                        nicspec.device.backing = \
                            vim.vm.device.VirtualEthernetCard. \
                            DistributedVirtualPortBackingInfo()
                        nicspec.device.backing.port = dvs_port_connection

                    nicspec.device.connectable = \
                        vim.vm.device.VirtualDevice.ConnectInfo()
                    #nicspec.device.connectable.connected = True
                    nicspec.device.connectable.startConnected = True
                    nicspec.device.connectable.allowGuestControl = True
                    device_change.append(nicspec)
                    break

            config_spec = vim.vm.ConfigSpec(deviceChange=device_change)
            task = vm.ReconfigVM_Task(config_spec)
            tasks.wait_for_tasks(service_instance, [task])
            print "Successfully migrated instance",VM_UUID,"to",NETWORK_NAME

    except vmodl.MethodFault as error:
        print "Caught vmodl fault : " + error.msg
        return -1

    return 0
예제 #58
0
def create_vm(name, service_instance, vm_folder, resource_pool,
                    datastore,memSize, nbSockets, nbCores, vlan):
    """Creates a VirtualMachine.

    :param name: String Name for the VirtualMachine
    :param service_instance: ServiceInstance connection
    :param vm_folder: Folder to place the VirtualMachine in
    :param resource_pool: ResourcePool to place the VirtualMachine in
    :param datastore: DataStrore to place the VirtualMachine on
    :param memSize: Desired size of memory for the VirtualMachine
    :param nbSockets: Desired number of sockets for the VirtualMachine
    :param nbCores: Desired number of core by sockets for the VirtualMachine
    :param vlan: Name of Network to connect the VirtualMachine on

    """
    content = service_instance.RetrieveContent()

    vm_name = name

    dc = get_obj(content, [vim.Datacenter], 'FARMAN')

    datastore_path = '[' + datastore + '] ' + vm_name

    disk_filename = datastore_path + '/' + vm_name + '.vmdk'

    devices = [] 

    adaptermaps = []

    vmx_file = vim.vm.FileInfo(logDirectory=None,
                               snapshotDirectory=None,
                               suspendDirectory=None,
                               vmPathName=datastore_path)

    config = vim.vm.ConfigSpec(name=vm_name, memoryMB=int(memSize), numCPUs=int(nbSockets),
                               numCoresPerSocket=int(nbCores), files=vmx_file, guestId='centos64Guest',
                               version='vmx-10')

    # Configuring network interface
    nic = vim.vm.device.VirtualDeviceSpec()
    nic.operation = vim.vm.device.VirtualDeviceSpec.Operation.add # Add device
    nic.device = vim.vm.device.VirtualVmxnet3() # Define device type
    nic.device.wakeOnLanEnabled = True
    nic.device.addressType = 'assigned' # Vcenter assigne a MAC address
    nic.device.key = 4000  # 4000 seems to be the value to use for a vmxnet3 device
    nic.device.deviceInfo = vim.Description()
    nic.device.deviceInfo.label = "Network Adapter 0"
    nic.device.deviceInfo.summary = vlan
    nic.device.backing = vim.vm.device.VirtualEthernetCard.NetworkBackingInfo()
    nic.device.backing.network = get_obj(content, [vim.Network], vlan) # Connect to the correct network
    nic.device.backing.deviceName = vlan # Set name of the interface
    nic.device.backing.useAutoDetect = False
    nic.device.connectable = vim.vm.device.VirtualDevice.ConnectInfo()
    nic.device.connectable.startConnected = True
    nic.device.connectable.allowGuestControl = True
    devices.append(nic) # Add the nic to the device config


    # Create SCSI controller
    lsi = vim.vm.device.VirtualDeviceSpec()
    lsi.operation = vim.vm.device.VirtualDeviceSpec.Operation.add # Add device
    lsi.device = vim.vm.device.VirtualLsiLogicController() # Define device type
    lsi.device.sharedBus = vim.vm.device.VirtualSCSIController.Sharing.noSharing # Set sharing mode
    lsi.device.scsiCtlrUnitNumber = 0 # Set SCSI Ctrl unit number
    devices.append(lsi) # Add the SCSI controller to the device config


    # Apply change configuration NIC + SCSI controller
    config.deviceChange = devices

    # Vm Creation
    print "Creating VM {}...".format(vm_name)
    task = vm_folder.CreateVM_Task(config=config, pool=resource_pool)
    tasks.wait_for_tasks(service_instance, [task])


    # Create VMDK file
    disk_path = datastore_path + '/' + vm_name + '.vmdk'
    capacity_kb = 1 * 1024 * 1024 # 10Go
    
    disk_manager = content.virtualDiskManager

    disk_spec = vim.VirtualDiskManager.FileBackedVirtualDiskSpec()
    #disk_spec.diskType = 'eagerZeroedThick'
    disk_spec.diskType = 'preallocated'
    disk_spec.adapterType = 'lsiLogic'
    disk_spec.capacityKb = capacity_kb

    # VMDK Creation 
    print "Creating VMDK {}...".format(disk_path)
    task2 = disk_manager.CreateVirtualDisk(disk_path, dc, disk_spec)
    tasks.wait_for_tasks(service_instance, [task2])


    # Connect VMDK  to the VM

    # Get the newly created VM
    vmxfile = datastore_path + '/' + vm_name + '.vmx'
    search = content.searchIndex
    vm = search.FindByDatastorePath(dc, vmxfile)

    # Get controller SCSI  
    controller = None
    devices = vm.config.hardware.device
    for device in devices:
        if 'SCSI' in device.deviceInfo.label:
            controller = device

    # Define the disk
    disk = vim.vm.device.VirtualDisk()
    disk.backing = vim.vm.device.VirtualDisk.FlatVer2BackingInfo()
    disk.backing.diskMode = 'persistent'
    disk.backing.thinProvisioned = False
    #disk.backing.eagerlyScrub = True
    disk.backing.eagerlyScrub = False
    disk.backing.fileName = disk_filename

    disk.connectable = vim.vm.device.VirtualDevice.ConnectInfo()
    disk.connectable.startConnected = True
    disk.connectable.allowGuestControl = False
    disk.connectable.connected = True

    disk.key = -100
    disk.controllerKey = controller.key # id of scsi controller
    disk.unitNumber = len(controller.device) # number of SCSI device
    
    
    # Create disk's spec
    device_spec = vim.vm.device.VirtualDiskSpec()
    device_spec.operation = vim.vm.device.VirtualDeviceSpec.Operation.add
    device_spec.device = disk

    spec = vim.vm.ConfigSpec()
    spec.deviceChange = [device_spec]

    # Reconfigure VM 
    task3 = vm.ReconfigVM_Task(spec)
    tasks.wait_for_tasks(service_instance, [task3])