A Couple of Handy Scripts to Manage VirtualBox Virtual Machines

Thu, May 9, 2013 2-minute read

I have a server running several virtual machines with Virtual Box. Yesterday I configured an UPS on that server and I had the need to write a pair of scripts:

  • one to save the state of the running virtual machines when there is a power outage and
  • another to bring them back to a running state when the power is available again.

Luckily VirtualBox has an handy command line tool (VBoxManage) to manage the virtual machines and I’ve been able to exploit it to do my job.

Please note that these scripts run on Mac OS X. If your server is a Linux box you have to use the vboxmanage command instead of VBoxManage.

Saving virtual machines states

With this code we can save the state of each running virtual machine.

VMS=`VBoxManage list runningvms | awk '/{*}/ NF{gsub(/[{}]/,""); print $NF}'`
rm ./runningvms.txt
for vm in $VMS
do
  VBoxManage controlvm $vm savestate
  echo $vm >> ./runningvms.txt
done

The first line simply gets the list of the running virtual machines from the VBoxManage, parses the output to get the identifiers of each running virtual machine. Then, at line two, I delete the old copy of the file in which I’ll store the identifiers of the virtual machines stopped by the script. Finally the for loop properly invokes VBoxManage and saves the identifier of the stopped virtual machine to a file.

Restoring stopped virtual machines

With this code we can start again the virtual machines we stopped with the other script.

while read vm
do
  VBoxManage startvm $vm --type headless
done < runningvms.txt
echo "" > ./runningvms.txt

The loop reads each line of the runningvms.txt file, which contains the identifiers of the virtual machine we want to restore, and simply asks VBoxManage to start the vm.

Since I am running on a server I don’t need the GUI of VirtualBox, so I used the --type headless command line switch.