Virtualbox as a sysadmin toolVirtualbox como herramienta para administradores

Besides the port fordwarding, VirtualBox has another very useful feature for system administrators: running a virtual machine WITHOUT graphical interface.

We suppose this situation: we have a virtualized server (it doesn’t matter if it’s linux, Windows, Solaris,…), must run every time you start the system and must also consume less resources as possible.

The solution seems simple. VirtualBox brings commands: vboxsdl and vboxheadless. Both allow to run a virtual machine without open virtual machines manager.

vboxsdl run the virtualized system in a window graphical interface, in fact is the same as running the system from the virtual machines manager, but if we call it directly, we avoid having to resort to this.

vboxsdl -startvm "VM_NAME"

vboxheadless run virtualised system, but without raising any graphical interface, making it possible to boot only with the console. This is especially useful for servers that dispenses with the Xserver.

vboxheadless -startvm "VM_NAME"

If we can not see the virtual machine, how would you control?

Here I have a couple of tips used in Windows XP as host, Windows 2000 Server as guest, but the same should be applied in a Linux and other systems.

Además de la redirección de puertos, hay otra característica de Virtualbox muy útil para administradores: correr una máquina virtual SIN interfaz gráfica.

Supongamos esta situación: Tenemos un servidor virtualizado (da lo mismo si es linux, windows, solaris, …), debemos ejecutarlo cada vez que parta el sistema y además debe consumir los menos recursos que sea posible.

La solución pareciera ser muy sencilla. Virtualbox trae los comandos: vboxsdl y vboxheadless. Ambos permiten correr una máquina virtual sin abrir el administrador de máquinas virtuales.

vboxsdl ejecuta el sistema virtualizado en una ventana de interfaz gráfica, de hecho es lo mismo que correr el sistema desde el administrador de máquinas virtuales, pero si lo llamamos directamente, nos evitamos tener que recurrir a este.

vboxsdl -startvm "NOMBRE_DE_LA_MAQUINA_VIRTUAL"

vboxheadless ejecuta el sistema virtualizado, pero sin levantar interfaz gráfica alguna, por lo cual es posible arrancar una máquina virtual solo con la consola. Esto es especialmente útil para servidores que prescinden del Xserver.

vboxheadless -startvm "NOMBRE_DE_LA_MAQUINA_VIRTUAL"

Ahora, hay un pequeño problema. Si no podemos ver la máquina virtual ¿cómo la controlamos?

Tengo acá un par de consejos que he aplicado en windows xp virtualizando windows 2000 server, pero debiera poder aplicarse lo mismo en un host con Linux u otros sistemas.

Setting up a virtual machine with remote desktop

If someone has occupied the guest additions, using a remote desktop is something similar. First, we must enable the remote desktop to the VM, the manager of VirtualBox virtual machines:

virtualbox vrdp

Tip: change the default port, especially on windows, because the Remote Desktop Service reserves the use of the port by default. If we have more than one virtual machine, then you should also have each their own port. In my case, leave it to port 1000.

Then with the same client for Windows Remote Desktop (Start -> All Programs -> Accessories-> Remote Desktop Connection), we can connect to the VirtualBox server, using as host localhost: 1000.

Kubuntu brings krdc client, who should do the same thing (I have not tested yet).

Tweak for Windows as host: start the VM without showing the cmd console

There is only a small great discomfort. Just wanted to avoid any window on the taskbar, running the VM in the background, but the cmd console shown anyway.

There are several ways to execute a command «in the background» in Windows, but the more complex is to use parameters of the WinAPI in source code. It is therefore not a viable solution.

The only solution I’ve found up to the minute, is to use a combination of a batch file (.bat) with a vbscript (.vbs) that can be run from the desktop.

vboxsart.bat:

"C:\Archivos de programa\Sun\xVM VirtualBox\VBoxHeadless.exe" -startvm "NOMBRE_DE_MAQUINA_VIRTUAL"

(modify the path to vboxheadless if necessary)

In the same directory, create vboxstart.vbs:

Set WshShell = CreateObject("WScript.Shell")
WshShell.Run chr(34) & "vboxstart.bat" & Chr(34), 0
Set WshShell = Nothing

Finally, create a shortcut and move it to Start-> All Programs -> Start, or any other form of boot commands to boot windows, would be ready.

Fortunately on Linux is much easier to start these commands, especially because we can create scripts as a service, or when we start a command from a launcher on the desktop, will not open any console window (default).

Another tip

Windows 2000 Server has a skill. To log on is to press CTRL + ALT + DELETE. If we do, respond the keyboard shortcut of host Guest system. To avoid this, you can configure automatic logon to the guest system. It is generally advisable to avoid the use of keyboard shortcuts in virtual machines.

Just missing …

Well, something I have not researched yet, is how to create and configure the virtual machine console, without requiring the VirtualBox manager wizard. Surely it is very simple, so it is left as an exercise for the reader. Hint: RTFM.

