Go to content Go to menu

Managing Virtualbox VM’s with Python

Tuesday, August 23, 2016

vboxpython.png Have you ever wanted to automate Virtualbox VM’s using the vboxapi Python bindings? Then you might have also read the SDK documentation PDF (e.g. for 5.1.4 here). There are just some few lines on working with Python and sometimes not everything seems clear (at least not to me). So in this post I show some sample which provided me some troubles while working on a project lately.

Suppose you want to change network adapter settings on a VM (especially when VM is running). You need a session object to get a “lock” to the VM. depending on if the VM is running or stopped this is done in two different ways.
 
 
Example 1: disconnect cable of network adapter 2 of stopped VM

import vboxapi
vboxMgr = vboxapi.VirtualBoxManager(None, None)
vbox = vboxMgr.vbox
# 'example-vm' is the name of the VM we want to change
vm = vbox.findMachine('example-vm')
session = vboxMgr.getSessionObject(vbox)
try:
    vm.lockMachine(session, vboxMgr.constants.LockType_Write)
    net = session.machine.getNetworkAdapter(2)
    net.cableConnected = False
    session.machine.saveSettings()
except Exception as err:
    print err.__doc__
    print err.message
finally:
    session.unlockMachine()

Ensure that you always unlock the VM event in case of an error. If you run this code against a running VM it will throw an exception when acquiring the lock to the VM.
 
 
Example 1: disconnect cable of network adapter 2 of a running VM

import vboxapi
vboxMgr = vboxapi.VirtualBoxManager(None, None)
vbox = vboxMgr.vbox
# 'example-vm' is the name of the VM we want to change
vm = vbox.findMachine('example-vm')
session = vboxMgr.openMachineSession(vm)
try:
    net = session.machine.getNetworkAdapter(2)
    net.cableConnected = False
    session.machine.saveSettings()
except Exception as err:
    print err.__doc__
    print err.message
finally:
    session.unlockMachine()

As you can see for a running VM you will only need vboxMgr.openMachineSession(vm) whereas for a stopped VM vboxMgr.getSessionObject(vbox) and vm.lockMachine(session, vboxMgr.constants.LockType_Write) is needed.

It is also possible to reconnect a network adapter to a different network during runtime which makes it possible to automate some network test scenarios like roaming a VM as mobile client from one network to another.
 
 
Example 3: reconnect interface 1 of a running VM to a host internal network vboxnet3

import vboxapi
vboxMgr = vboxapi.VirtualBoxManager(None, None)
vbox = vboxMgr.vbox
vm = vbox.findMachine('example-vm')
session = vboxMgr.openMachineSession(vm)
try:
    net = session.machine.getNetworkAdapter(1)
    net.hostOnlyInterface = 'vboxnet3'
    session.machine.saveSettings()
except Exception as err:
    print err.__doc__
    print err.message
finally:
    session.unlockMachine()

Maybe this samples are usefull for others.