Manage VirtualBox with PHP

Jan 4, 2020 by Thibault Debatty | 3751 views

PHP

https://cylab.be/blog/49/manage-virtualbox-with-php

phpVirtualBox is a well known web interface for managing virtual machines. There is however another less known library that allows to manage virtual machines from your own PHP applications : php-vbox-api. The API allows you to do stuff like:

$vbox = new VBox($username, $password);

// a single .ova may contain multiple machines
$vms = $vbox->import("/path/to/image.ova");
$vm = $vms[0];

$vm->setMemorySize(512); // MB
$vm->setCPUCount(2);

$adapter = $vm->getNetworkAdapter(0);
$adapter->setAttachmentType(NetworkAdapter::ATTACHEMENT_BRIDGED);
$adapter->setBridgedInterface("eno1");

$vm->up();
$vm->reset();
$vm->destroy();

Installation

The library itself is best installed using composer:

composer require cylab/php-vbox-api

VirtualBox Web Service

You will of course have to download and install VirtualBox.

In VirtualBox, each virtual machine is a separate user process. So it is usually best to create a dedicated user for running your VM's :

sudo adduser vbox

Then add this new user to the vbox group so it will be allowed to run virtual machines :

sudo adduser vbox vbox

Finally, you have to activate the VirtualBox Web Service.

Therefore, you have to create the file /etc/default/virtualbox and indicate which user should be used to run your machines:

VBOXWEB_USER=vbox

You can now start the VirtualBox Web Service:

sudo service vboxweb-service restart

By default the web service will be listening on port 18083 :

Usage

Connecting to VirtualBox

$vbox = new VBox("vbox", "passord-of-vbox-user");

List all machines

$vms = $vbox->allVMs();
foreach ($vms as $vm) {
  echo $vm->getName() . "
";
  echo $vm->getUUID() . "
";
}

Modify a VM

$vm = $vbox->findVM("name or UUID");

// do a clean shutdown
$vm->halt();
$vm->setMemory(2048);
$vm->setCPUCount(4);
$vm->up();

// do a hard shutdown
$vm->kill();

// destroy the VM
$vm->destroy();

You can find more examples on https://gitlab.cylab.be/cylab/php-vbox-api

This blog post is licensed under CC BY-SA 4.0

This website uses cookies. More information about the use of cookies is available in the cookies policy.
Accept