VirtualBox Auto Start VM Centos Fedora RedHat

Scenario / Question:

How do I get my VirtualBox Guest VM’s to start and stop when the host system reboots, shutdown, or starts.

Solution / Answer:

Create an init.d script so that VirtualBox Guest VM are controlled as a system service.

Install VirtualBox VM Service script

The original script was for Ubuntu systems found here . Modified for Centos by Kevin Swanson found here .

Create Config File for vboxcontrol service script

# mkdir /etc/virtualbox
# touch /etc/virtualbox/machines_enabled

The file “machines_enabled” located in “/etc/virtualbox” is where we list the names of the Guest VM’s that we want vboxcontrol to control.

To get a list of your current Guest VM names execute the following command and notice the name is in ” “:

$ VBoxManage list vms
"Centos_HDLES_x86_1" {5087b02a-5816-4c76-b302-c13175623023}
"Centos_HDLES_x86_3" {bcae660a-f627-46d6-8c95-9da97363eeea}
"Centos_HDLES_LAMP" {3907173c-cc15-4820-a930-f0bb3c13cb7e}

Add Guest VM’s to “machines_enabled” include one VM name per line

# vi /etc/virtualbox/machines_enabled
Centos_HDLES_x86_1
Centos_HDLES_x86_3
Centos_HDLES_LAMP

Add VirtualBox VM Service script

Create new init.d service script file and give execute permissions

# touch /etc/init.d/vboxcontrol
# chmod 755 /etc/init.d/vboxcontrol

Copy the following code into file “/etc/init.d/vboxcontrol”

#! /bin/sh
# vboxcontrol   Startup script for VirtualBox Virtual Machines
#
# chkconfig: 345 98 02
# description: Manages VirtualBox VMs
# processname: vboxcontrol
#
# pidfile: /var/run/vboxcontrol/vboxcontrol.pid
#
### BEGIN INIT INFO
#
### END INIT INFO
#
# Version 20090301 by Kevin Swanson <kswan.info> based on:
# Version 2008051100 by Jochem Kossen <jochem.kossen@gmail.com>
# http://farfewertoes.com
#
# Released in the public domain
#
# This file came with a README file containing the instructions on how
# to use this script.
#

# Source function library.
if [ -f /etc/init.d/functions ] ; then
. /etc/init.d/functions
elif [ -f /etc/rc.d/init.d/functions ] ; then
. /etc/rc.d/init.d/functions
else
exit 1
fi

################################################################################
# INITIAL CONFIGURATION
VBOXDIR="/etc/virtualbox"
VM_USER="vmadmin"
USE_NAT="no"

export PATH="${PATH:+$PATH:}/bin:/usr/bin:/usr/sbin:/sbin"

if [ -f $VBOXDIR/config ]; then
. $VBOXDIR/config
fi

SU="su $VM_USER -c"
VBOXMANAGE="VBoxManage -nologo"

################################################################################
# FUNCTIONS

# Determine if USE_NAT is set to "yes"
use_nat() {
if [ "$USE_NAT" = "yes" ]; then
return `true`
else
return `false`
fi
}

log_failure_msg() {
echo $1
}

log_action_msg() {
echo $1
}

# Check for running machines every few seconds; return when all machines are
# down
wait_for_closing_machines() {
RUNNING_MACHINES=`$SU "$VBOXMANAGE list runningvms" | wc -l`
if [ $RUNNING_MACHINES != 0 ]; then
sleep 5
wait_for_closing_machines
fi
}

################################################################################
# RUN
case "$1" in
start)
if [ -f /etc/virtualbox/machines_enabled ]; then

cat /etc/virtualbox/machines_enabled | while read VM; do
log_action_msg "Starting VM: $VM ..."
$SU "$VBOXMANAGE startvm "$VM" -type vrdp"
RETVAL=$?
done
touch /var/lock/subsys/vboxcontrol
fi
;;
stop)
# NOTE: this stops all running VM's. Not just the ones listed in the
# config
$SU "$VBOXMANAGE list runningvms" | while read VM; do
log_action_msg "Shutting down VM: $VM ..."
$SU "$VBOXMANAGE controlvm "$VM" acpipowerbutton"
done
rm -f /var/lock/subsys/vboxcontrol
wait_for_closing_machines

;;
start-vm)
log_action_msg "Starting VM: $2 ..."
$SU "$VBOXMANAGE startvm "$2" -type vrdp"
;;
stop-vm)
log_action_msg "Stopping VM: $2 ..."
$SU "$VBOXMANAGE controlvm "$2" acpipowerbutton"
;;
poweroff-vm)
log_action_msg "Powering off VM: $2 ..."
$SU "$VBOXMANAGE controlvm "$2" poweroff"
;;
status)
echo "The following virtual machines are currently running:"
$SU "$VBOXMANAGE list runningvms" | while read VM; do
echo -n "$VM ("
echo -n `$SU "VBoxManage showvminfo ${VM%% *}|grep Name:|sed -e 's/^Name:s*//g'"`
echo ')'
done
;;
*)
echo "Usage: $0 {start|stop|status|start-vm <VM
name>|stop-vm <VM name>|poweroff-vm <VM name>}"
exit 3
esac

