[使用Python控制Hyper-V VM

问题描述 投票:1回答:1

im试图使用Python在HyperV服务器上编写控制VM。我首先连接到运行HyperV服务器的服务器:

connection = wmi.connect_server(server="servername", namespace=r"root\virtualization", user=r"username", password=r"password")
wmiServerConnection = wmi.WMI(wmi=connection)

这为我提供了用于此连接的wmi对象。

为了停止和启动VM,我可以简单地使用:

#get the wmi object representing the VM
vmSystem = wmiServerConnection.Msvm_ComputerSystem(ElementName="VmName")
#send change request to vm
vmSystem[0].RequestStateChange(3)

但是在启动VM之前,我想应用某个快照。Msvm_VirtualSystemManagementService类为此提供了一种方法ApplyVirtualSystemSnapshot / ApplyVirtualSystemSnapshotEx。它需要SnapshotSettingData作为参数,我想我可以使用同一类的GetSummaryInformation方法获得该参数。 MSDN说此方法返回一个Msvm_SummaryInformation类。

我这样称呼此功能:

#get the wmi class object
vmManagement = wmiServerConnection.Msvm_VirtualSystemManagementService()
snapshotInfo = vmManagement[0].GetSummaryInformation([1,107])

这应该为我提供HyperV服务器上所有VM的名称和快照信息。但是我得到的只是COM对象列表。

[当我尝试给某个虚拟机作为从中获得的参数时

vmSettings = wmiServerConnection.Msvm_VirtualSystemSettingData(ElementName="VmName")

喜欢这样

snapshotInfo = vmManagement[0].GetSummaryInformation([1,107], [vmSettings[0]])

它崩溃。

我的问题:

  1. 为什么我没有WMI对象?

  2. 第二个参数显然是错误的。 MSDN表示需要CIM_VirtualSystemSettingData REF SettingData[]作为参数。 WMI对象是错误的对象吗?如何获得正确的参数?

  3. 我如何从COM对象中检索所需的信息?

还是我完全走错了路?

谢谢,孙燕姿

python wmi hyper-v
1个回答
5
投票

所以,我终于找到了解决方案。这比我想象的要容易得多,但是无论如何:

1。连接到服务器并获取WMI对象:

connection = wmi.connect_server(server=serverName, namespace=r"root\virtualization", user=username, password=password)
wmiServerConnection = wmi.WMI(wmi=connection)

2。获取系统对象和管理服务对象:

#get object representing VM
vmSystem = wmiServerConnection.Msvm_ComputerSystem(ElementName=VmName)
#get object responsible for VM
vmManagement = wmiServerConnection.Msvm_VirtualSystemManagementService()

3。获取与VM关联的对象:

#get objects the VM contains
    vmObjects = vmSystem[0].associators(wmi_result_class="Msvm_VirtualSystemSettingData ")

4。应用所需的快照:

for singleVmObject in vmObjects:    
    if(singleVmObject.SettingType == 5 and singleVmObject.ElementName == snapshotName):
        retVal = vmManagement[0].ApplyVirtualSystemSnapshotEx(vmSystem[0].path(), singleVmObject.path())

可以在这里找到更多文档:

http://timgolden.me.uk/python/wmi/wmi.html

http://msdn.microsoft.com/en-us/library/cc136986(v=vs.85).aspx

© www.soinside.com 2019 - 2024. All rights reserved.