Freitag, 4. Februar 2011

Running a virtual machine without a gui on Windows

Hi felt the urge today to have a virtual Linux running on my Windows box, just as I had my kvm virtual machine under Linux. Since I only want to use SSH and I want it to integrate in my running screen-session, I do not need a fancy gui.
Also for various reasons I cannot set up any network for the VM, so I'm forced to used the default NAT option.

I choose VirtualBox, because it's popular and easy to install.

So after the normal installation of the Virtual Box, here's the trick:

1. Set up a init script to connect to the host on startup and forward the ssh port (through NAT). My script looks like this:



#!/bin/bash
#
# Init Script to allow running the VM without GUI
# chkconfig: 345 99 1
# description: Automatically start a reverse SSH tunnel.

# Source function library.
. /etc/init.d/functions

# Environment configured in startup scripts

SSH=/usr/bin/ssh
RPORT=1234
RETVAL=0
RUSER=vmuser
RHOST=pc06
SSHKEY=/root/vmkey

start()
{
echo -n $"Starting remote port forward "

${SSH} -i ${SSHKEY} -R ${RPORT}:localhost:22 $RUSER@$RHOST sleep 36000 &
RETVAL=$?

if [ $RETVAL -eq 0 ] && [ -f $PIDFILE ]; then
echo_success
else
echo_failure
fi
echo
}

stop()
{
echo -n $"Just wait until it times out ok kill it yourself"
RETVAL=$?
if [ $RETVAL -eq 0 ] && rm -f /var/lock/subsys/inm ; then
echo_success
else
echo_failure
fi
echo
return $RETVAL
}

case "$1" in
start)
start
;;
stop)
stop
;;
restart)
stop
start
RETVAL=$?
;;
status)
RETVAL=$?
;;
*)
echo $"Usage: $0 {start|stop|restart|condrestart|status}"
RETVAL=1
esac

exit $?
Obviously you will need to create a pair of ssh keys and do the usual setup. Probably not the wised thing to run this as root, but since it's a VM I don't really care. Also obviously you will need to add this user to your windows box and give it permissions to ssh in (I use cygwin) and it's maybe a good idea to limit the accounts permissions for secutiry.

2.) Running the VM without any window popping up.
It seems like the only way to do this is to use a VBS scrpt that calls the BAT file that starts VM.

Set WshShell = CreateObject("WScript.Shell")
WshShell.Run chr(34) & "C:\Documents and Settings\bjoern.henkel\runcentosvm.bat" & Chr(34), 0
Set WshShell = Nothing

@echo off
"C:\Program Files\Oracle\VirtualBox\VBoxHeadless.exe" -s {0d7a417e-3c54-4c70-b87a-fd3fa8448870}

Now I'm able to reach the virtual linux by using

ssh -p 1234 localhost