用Python从命令行控制VirtualBox

1 投票
2 回答
2723 浏览
提问于 2025-04-15 19:35

我们正在使用 Python 的 VirtualBox API 来控制 VirtualBox。为此,我们使用了 "pyvb" 这个包(在 Python API 文档中有说明)。

al=pyvb.vb.VB()
m=pyvb.vm.vbVM()
al.startVM(m)

我们已经通过 Python 解释器执行了代码。没有出现错误,但 VirtualBox 并没有启动。你能告诉我们可能出什么问题了吗?(所有必要的模块和包都已经导入)

2 个回答

1

引用的代码似乎没有说明要运行哪个虚拟机(VM)。你是不是应该先调用一下 getVM,然后在你的 startVM 调用中使用得到的虚拟机实例呢?比如:

al=pyvb.vb.VB()
m=al.getVM(guid_of_vm)
al.startVM(m)

...这段代码会启动用给定的GUID标识的虚拟机(所有的VirtualBox虚拟机在创建时都会分配一个GUID)。你可以从虚拟机的XML文件中获取这个GUID。如果你需要在运行时发现虚拟机,可以使用很方便的 listVMS 调用:

al=pyvb.vb.VB()
l=al.listVMS()
# choose a VM from the list, assign to 'm'
al.startVM(m)
4

我发现可以使用以下函数来检查虚拟机(VM)是否在运行,恢复虚拟机到某个特定的快照,以及通过名称启动虚拟机。

from subprocess import Popen, PIPE

    def running_vms():
        """
        Return list of running vms
        """
        f = Popen(r'vboxmanage --nologo list runningvms', stdout=PIPE).stdout
        data = [ eachLine.strip() for eachLine in f ]
        return data

    def restore_vm(name='', snapshot=''):
        """
        Restore VM to specific snapshot uuid

        name = VM Name
        snapshot = uuid of snapshot  (uuid can be found in the xml file of your machines folder)
        """
        command = r'vboxmanage --nologo snapshot %s restore %s' % (name,snapshot)
        f = Popen(command, stdout=PIPE).stdout
        data = [ eachLine.strip() for eachLine in f ]
        return data

    def launch_vm(name=''):
        """
        Launch VM

        name = VM Name
        """
        command = r'vboxmanage --nologo startvm %s ' % name
        f = Popen(command, stdout=PIPE).stdout
        data = [ eachLine.strip() for eachLine in f ]
        return data

撰写回答