Автозагрузка VirtualBox VM Service CentOS 6 Печать
17.07.12 14:11

Автозагрузка VirtualBox VM Service в CentOS 6.2

 

( Скрипт для запуска и управления виртуальными машинами VirtualBox в CentOS и RadHat )


Для запуска виртуальной машины от имени root можно использовать команду:

su -s /bin/bash root -c "VBoxManage startvm "имя вашей машины" --type headless"

Но мне было необходимо добавить в сервис ( chkconfig ) запуск нескольких виртуальных машин. Как вы знаете, или еще не знали,
для добавления в сервис CentOS, скрипт должен соответствовать определенным стандартам. На просторах инета есть масса скриптов по запуску в среде Ubuntu и Debian. А вот по CentOS и старшего брат RadHat инфы маловато.

 

 

Создадим фал machines_enabled

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

 

В этом файле /etc/virtualbox/machines_enabled , мы пропишем в столбик имена всех наших виртуальных машин.

 

Узнать имена всех машин можно командой

$ 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}

 

Добавим имена машин в файл

# vi /etc/virtualbox/machines_enabled
Centos_HDLES_x86_1
Centos_HDLES_x86_3
Centos_HDLES_LAMP

Создадим скрипт автозагрузки VirtualBox VM  - vboxcontrol

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

Содержимое “/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 < Данный адрес e-mail защищен от спам-ботов, Вам необходимо включить Javascript для его просмотра. >
# 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="root"
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


Добавим "vboxcontrol" наш скрипт в сервис "chkconfig registry"

# chkconfig --add vboxcontrol

Создадим симлинк для запуска сервиса

# chkconfig vboxcontrol on

Как использовать скрипт?

Старт всех виртуальных машин

# service vboxcontrol start

Остановка всех запущенных виртуальных машин

# service vboxcontrol stop

Показать статус всех виртуальных машин

# service vboxcontrol status

Старт одной виртуальной машины

# service vboxcontrol start-vm <VM NAME>

Стоп одной виртуальной машины

# service vboxcontrol stop-vm <VM-NAME>

Выключить питание виртуальной машины (immediate power off)

# service vboxcontrol poweroff-vm <VM-NAME>




источник: http://www.php2s.com/linux/virtualbox-auto-start-vm-centos-fedora-redhat.html
ссылка на материал: http://thin.kiev.ua/linux/39-linux/653-virtualbox-vm-service-centos.html


P.S. Для старта виртуальных машин в Debian

touch /etc/init.d/virtualboxServerDebian
chmod +x /etc/init.d/virtualboxServerDebian
vi /etc/init.d/virtualboxServerDebian


and insert this :

#!/bin/bash
# This script starts and stops the VirtualBox virtual machine ServerDebian.
# Use a SSH client to connect to the virtual machine.
case "$1" in
'start')
/usr/bin/VBoxHeadless --startvm "ServerDebian" --vrde off &
;;
'stop') /usr/bin/VBoxManage controlvm "ServerDebian" acpipowerbutton
;;
*)
echo "Usage: $0 { start | stop }"
exit 1
;;
esac


I test (and success) using this commands :
/etc/init.d/virtualboxServerDebian start
/etc/init.d/virtualboxServerDebian stop


And then create services :
update-rc.d virtualboxServerDebian defaults


Еще один скрипт для CentOS
источник
http://www.dzinovic.net/how-tos/virtualbox-on-centos/

wget http://www.dzinovic.net/dl-files/vmsctrl/vbox/vmsctrl.tar.gz
tar xvzf vmsctrl.tar.gz -C /etc/init.d/
chkconfig --add vmsctrl

Замените
NAME="vmsctrl" на имя пользователя от которого запускается VirtualBox

#!/bin/bash

######################################################################################
## Script for automatic control over VirtualBox virtual machines
## Copyright (C) 2012 Almir Dzinovic < Данный адрес e-mail защищен от спам-ботов, Вам необходимо включить Javascript для его просмотра. >
##
## This program is free software; you can redistribute it and/or modify it under
## the terms of the GNU General Public License as published by the Free Software
## Foundation; either version 3 of the License, or (at your option) any later version.
##
## This program is distributed in the hope that it will be useful, but WITHOUT
## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
## FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
##
## Get the full text of the GPL here: http://www.gnu.org/licenses/gpl.txt
######################################################################################

### BEGIN INIT INFO
# Provides: VBox VMs Control
# Required-Start: $local_fs $network $syslog
# Required-Stop:
# Default-Start: 2 3 5
# Default-Stop: 0 6
# Short-Description: Starts or stops VirtualBox VMs
# Description: Starts or stops VirtualBox virtual machines
### END INIT INFO

# vmsctrl     Starts or stops VirtualBox VMs.
#
# chkconfig: 235 99 05
# description: Starts or stops VirtualBox virtual machines.
# config: /etc/default/vmsctrl.conf

. /lib/lsb/init-functions

DESC="VirtualBox VMs control script"
NAME="vmsctrl"

. /etc/default/virtualbox

VMACHINES=$(su - "${VBOXWEB_USER}" -c "vboxmanage list vms | awk '{ print \$NF }' | sed -e 's/[{}]//g'")

case "$1" in
start)
echo -n $"Starting virtual machines "
# Starting virtual machines
for i in $VMACHINES
do
su - "${VBOXWEB_USER}" -c "vboxmanage startvm $i --type headless &> /dev/null"
done
[ $? -eq 0 ] && log_success_msg || \
log_failure_msg
;;
stop)
echo -n $"Powering off virtual machines "
# Powering off virtual machines
for i in $VMACHINES
do
su - "${VBOXWEB_USER}" -c "vboxmanage controlvm $i poweroff &> /dev/null"
done
[ $? -eq 0 ] && log_success_msg || \
log_failure_msg
;;
restart)
echo -n $"Power cycling virtual machines "
# Power cycling virtual machines
for i in $VMACHINES
do
su - "${VBOXWEB_USER}" -c "vboxmanage controlvm $i reset &> /dev/null"
done
[ $? -eq 0 ] && log_success_msg || \
log_failure_msg
;;
*)
echo $"Usage: "$0" {start|stop|restart}"
exit 1
;;
esac

exit $?



{jcomments on}
Последнее обновление 20.08.12 16:25