Another detail that I needed, and could be serious, it’s like to send a signal off the virtual machine, in order to shutdown it safely. For now, I can only kill the process of the virtual machine (unsafe) or turning off the system through the guest remote desktop.

Just send me a link to a service script to start and stop a virtual machine on Archlinux.

Finally, I owe some tests on Kubuntu, until further notice.

Configurar la máquina virtual con escritorio remoto

Si alguien ha ocupado las guest additions, usar un escritorio remoto es algo similar. Primero, debemos habilitar el escritorio remoto para la VM, en el administrador de máquinas virtuales de Virtualbox:

virtualbox vrdp

Consejo: cambiarle el puerto predeterminado, en windows sobre todo, debido a que el servicio de escritorio remoto reserva el uso del puerto por defecto. Si tenemos más de una máquina virtual, entonces también debería tener cada una su propio puerto. En mi caso, lo deje con el puerto 1000.

Luego, con el mismo cliente de escritorio remoto de windows ( Inicio -> todos los programas -> Accesorios-> Conexión a escritorio remoto ), podemos conectarnos al servidor de virtualbox, usando como host localhost:1000.

En Kubuntu, viene el cliente krdc, que debería permitir hacer lo mismo (no he probado aún).

Ajuste para host Windows: arrancar la VM sin mostrar la consola de cmd

Solo hay una pequeña gran incomodidad. Justamente, me quería ahorrar una ventana en la barra de tareas corriendo la VM en el fondo, pero igual me quedó visible la consola de cmd.

Hay varias formas para ejecutar un comando en windows, pero la más compleja consiste en usar unos parámetros de la WINAPI a nivel de código fuente. Por lo tanto no es una solución viable.

La única solución satisfactoria que he encontrado hasta el minuto, es usar una combinación de un archivo por lotes (.bat) con un vbscript (.vbs) que se pueda ejecutar desde el escritorio:

vboxsart.bat:

"C:\Archivos de programa\Sun\xVM VirtualBox\VBoxHeadless.exe" -startvm "NOMBRE_DE_MAQUINA_VIRTUAL"

(modificar la ruta a vboxheadless si es necesario)

En el mismo directorio, creamos vboxstart.vbs:

Set WshShell = CreateObject("WScript.Shell")
WshShell.Run chr(34) & "vboxstart.bat" & Chr(34), 0
Set WshShell = Nothing

Finalmente, con crear un acceso directo y moverlo a Inicio->Todos los programas -> Inicio, o cualquier otra forma de arrancar comandos al bootear windows, quedaría listo.

Afortunadamente en linux es mucho más fácil arrancar estos comandos, sobre todo porque podemos crear scripts de inicio como servicio, o por último cuando lo hacemos desde X, no se levanta ninguna ventana de consola (por defecto).

Otro consejo

Windows 2000 Server tiene una maña. Para hacer iniciar la sesión hay que presionar ctrl+alt+supr. Si lo hacemos, responderá la combinación de teclas del sistema Host. Para evitar eso, se puede configurar a mano un inicio de sesión automático en el sistema Guest. En general, se aconseja evitar el uso de atajos de teclado en las máquinas virtuales.

Tan solo falta…

Bueno, algo que no he investigado aún, es como crear y configurar la máquina virtual por consola, sin necesitar el asistente gráfico de virtualbox. Seguramente es muy sencillo, así que se deja como ejercicio para el lector. Hint: RTFM.

Otro detalles que sí me falta, y podría ser serio, es como mandarle una señal de apagado a la máquina virtual, para poder bajarla en forma segura. Por el momento, solo puedo apagar la máquina matando el proceso de la máquina virtual (inseguro) o apagando el sistema invitado a través del escritorio remoto.

Me acaban de mandar un enlace de un script de servicio, para arrancar y detener una máquina virtual en Archlinux.

Finalmente, quedo en deuda con algunas pruebas en Kubuntu hasta nuevo aviso.

5 comentarios sobre “Virtualbox as a sysadmin toolVirtualbox como herramienta para administradores

  1. Bueno creo que el codigo que indicas aqui tiene error
    porque no me funciona.Si me puedes ayudar.
    Set WshShell = CreateObject(«WScript.Shell»)
    WshShell.Run chr(34) & «vboxstart.bat» & Chr(34), 0
    Set WshShell = Nothing
    Esta muy bueno el texto.muchas gracias

  2. A mi me ha funcionado poniendo esto:

    Set WshShell = CreateObject(«WScript.Shell»)
    WshShell.Run «vboxstart.bat»,0,1
    Set WshShell = Nothing

  3. Para detener la maquina virtual desde la consola podemos usar:
    $ VBoxManage controlvm «SnMiguel» poweroff

  4. VBoxManage controlvm «nombre de la maquna» acpipowerbutton manda señal de apagado a la maquina,

    VBoxManage controlvm “SnMiguel” poweroff apaga la maquina de golpe :S

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *

Este sitio usa Akismet para reducir el spam. Aprende cómo se procesan los datos de tus comentarios.