在操作VM的過程,經常有需要把所有本地端主機上的所有 VM都打開或是關機,有了Python API,我們可以建立一個簡單的程式,使用listAllDomains把所有的domain都找出來放在一個串列中,然後分別以create()和shutdown()這兩個方法來打開或是關閉每一個domain(虛擬機)。

程式碼如下所示:

#! /usr/bin/python
import libvirt
import sys

if len(sys.argv)<2:
  print "Usage: vmturn on/off"
  exit(1)
command = sys.argv[1]
conn = libvirt.open("qemu:///system")
allvm = conn.listAllDomains()
for vm in allvm:
  if command == 'on':
    try:      vm.create()
    except:   continue
  if command == 'off':
    try:    vm.shutdown()
    except:  continue
conn.close()

你可以把這個程式命名為 vmturn(不用副檔名),然後設定成可執行檔,複製到/usr/sbin中,以後只要想一口氣打開所有的VM,只要執行 vmturn on就可以了,當然,要關閉所有的VM,也是只要使用 vmturn off。輸入其它的參數都不會有任何的作用。

除了create()和shutdown()這兩個方法函數之外,可以操作domain的方法還有如下所示的這麼多種,有興趣的朋友可以自己試試看喔:

‘abortJob’, ‘attachDevice’, ‘attachDeviceFlags’, ‘autostart’, ‘blkioParameters’, ‘blockCommit’, ‘blockCopy’, ‘blockInfo’, ‘blockIoTune’, ‘blockJobAbort’, ‘blockJobInfo’, ‘blockJobSetSpeed’, ‘blockPeek’, ‘blockPull’, ‘blockRebase’, ‘blockResize’, ‘blockStats’, ‘blockStatsFlags’, ‘connect’, ‘controlInfo’, ‘coreDump’, ‘coreDumpWithFormat’, ‘create’, ‘createWithFiles’, ‘createWithFlags’, ‘destroy’, ‘destroyFlags’, ‘detachDevice’, ‘detachDeviceFlags’, ‘diskErrors’, ’emulatorPinInfo’, ‘fSTrim’, ‘fsFreeze’, ‘fsThaw’, ‘getCPUStats’, ‘getTime’, ‘hasCurrentSnapshot’, ‘hasManagedSaveImage’, ‘hostname’, ‘info’, ‘injectNMI’, ‘interfaceParameters’, ‘interfaceStats’, ‘isActive’, ‘isPersistent’, ‘isUpdated’, ‘jobInfo’, ‘jobStats’, ‘listAllSnapshots’, ‘managedSave’, ‘managedSaveRemove’, ‘maxMemory’, ‘maxVcpus’, ‘memoryParameters’, ‘memoryPeek’, ‘memoryStats’, ‘metadata’, ‘migrate’, ‘migrate2’, ‘migrate3’, ‘migrateGetCompressionCache’, ‘migrateGetMaxSpeed’, ‘migrateSetCompressionCache’, ‘migrateSetMaxDowntime’, ‘migrateSetMaxSpeed’, ‘migrateToURI’, ‘migrateToURI2’, ‘migrateToURI3’, ‘name’, ‘numaParameters’, ‘openChannel’, ‘openConsole’, ‘openGraphics’, ‘openGraphicsFD’, ‘pMSuspendForDuration’, ‘pMWakeup’, ‘pinEmulator’, ‘pinVcpu’, ‘pinVcpuFlags’, ‘reboot’, ‘reset’, ‘resume’, ‘revertToSnapshot’, ‘save’, ‘saveFlags’, ‘schedulerParameters’, ‘schedulerParametersFlags’, ‘schedulerType’, ‘screenshot’, ‘securityLabel’, ‘securityLabelList’, ‘sendKey’, ‘sendProcessSignal’, ‘setAutostart’, ‘setBlkioParameters’, ‘setBlockIoTune’, ‘setInterfaceParameters’, ‘setMaxMemory’, ‘setMemory’, ‘setMemoryFlags’, ‘setMemoryParameters’, ‘setMemoryStatsPeriod’, ‘setMetadata’, ‘setNumaParameters’, ‘setSchedulerParameters’, ‘setSchedulerParametersFlags’, ‘setTime’, ‘setVcpus’, ‘setVcpusFlags’, ‘shutdown’, ‘shutdownFlags’, ‘snapshotCreateXML’, ‘snapshotCurrent’, ‘snapshotListNames’, ‘snapshotLookupByName’, ‘snapshotNum’, ‘state’, ‘suspend’, ‘undefine’, ‘undefineFlags’, ‘updateDeviceFlags’, ‘vcpuPinInfo’, ‘vcpus’, ‘vcpusFlags’

(44)