exit 0

Add vboxcontrol service to chkconfig registry

# chkconfig --add vboxcontrol

Tell chkconfig to create symlinks for runlevels and activate service vboxcontrol

# chkconfig vboxcontrol on

How to use vboxcontrol to control Guest VM’s running as a service

Start ALL VirtalMachines listed in machines_enable file:

# service vboxcontrol start

Stop ALL VirtualMachines currently running !!

# service vboxcontrol stop

View Status of Running VirtualMachines

# service vboxcontrol status

Start a Specific VirtualMachine Only !!

# service vboxcontrol start-vm <VM NAME>

Stop a Specific VirtualMachine Only ( send acpipowerbutton signal )

# service vboxcontrol stop-vm <VM-NAME>

Send Power Kill signal to VirtualMachine (immediate power off)

# service vboxcontrol poweroff-vm <VM-NAME>
Fabio Milano has written 80 articles for us. Fabio Milano is a certified RHCE, MCP, and CFOI. He runs an IT consulting and services company called RDS Support inc. Website:http://www.rdssupport.com
The information provided is for educational purposes only. All content including links and comments is provided "as is" with no warranty, expressed or implied. Use is at your own risk and you are solely responsible for what you do with it.

40 Comments so far

  1. Kevin Swanson on November 23rd, 2009

    Fabio,

    Thank you for writing such a clear explanation of this process.

  2. mirmit on December 9th, 2009

    Hi,

    It seem – at least in VirtualBox 3.1.0 – the output format of the VBoxManage list command has changed. It include both the name and the UUID of the VM. Unfortunatelly this is not accepted by the stop command.

    I’ve changed the script to trim down the VM name cahngeing the line to:

    $SU “$VBOXMANAGE list runningvms” | egrep -o “^\”[a-zA-Z09]*\”" | while read VM; do

    and then I can properly close the VM.

    Hopping it will help

  3. Marcel on January 22nd, 2010

    Hi,

    $SU “$VBOXMANAGE list runningvms” | egrep -o “^\”[a-zA-Z09]*\”” | while read VM; do

    Did not work, changed a minor thing:

    $SU “$VBOXMANAGE list runningvms” | egrep -o “^\”[a-zA-Z0-9]*\”” | while read VM; do

    Cheers

  4. Ivan Sotelo on March 23rd, 2010

    thanks

    excellent article.

  5. Chris M on May 13th, 2010

    Works great. Really saved me a ton of time! I had a problem where my server would randomly sigfault and restart. This script at least ensures any virtual servers on it restart while i figure out the real problem.

    Thanks!

  6. hgjhj on June 9th, 2010

    [root@xxxxxx ~]# service vboxcontrol start-vm yyyyyyyy
    Starting VM: yyyyyyyy …
    su: user vmadmin does not exist

  7. gemlog on July 6th, 2010

    You need to set that variable to the unprivileged user who actually owns the vm.

  8. ol@fo on July 7th, 2010

    Excelent, works in ClearOS 5.1 (ClarkConnect, use Centos 5.x). I try to traslate in my blog this in spanish, and minor modifications. Try for you blog and information.

    HGJHJ the error is because not exist vmadmin user. If the machine run in a specific user, you may change user parameter in the script for run properly or create vmadmin user.

  9. Maximus on August 6th, 2010

    Excelent, works in CentOs 5.5. Thank you.

  10. Mrbytes on August 13th, 2010

    Maximus

    How to ??
    No I could do it any way, I have CentOs 5.5 (ClearOs 5.2)

    Thx

  11. nosebreaker on August 25th, 2010

    I can’t get the VM’s to stop when I reboot the box (it hangs, waiting for them to shutdown), I tried manually stopping them and they still don’t stop! It gives:
    ERROR: The machine ‘testVM’ does not have an open session
    Details: code VBOX_E_INVALID_SESSION_STATE (0x80bb000b), component Machine, interface IMachine, callee nsISupports
    Context: “OpenExistingSession(a->session, machineuuid)” at line 90 of file VBoxManageControlVM.cpp

  12. TimLa on October 6th, 2010

    You are DA MAN! This worked flawlessly in FC13, just had to change the VM_USER variable.

    Way coolio, saved me a huge amount of time.

    THANK YOU!

  13. Andrés on October 8th, 2010

    [root@Sonda1 ~]# service vboxcontrol stop
    su: invalid option — n
    Try `su –help’ for more information.

  14. Andrés Loyola Barberis on October 26th, 2010

    Finally I get with the solution.
    $SU “$VBOXMANAGE list runningvms” | sed ‘s/.*”\(.*\)”.*/\1/’ | while read VM; do
    Works better than egrep.
    also, you need to add one “-” to nologo line.
    VBOXMANAGE=”VBoxManage –nologo”

    and in Windows 7, at power settings, please, select “shutdown” when button is pressed, otherwise it won’t shut down the machine.
    By default, it does nothing.

    thanks to Cristian Honorato for the SEC command.

  15. Leandro on November 30th, 2010

    It worked without modifications for VBox 3.2.10 with CentOS 5.5 host and guest. Thank you very much for posting this solution. :-D

  16. TechLife on December 29th, 2010

    Please excuse but I’m a bit of a noob to Linux. The script gives me the following result:

    The following virtual machines are currently running:
    “Windows 7″ {e8c50298-9b2b-4d3e-8c05-4c5261eabf78} (bash: -c: line 0: unexpected EOF while looking for matching `”‘
    bash: -c: line 1: syntax error: unexpected end of file
    )

    I assume this is because of the differentiating output format mentioned in earlier posts. I have tried pasting the above mods into the vboxcontrol script but I clearly am not doing it correctly.

    So, for the slow kids, could someone PLEASE post their ENTIRE file so I can cut, paste and change the user name? Or at least be very specific in what exactly needs to be replaced?

    THANK YOU!!!

  17. Andres on December 29th, 2010

    Hi, you can find the complete text file on:
    http://www.bsw.cl/VBox/VboxManagetext.txt.

    Good Luck

  18. Tiago Samuel on April 25th, 2011

    $SU “$VBOXMANAGE list runningvms” | cut -d{ -f1 | while read VM; do

    is simple and easy to solve the problem of machine name substr :D

  19. Jerry Lumpkins on May 1st, 2011

    Thanks a bunch,
    It took me less than 10 minutes to have my virtual machine up and running as a service.

    This was a real time saver.
    (Plus, I got some good insights into how to create other services for future use.)

    The only change I made to your script was to change the user to one that I had already configured.

    Regards,

  20. Michael Lewinger on May 5th, 2011

    Amazing, thank you very much !!!

  21. Stefan Loefler on July 28th, 2011

    worked great on my CentOS 5.6 and safes me a lot of time

  22. Tech on September 5th, 2011

    Seems not working with latest Centos 6.0 and Solaris vbox error:”env: /etc/init.d/vboxcontrol: No such file or directory” i think it is referring to “VBOXDIR=”/etc/virtualbox” ” witch does not exist.

    Please Help.

  23. Tech on September 5th, 2011

    Corection: “VBOXDIR=”/etc/virtualbox” does exist, something else is missing ??:(

  24. Tech on September 6th, 2011

    Solved: Don’t edit with Windows Wordpad, use notepad instead

  25. Kiko on October 29th, 2011

    Worked perfect for me, You have sorted the running users account whose VMs owner-

    Easy peacey. Thanks A lot.

  26. [...] imabonehead: How to configure VirtualBox to Auto start and stop Guest VM | CentOS | Linux Tutorial (kernelhardware.org) [...]

  27. [...] imabonehead: How to configure VirtualBox to Auto start and stop Guest VM | CentOS | Linux Tutorial (kernelhardware.org) [...]

  28. [...] imabonehead: How to configure VirtualBox to Auto start and stop Guest VM | CentOS | Linux Tutorial (kernelhardware.org) [...]

  29. [...] imabonehead: How to configure VirtualBox to Auto start and stop Guest VM | CentOS | Linux Tutorial (kernelhardware.org) [...]

  30. [...] ini saya modifikasi dari script nya Kevin Swanson yang ditampilkan disini. Buat config file untuk vboxcontrol init.d [...]

  31. [...] How to configure VirtualBox to Auto start and stop Guest VM | CentOS | Linux Tutorial. This entry was posted in CentOS, Fedora, Linux, News. Bookmark the permalink. ← Tuning tmpfs filesystem /dev/shm for CentOS — centoshacker Tomorrow Site Outage… → [...]

  32. surachat on June 20th, 2012

    VBoxManage : error : Failed to initialize COM!

  33. Loren Burlingame on July 9th, 2012

    I just thought I would add my own solution to the “VBoxManage list runningvms” line 95:

    $SU “$VBOXMANAGE list runningvms | sed ‘s/ .*//’ | sed ‘s/\”//g’” | while read VM; do

  34. [...] Script ini saya modifikasi dari script nya Kevin Swanson yang ditampilkan disini. [...]

  35. [...] Script ini saya modifikasi dari script nya Kevin Swanson yang ditampilkan disini. [...]

  36. Mario on March 15th, 2014

    Thanks, it works!

  37. Matteo Ghirardelli on April 16th, 2014

    Grazie.

    Ottima

  38. Ikhwan on December 15th, 2014

    This works perfectly. But I have one question. Since the the vm starts automatically, now I can’t view the vm window when I want to do some settings inside the vm. the only it could work is to shutdown the vm through Virtual Box application and run the vm again then only the window for the vm appear. May I know if there are work around. Please email me at ikhwanhuzir@hotmail.com

  39. George Lavan on August 12th, 2015

    Fabio,

    In CentOS 6.6 this works sweet !!!

    Thanks so much, most other posts on this subject were generally pretty worthless. Very clean and precise.

    Geo

  40. George Lavan on September 11th, 2015

    Was working sweet, then broke when I upgraded Linux 6.6 Host to VBox 5.04 for Windows 10 support.

    Now have to start manually again. Oh well …

    :0(

Leave a reply