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]])
它崩溃。
我的问题:
为什么我没有WMI对象?
第二个参数显然是错误的。 MSDN表示需要CIM_VirtualSystemSettingData REF SettingData[]
作为参数。 WMI对象是错误的对象吗?如何获得正确的参数?
我如何从COM对象中检索所需的信息?
还是我完全走错了路?
谢谢,孙燕姿
所以,我终于找到了解决方案。这比我想象的要容易得多,但是无论如何:
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