Control a Virtual Machine threw VirtualBox and C

Материал из Wiki Test Lab
Перейти к: навигация, поиск

Назад    Главная
 

Содержание

Control a Virtual Machine threw VirtualBox and C.

Источник

« Précédent / Suivant » Par deisss / septembre 23, 2012 / CSharp / Un commentaire

I wanted to manage a VM using only C#, the idea was to create an easy start/stop program which help the user to use it without any knowledge.

This program should cover this :

  • Be able to start/stop the VM
  • Be able to hide everything
  • Be able to get the VM ip (the system on the VM was a complex internet demo site)
  • Be able to know the VM state (to indicate if the VM is currently running or not)

For all of this, VirtualBox provide a nice tool called VirtualBoxManage, which is a command line tool. It seems to be able to do exactly the same stuff as VirtualBox, but in a command line way of course. I will detail here the commands used to make the system working. I will assume the VM name is « MyLinuxOS », the name can be found by launching VirtualBox and checking the VM name on the left list !

VirtualBoxManage command

I will show here basics to make VirtualBoxManage doing all the stuff :

Starting a VM

Maybe the most simple, and easy to find on internet, the startvm command will start the VM, adding the headless parameters will make the VM hidden to the user :

VirtualBoxManage startvm "MyLinuxOS" --type headless

Stopping a VM

Like starting, stopping is also an easy one :

VirtualBoxManage controlvm "MyLinuxOS" poweroff

Getting the VM ip

The IP is not created when starting the VM, so it can be accessed long time before, or when the VM is not running ! Here is the command :

VirtualBoxManage guestproperty get "MyLinuxOS" "/VirtualBox/GuestInfo/Net/0/V4/IP"

This will return a « Value: 10.4.4.4 » for example, so we should parse the string to remove Value parts…

Knowing the VM state

This one is the most complicated : it seems there is no way to check a VM is started or not. And when I say « started », I’m saying the VM is ready to logon, not just running. But, you can threw VirtualBox send command to the VM like a real user, so you can get that state threw a simple trick :

VirtualBoxManage guestcontrol "MyLinuxOS" execute --image "/bin/uname" --username myLogin --password myPassword --wait-stdout

This will send the command /bin/uname (reply « Linux » on Linux) using a simple logon on the system. Of course, it will not work on OS who don’t have /bin/uname (like Windows for example), but you can send another command if you want. If the VM is not ready (not launched or not ready to logon), VirtualBoxManage will send message on error output. You should use here a command which reply a basic things (the best is a non-change string, like uname always reply Linux it will never change)

Now all commands have been listed, we can do a basic C# program to manage that !

Читать дальше

Личные инструменты