Child pages
  • Hyper-V WMI Example Code
Skip to end of metadata
Go to start of metadata

Python WMI Commands to Hyper-V Server

Соединение с сервером Hyper-V, запрос провайдера виртуализации:

>>> c = wmi.WMI(computer='Brahma', namespace='Root\\virtualization', user='Administrator', password='P@ssw0rd')Формирование запроса на показ виртуалок под Hyper-V и засылка на сервер:
>>> wql = "select * from Msvm_ComputerSystem where Caption=\"Virtual Machine\""
>>> for vm in c.query(wql):

#Вычленить название виртуалок:
>>> wql = "select ElementName from Msvm_ComputerSystem where Caption=\"Virtual Machine\""
>>> for vm in c.query(wql):


A script which detects whether the machine that the script is run on is a virtual machine or a physical machine

import wmi
def sys_info():
objWMIService = wmi.GetObject(r"winmgmts:\root\cimv2")
     colItems = objWMIService.ExecQuery("Select * from Win32_BaseBoard")
for objItem in colItems:
         print "inside"
         Manufacturer = objItem.Manufacturer
         if Manufacturer == "Microsoft Corporation":
             print "Virtual Machine"
             print "Not in one"

win32com.client hack

Using win32com.client and rewrapping it using wmi._wmi_object() after setting properties works correctly.

HDobj = win32com.client.Dispatch("WbemScripting.SWbemLocator")\
HDobj.Address = 30
HD = wmi._wmi_object(HDobj)

--------------------import wmi
c = wmi.WMI(namespace="virtualization", find_classes=False)
VMMS = c.Msvm_VirtualSystemManagementService()-1
HD = c.Msvm_ResourceAllocationSettingData(InstanceID='Microsoft:Definition
HD.Address = 0
VMMS.AddVirtualSystemResources(HD.gettext_(1),, VM)


import wmi
c = wmi.WMI("hostname", namespace="virtualization", find_classes=False)
VM = c.Msvm_ComputerSystem(ElementName="vmname")-1
DiskPool = c.Msvm_ResourcePool(ResourceType=22,ResourceSubtype="Microsoft Physical Disk Drive")-1
Disks = DiskPool.associators(wmi_result_class="Msvm_DiskDrive")
Disk = d for d in Disks if d.DriveNumber==100
VSSDs = VM.associators(wmi_result_class="Msvm_VirtualSystemSettingData")
VSSD = v for v in VSSDs if v.SettingType==30
SCSIs = VSSD.associators(wmi_result_class="Msvm_ResourceAllocationSettingData")
SCSI = s for s in SCSIs if s.ResourceType==60
AC = c.Msvm_AllocationCapabilities(ResourceType=22,ResourceSubtype="Microsoft Physical Disk Drive")-1
Default = c.Msvm_SettingsDefineCapabilities(ValueRange=0,GroupComponent=AC.Path_.Path)-1
Problematic section
HD = Default.PartComponent
HD.Address = "100"
HD.Parent = SCSI.Path_.Path
HD.HostResource= DISK.Path_.Path
VMMS.AddVirtualSystemResources(VM, HD.gettext_(1),)