• CommentTimeNov 5th 2010 edited

    I run a Windows VM on my file server that I control using LogMeIn (which I can't recommend enough) but I often forget to start the VM, and being headless - there is nothing really to remind me. VirtualBox doesn't come with any scripts to start/stop a VM with the computer and a lot of the suggestions I've seen are rather complex. This is a really simple script that starts the VM with your machine and then saves the state on shut down.

    So first, create a new file in /etc/init.d - I'll call mine SpodeVM. I personally do this in an terminal using nano, but you could use gEdit. Remember that you'll need root privileges to write to that folder, so "sudo nano /etc/init.d/SpodeVM".

    Inside the file, you'll want the following. Change "spode" for the user that your VirtualBox VM is owned by, and change "My VM Name" for the name of your VM.

    #! /bin/sh # /etc/init.d/SpodeVM # #Edit these variables! VMUSER=spode VMNAME="My VM Name" case "$1" in start) echo "Starting VirtualBox VM..." sudo -H -b -u $VMUSER /usr/bin/VBoxVRDP -s "$VMNAME" ;; stop) echo "Saving state of Virtualbox VM..." sudo -H -u $VMUSER /usr/bin/VBoxManage controlvm "$VMNAME" savestate ;; *) echo "Usage: /etc/init.d/SpodeVM {start|stop}" exit 1 ;; esac exit 0

    Then give that script executable permission with "sudo chmod +x /etc/init.d/SpodeVM".

    Now we need to tell the script to run when the computer starts up and shuts down. So we use "sudo update-rc.d SpodeVM defaults 99 01". This will make sure that the VM is the last thing to start up, and the first thing to shut down.

    You can see it's a very simple script, based on the debian skeleton. In my case, I use VBoxVRDP to start the VM as I use RDP to control it, you can also use VBoxManage to the same effect, or to customise options.

    Notably - see the use of "-b" on sudo, to run the command as a background task, and "-H" to set the home folder to that of the user. Without that, it causes an error to do with initializing the COM interface.

    This has been tested on Ubuntu 10.10, using VirtualBox 3.2.10. It's generic enough that I imagine it should stand the test of time :)

Copyright Andrew Miller (Spode), 2008