VirtualBox Python API 恢复快照

3 投票
2 回答
2742 浏览
提问于 2025-04-16 13:24

我正在尝试通过SDK提供的vboxapi来管理一些虚拟机。到目前为止,我已经成功启动了虚拟机并将其关闭,但我无法恢复快照。看起来关闭虚拟机的过程会锁定虚拟机,直到脚本执行完毕,实际上我遇到的错误就是这个:

    progress = self.session.console.restoreSnapshot(self.mach.currentSnapshot)
  File "", line 3, in restoreSnapshot
xpcom.Exception: 0x80070005 (The object is not ready)

接下来是我依次调用的具体函数,用来停止虚拟机和恢复快照。

    def stop(self):
        if self.mach:
            # Poweroff the virtual machine.
            progress = self.session.console.powerDown()
            # Wait for task to complete with a 60 seconds timeout.
            progress.waitForCompletion(VIRTUALBOX_TIMEOUT)
            # Check if poweroff was successful.
            if progress.resultCode != 0:
                log("[Virtual Machine] [PowerOff] [ERROR] Unable to poweroff virtual machine \"%s\"." % self.mach.name)
                return False
            else:
                log("[Virtual Machine] [PowerOff] Virtual machine \"%s\" powered off successfully." % self.mach.name)
        else:
            log("[Virtual Machine] [PowerOff] [ERROR] No virtual machine handle.")
            return False

        return True

    def restore_snapshot(self):
        if self.mach:
            # Restore virtual machine snapshot.
            progress = self.session.console.restoreSnapshot(self.mach.currentSnapshot)
            # Wait for task to complete with a 60 seconds timeout.
            progress.waitForCompletion(VIRTUALBOX_TIMEOUT)
            # Check if snapshot restoring was successful.
            if progress.resultCode != 0:
                log("[Virtual Machine] [Restore Snapshot] [ERROR] Unable to restore virtual machine \"%s\" snapshot." % self.mach.name)
                return False
            else:
                log("[Virtual Machine] [Restore Snapshot] Virtual machine \"%s\" successfully restored to current snashot." % self.mach.name)
        else:
            log("[Virtual Machine] [Restore Snapshot] [ERROR] No virtual machine handle.")
            return False

        return True

我觉得我可能漏掉了什么,有没有什么线索可以帮我?谢谢,C。

2 个回答

0

你需要先锁定机器,这样控制台对象才能为你创建出来。

2

如果你把机器关掉了,想要恢复之前的快照,就得重新创建一个 IConsole 对象。在你的代码里,可以在恢复快照之前加上这些代码。

def restore_snapshot(self):
    if self.mach:
         self.mach.lockMachine(self.session,1)
         console = self.session.console
         progress = console.restoreSnapshot(self.mach.currentSnapshot)

在 SDK 里:当一台机器被锁定用于某个特定的会话(客户端进程)时,会创建一个控制台对象,这个锁定是通过 IMachine::lockMachine() 或 IMachine::launchVMProcess() 来实现的。

推特 @dsanchezlavado

撰写回答