views:

234

answers:

2

We are using python virtualbox API for controlling the virtualbox. For that we are using the "pyvb" package(as given in python API documentation).

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

we have executed using the python interpreter. No error is shown but the virtualbox doesnt start. Could you please tell us what could be wrong(all necessary modules and packages have been imported)

A: 

The code quoted doesn't seem to specify what VM to run. Shouldn't you be doing a getVM call and then using that resulting VM instance in your startVM call? E.g.:

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

...would start the VM identified with the given GUID (all VirtualBox VMs have a GUID assigned when they're created). You can get the GUID from the VM's XML file. If you need to discover VMs at runtime, there's the handy listVMS call:

al=pyvb.vb.VB()
l=al.listVMS()
# choose a VM from the list, assign to 'm'
al.startVM(m)
T.J. Crowder
we tried it, but got a few errors like:Traceback(most recent call last):File "<stdin>",line1,<in module>File "/usr/lib/python2.5/site-packages/pyvb-0.0.2-py2.5.egg/pyvb/vb.py",line 65,in startVM cmd='%s %s'%(VB_COMMAND_STARTVM,vm.getUUID())AttributeError:'NoneType' Object has no attribute 'getUUID'.please help us out.
ask
Thanks for ur quick responsebut what we actually need is to execute those commands using python virtualbox API.
ask
@ask: Sorry, I figured since VirtualBox supports using a name instead of a GUID in its command-line tools, the python lib would as well, but the `getVM` method says it requires a GUID. Blech. Updated the answer for that and to call attention to the `listVMS` method.
T.J. Crowder
+1  A: 

I found that I can use the following functions to find if a VM is running, restore a VM to a specific snapshot, and start a VM by name.

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
Ted Hosmann