Basic VirtualBox command-line manual
VirtualBox is a practical virtualization tool from Oracle. Its interface is simple enough for a less experienced user to install it on a desktop and create a VM in minutes. It is also free and used in business environments with reliable performance. A virtual machine lets you simulate production environments and try less common operating systems without reinstalling your applications if something goes wrong.
Many online manuals explain how to use VirtualBox's graphical interface, but fewer cover its more complete command-line interface. This manual walks through installation and use on a Linux machine from a terminal. Linux distributions differ little, and Windows is not very different either; you will usually only need to change file paths and network-interface names.
What are host and guest systems?
The host system is the operating system installed on your physical machine. The guest system is the operating system installed in a virtual machine (VM). The host does not always determine guest performance, but the more programs compete with your VMs for resources, the worse they perform. Choose a minimal distribution; a Debian netinst image is ideal.
The Linux distribution used for testing and writing this manual is Debian 6, installed from an approximately 60 MB netinst image. Only the OpenSSH package was needed for remote configuration. On Windows, you can use PuTTY or PenguiNet; on Linux, use the ssh command. If you are unfamiliar with these tools, I recommend the graphical version of VirtualBox.
This host is treated as a headless environment (without a graphical interface). Such environments are common in businesses where each machine or server does not have its own monitor, mouse, and keyboard. If the environment is virtualized, why limit yourself to the physical location of the machine that runs the VMs?
Read later: cloud computing.
What is VirtualBox?
VirtualBox is the hypervisor, also known as a VMM (Virtual Machine Manager). It simulates a physical machine inside a virtual machine and may use processor virtualization features such as Intel VT-x and AMD-V.
There are two types of hypervisors:
Type 1 (bare metal): runs directly on the machine rather than on a host operating system, avoiding issues with applications installed on the host. Citrix XenServer is an example of a bare-metal hypervisor.
Type 2 (hosted): runs on a host operating system, as VirtualBox does. Performance is not as high as a bare-metal hypervisor, but it can still be very good when combined with processor features such as VT-x or AMD-V.
Organizing directories for virtualization
As a suggestion, create a few directories to organize your environment. One inconvenience of the default VirtualBox installation is the spaces in automatically created directory names. Spaces are troublesome when using the command-line interface.
# Primeiro de tudo, entre no modo ROOT
su
# Criando a pasta do ambiente de virtualização
mkdir /virt
# Criando uma pasta para armazenar todas as máquinas criadas
mkdir /virt/vms
# Criando uma pasta para armazenar as ISOs de instalação
mkdir /virt/isos
# Criando uma pasta para armazenar alguns pacotes utilizados na instalação/configuração
# do VirtualBox
mkdir /virt/packs
# Definindo permissões liberais para a pasta de vms
chmod 0777 -R /virt/vmsInstalling VirtualBox on Debian
Before installing, note that the URLs used by the wget commands below may stop working because VirtualBox is updated frequently. Visit the VirtualBox website for current links if one fails. Since this is Debian, we will use apt-get to install packages.
# Entrando na pasta de pacotes
cd /virt/packs
# Inserindo o repositório do VirtualBox na lista de sources do apt-get
echo deb http://download.virtualbox.org/virtualbox/debian squeeze contrib non-free \
>> /etc/apt/sources.list
# Registrando a chave da Oracle para o apt-get
wget -q http://download.virtualbox.org/virtualbox/debian/oracle_vbox.asc -O- \
| sudo apt-key add -
# Não esqueça de atualizar as definições de pacotes
sudo apt-get update
# Instalando o VirtualBox de fato
sudo apt-get install virtualbox-4.1 dkms
# Instalando o pacote de extensões para ativar o acesso remoto a máquina virtual
wget http://phcco.com/public/res/vbox/extpack.php -O extpack.vbox-extpack
# Utilize o vboxmanage do VirtualBox para instalar o pacote adicional
vboxmanage extpack install extpack.vbox-extpack
# Acabaram as tarefas de root
exitIf you cannot find vboxmanage in the last step, something likely went wrong with the package installation. On Windows, make sure the PATH variable also includes the VirtualBox binaries directory.
After installation, leave administrator mode. Creating VMs as
rootmay cause problems when starting them.
Downloading a Debian ISO for the guest system
While creating the VM, open another terminal and download the Debian 6 ISO to install as the guest operating system. This example uses the 64-bit version. A 64-bit host is recommended, and the guest should also be 64-bit whenever possible.
wget http://cdimage.debian.org/debian-cd/6.0.5/amd64/iso-cd/debian-6.0.5-amd64-netinst.iso \
-O /virt/isos/debian-6.0.5-amd64-netinst.isoCreating the virtual machine
When creating a VM, specify its guest operating system so VirtualBox can configure the hypervisor appropriately. You can choose a different operating-system type, but the system may not work correctly. In this example, we find Debian's ID.
# Omita o "| grep Debian" se quiser dar uma olhada no cardápio
vboxmanage list ostypes | grep Debian
# Criando a máquina virtual de fato, no nosso exemplo chamaremos a máquina de Deb64
# Evite o espaço no nome!
vboxmanage createvm --name Deb64 --ostype Debian_64 --register --basefolder /vms
# Agora defina quantos processores esta máquina utilizará e qual é o tamanho da memória RAM e VRAM
vboxmanage modifyvm Deb64 --cpus 4 --memory 1024 --vram 8There is no benefit to assigning four processors if your physical machine has only two cores. Set no more than the number of cores the machine actually has. VirtualBox lets you assign 36 processors to a VM, but on a four-core machine it would spend more time simulating the extra 28 than running your applications.
Because this host has no graphical interface, do not assign too much VRAM; it will be wasted. Eight MB is enough for most Linux systems without a window manager. For Windows, I recommend 16 MB.
Advanced machine settings
The settings above are enough to start the machine, but it is worth configuring a few additional properties. The command below enables processor virtualization features; some apply only to Intel machines with VT-x. For details about each parameter, consult the official VirtualBox manual.
vboxmanage modifyvm Deb64 --pae on --hwvirtex on --hwvirtexexcl on \
--nestedpaging on --largepages on --vtxvpid onThe cpuexecutioncap parameter limits how much host processing power the guest may use. It is a percentage; the example below allows 75% of the CPU. This is useful only when several VMs are running and you do not want one to use resources reserved for another.
vboxmanage modifyvm Deb64 --cpuexecutioncap 75The command below enables ACPI and I/O APIC for the VM. ACPI provides power-management features; I/O APIC is required for some operating systems to detect more than one processor.
vboxmanage modifyvm Deb64 --acpi on --ioapic onSome BIOS settings are important. Set the boot order and disable the BIOS screen in the VM.
# Eliminando o logotipo do VirtualBox que simula a BIOS
vboxmanage modifyvm Deb64 --bioslogodisplaytime 0
# Definindo a ordem de boot, primeiro o DVD e depois o HD
vboxmanage modifyvm Deb64 --boot1 dvd
vboxmanage modifyvm Deb64 --boot2 diskA VM needs a controller for its hard disks and DVD drive. Here, we create a SATA controller with two ports.
# Criamos uma interface de nome SATA, para facilitar, com duas portas
vboxmanage storagectl Deb64 --name sata --add sata --sataportcount 2
# Desabilitamos o cache de IO, só utilize ON se seu disco rígido for ruim
vboxmanage storagectl Deb64 --name sata --hostiocache off
# Definimos que é possível bootar por ele
vboxmanage storagectl Deb64 --name sata --bootable onUsing hostiocache requires extra processing, so disable it when using a solid-state or fast disk (7,200 RPM or higher). On slower disks, leave it enabled for better sequential read/write performance. The cache can also corrupt a virtual disk if the host forcibly closes the VMs.
Additional options
Because this VM will be headless, disable unnecessary features.
# Removendo o audio
vboxmanage modifyvm Deb64 --audio none
# Removendo a área de transferência
vboxmanage modifyvm Deb64 --clipboard disabled
# Removendo a interface USB
vboxmanage modifyvm Deb64 --usb off --usbehci offConfiguring networking
There are two ways to configure a virtual network interface. Bridged mode puts the guest on the same network as the host. NAT makes the host act as a router that hides the VMs. In practice, NAT is useful when there is no DHCP service on the host's network.
Network parameters end with a number that identifies the guest interface affected by the command. A VM can have up to nine network interfaces, starting at 1.
Bridged networking options
In bridged mode, you can set a specific MAC address for the adapter and assign it a static IP through your DHCP server. You must also specify which host adapter to use; in this example, it is eth0.
vboxmanage modifyvm Deb64 --nic1 bridged --bridgeadapter1 eth0 --macaddress1 ca0ca0ca0ca0 \
--cableconnected1 on --nicpromisc1 denyPromiscuous mode is disabled. Without this setting, the guest could read every packet passing over the network.
NAT networking options
If you want to use NAT, I recommend the settings below.
vboxmanage modifyvm Deb64 --nic1 nat --natnet1 "192.168.0/24" --natdnsproxy1 on \
--nataliasmode1 sameportsThis defines the network range for the VM; VirtualBox's built-in DHCP service assigns an IP from that range. The hypervisor also acts as a DNS server so the host's DNS configuration is not exposed. NAT is configured to use the same outbound ports as the guest, which reduces compatibility problems.
Creating NAT port forwards
You can forward host ports to accept incoming connections to the guest. In this example, host port 2222 forwards to guest port 22.
# Sintaxe dos parâmetros
# vboxmanage modifyvm Deb64 --natpf<1-N> "[<name>],tcp|udp,,<hostport>,,<guestport>"
# Criamos o redirecionamento
vboxmanage modifyvm Deb64 --natpf1 "guestssh,tcp,,2222,,22"
# Para apagar basta utilizar o comando delete
# vboxmanage modifyvm Deb64 --natpf1 delete "guestssh"Configuring the remote display interface (VRDE)
VRDE is important in a headless environment. It is a variation of RDP; use mstsc on Windows or tsclient on Linux to access the VM while installing the guest system.
# Habilitamos o VRDE, e informamos qual é a porta do serviço
vboxmanage modifyvm Deb64 --vrde on --vrdeport 5000
# Ajustamos alguns parâmetros para otimizar o VRDE
vboxmanage modifyvm Deb64 --vrdereusecon on --vrdemulticon off --vrdevideochannel on \
--vrdevideochannelquality 75
# Informamos que não é necessário solicitar usuário e senha para abrir o VRDE
vboxmanage modifyvm Deb64 --vrdeauthtype null
# Abaixo desabilitamos algumas funcionalidades para melhorar o desempenho
vboxmanage modifyvm Deb64 --vrdeproperty Client/DisableUSB=1
vboxmanage modifyvm Deb64 --vrdeproperty Client/DisableAudio=1
vboxmanage modifyvm Deb64 --vrdeproperty Client/DisableClipboard=1
vboxmanage modifyvm Deb64 --vrdeproperty Client/DisableUpstreamAudio=1Running the VM without a password is insecure, but for tests in a controlled environment, configuring one may not be necessary. To set a username and password, use the procedure below.
# Habilitamos a autenticação externa do VRDE
vboxmanage modifyvm Deb64 --vrdeauthtype external
# Para criar um usuário e senha primeiro gere a senha
# O comando abaixo criará um hash
vboxmanage internalcommands passwordhash "pass"
# Copie o hash gerado e passe como parâmetro no comando abaixo
# Recomenda-se utilizar um nome de usuário que exista no sistema hospedeiro
# vboxmanage setextradata Deb64 "VBoxAuthSimple/users/<user>" <hash>
# O comando abaixo adiciona um usuário de nome user com a senha pass
vboxmanage setextradata Deb64 "VBoxAuthSimple/users/user" \
d74ff0ee8da3b9806b18c877dbf29bbde50b5bd8e4dad7a3a725000feb82e8f1The VRDE port is opened on the host, not the guest, so you do not need to configure a port inside the guest. Use a port above 1024 to avoid Linux security-policy issues.
Creating a virtual hard disk
Use the commands below to create a virtual hard disk. VDI is VirtualBox's recommended format, but you can choose VMDK or VHD for compatibility with another hypervisor.
# Crie um disco informando o caminho completo do arquivo
# O tamanho deve ser informado em megabytes
vboxmanage createhd --filename /virt/vms/Deb64/disk1.vdi --size 16384 --format vdiThe disk file does not use the full size specified for the virtual disk; it grows as files are stored in the VM. If you reach the virtual disk's limit, you can use two commands.
The resize command increases the disk size but does not update the partition table, so remember to repartition the disk.
vboxmanage modifyhd /virt/vms/Deb64/disk1.vdi --resize 20480You can also use compact to shrink the file based on actual usage. After removing unused space from partitions in the guest, you can reclaim disk space on the host.
vboxmanage modifyhd /virt/vms/Deb64/disk1.vdi --compactAfter creating the disk, connect it to the SATA controller created earlier. This example uses controller port 0 and normal mode.
vboxmanage storageattach Deb64 --storagectl sata --port 0 --type hdd \
--medium /virt/vms/Deb64/disk1.vdi --mtype normalThe immutable mode is useful after installing the guest operating system in normal mode. In immutable mode, changes to the disk are discarded when the VM shuts down. This is useful for temporary test machines. Use the command below to set the mode.
vboxmanage storageattach Deb64 --storagectl sata --port 0 --type hdd \
--medium /virt/vms/Deb64/disk1.vdi --mtype immutableCreating a CD/DVD from an ISO image
Create a CD/DVD drive to install the guest operating system. Specify the full path to the ISO with the medium parameter.
vboxmanage storageattach Deb64 --storagectl sata --port 1 --type dvddrive \
--medium /virt/isos/debian-6.0.5-amd64-netinst.isoUse the command below to remove the disk after installation.
# Neste caso removemos o drive
vboxmanage storageattach Deb64 --storagectl sata --port 1 --type dvddrive \
--medium none
# Neste outro apenas indicamos que removemos o disco do drive
vboxmanage storageattach Deb64 --storagectl sata --port 1 --type dvddrive \
--medium emptydriveInstalling the operating system
Once configured, start the VM with the parameter that selects headless mode.
# Inicializa a máquina
vboxmanage startvm Deb64 --type headless
# Você pode conferir o estado da máquina executando o comando
vboxmanage showvminfo Deb64 | grep StateWe configured port 5000 for the remote-terminal service, so use your RDP application to view the VM and install Debian.
Install an SSH package in the guest so you can administer it. VRDE is slow for long-term work and consumes significant processing power. On Windows machines, enable the native remote terminal; its response is much better.
Managing the virtual machine
Now that the VM is configured on your server, here are some other useful commands.
# Pausa a máquina, é similar ao sleep porém o sistema convidado não dorme
vboxmanage controlvm Deb64 pause
# Retoma a execução da máquina virtual após uma pausa, é como o wakeup
vboxmanage controlvm Deb64 resume
# Faz o reset da máquina, o efeito é o mesmo que o botão físico
vboxmanage controlvm Deb64 reset
# Salva o estado da máquina e a desliga, é equivalente ao hibernar
vboxmanage controlvm Deb64 savestate
# O efeito é o mesmo do botão físico de power
vboxmanage controlvm Deb64 acpipowerbutton
# Caso o modo ACPI não resolva seu problema em desligar a maquina virtual
# utilize a versão equivalente ao desligamento de energia
vboxmanage controlvm Deb64 poweroff
# O efeito é o mesmo da tecla sleep no teclado, neste caso o sistema convidado dorme
vboxmanage controlvm Deb64 acpisleepbuttonRecent VirtualBox versions pause a VM if the physical disk runs out of space. Because virtual-disk files grow as they are used, you could, for example, have several 100 GB virtual disks on a 100 GB physical disk. If a virtual disk cannot allocate physical storage, VirtualBox pauses the VM to prevent data loss.
You can also change network settings while the VM is running.
# Alterando o estado de conexão da rede (algo como "cabo ligado" ou o contrário)
vboxmanage controlvm Deb64 setlinkstate1 off
# Alterando o modo de rede
vboxmanage controlvm Deb64 nic1 nat
# Apagando a regra de port forwarding para o SSH em NAT
vboxmanage controlvm Deb64 natpf1 delete "guestssh"You can change the VM's execution limits as well.
# Removendo toda a restrição de execução
vboxmanage modifyvm Deb64 cpuexecutioncap 100You can also enable or disable VRDE after setup, or change the service port.
vboxmanage modifyvm Deb64 vrde on
vboxmanage modifyvm Deb64 vrdeport 3000Creating and managing snapshots
Snapshots are complete copies of a VM's state, including its configuration, RAM, and hard disk. You can use a snapshot to restore an earlier state.
# Criando um snapshot chamado Snap1
vboxmanage snapshot Deb64 take Snap1
# Restaurando um snapshot
vboxmanage snapshot Deb64 restore Snap1
# Listando todos os snapshots de uma máquina
vboxmanage snapshot Deb64 list
# Apagando um snapshot
vboxmanage snapshot Deb64 delete Snap1Remember that a snapshot is not a full backup: it creates "partial disks" that record changes from a particular point onward.
Exporting a virtual machine (appliance)
Exporting a VM is useful for saving a prepared machine. An appliance lets you distribute a ready-to-use VM with its settings configured. It is exported with the current settings and all disks attached to its controllers.
vboxmanage export Deb64 --output appliance.ovaImporting a virtual machine (appliance)
When you receive an OVF or OVA appliance, run the import command to register the VM. You can change some settings during import, but most can only be adjusted later with the commands covered in the other sections.
# Para simular uma importação e ver os parâmetros disponíveis
vboxmanage import appliance.ova --dry-run
# Para importar alterando basta o comando
vboxmanage import appliance.ova --vsys 0 --vmname NovaMaquinaUseful commands
Here are some useful commands for checking the status of virtual machines.
# Listando as VMs registradas
vboxmanage list vms
# Listando as VMs em execução
vboxmanage list runningvms
# Exibindo propriedades do sistema hospedeiro
vboxmanage list systemproperties
# Exibindo informações da máquina
vboxmanage list hostinfo