1#!/bin/bash 2# 3# vboxinit: auto start sessions when booting and save 4# sessions when host is stopped 5# 6# Based on vboxtool. Only tested in Debian. 7# 8# Debian install: 9# copy this script to /etc/init.d 10# run: 11# chmod u+rx /etc/init.d/vboxinit 12# update-rc.d vboxinit defaults 13 14### BEGIN INIT INFO 15# Provides: vboxinit 16# Required-Start: vboxdrv $local_fs 17# Required-Stop: vboxdrv $local_fs 18# Default-Start: 2 3 4 5 19# Default-Stop: 0 1 6 20# Description: Controls VirtualBox sessions 21### END INIT INFO 22 23. /etc/default/virtualbox 24 25# Enable/disable service 26if [ "${VBOXWEB_USER}" == "" ]; then 27 exit 0 28fi 29 30# Check for VirtualBox binary path 31if [ "$VBOX_BIN_PATH" != "" ]; then 32 PATH = "$PATH:$VBOX_BIN_PATH"; 33fi 34 35start() 36{ 37 # Get all autostart machines 38 MACHINES=$($su_command "VBoxManage list vms | awk '{ print \$NF }' | sed -e 's/[{}]//g'") 39 for UUID in $MACHINES; do 40 STARTUP=$($su_command "VBoxManage getextradata $UUID 'pvbx/startupMode'" | awk '{ print $NF }') 41 if [ "${STARTUP}" == "auto" ]; then 42 VMNAME=$($su_command "VBoxManage showvminfo $UUID | sed -n '0,/^Name:/s/^Name:[ \t]*//p'") 43 echo "$0: starting machine ${VMNAME} ..." 44 $su_command "VBoxManage startvm $UUID --type headless" >>/var/log/vb.log 45 fi 46 done 47} 48 49stop() 50{ 51 # vms are saved, instead of stopped. 52 MACHINES=$($su_command "VBoxManage list runningvms | awk '{ print \$NF }' | sed -e 's/[{}]//g'") 53 for UUID in $MACHINES; do 54 VMNAME=$($su_command "VBoxManage showvminfo $UUID | sed -n '0,/^Name:/s/^Name:[ \t]*//p'") 55 echo "$0: saving machine ${VMNAME} state ..." 56 $su_command "VBoxManage controlvm $UUID savestate" >>/var/log/vb.log 57 done 58 59} 60 61status() 62{ 63 $su_command "VBoxManage list runningvms" 64} 65 66restart() 67{ 68 stop 69 start 70} 71 72 73# Implementation of user control, execute several commands as another (predefined) user, 74su_command="su - ${VBOXWEB_USER} -s /bin/bash -c" 75 76# 77# Check for a command line option 78# 79case "$1" in 80 81 start) 82 start 83 ;; 84 stop) 85 stop 86 ;; 87 status) 88 status 89 ;; 90 restart) 91 restart 92 ;; 93 *) 94 echo "Usage: $0 {start|stop|restart|status}" 95 exit 1 96 ;; 97esac 98 99exit 0 100