SSH login on a VirtualBox VM using NAT

I find it useful to have a virtual machine running in the background, to test and explore stuff without the risk of breaking my main host. VirtualBox provides a fast and easy way to run virtual machines on your system. You can do pretty much the same using KVM visualization, but this post is focused on VirtualBox, on a Linux desktop.

VirtualBox provides different options as it comes to networking. The default setting is NAT networking, and it is sufficient for most of my needs.

The guest I am using is Ubuntu Server 14.04 LTS. What I want to do is SSH from my host to my virtual machine so I can work with it from my host’s terminal emulator and have less windows cluttering on my desktop. I can also use copy/paste with my terminal emulator between my host and guest, since we can’t use the VirtualBox shared clipboard without an X server running on the guest (which I don’t need). Another thing is that you won’t be stuck with the mouse and keyboard capture of VirtualBox’s gui, which prevents you from using alt+tab to switch between applications on your host.

For the following steps, I assume your guest VM is already installed and shut down.

The first step, is to open a port on your virtual machine for SSH to work. From the VirtualBox Manager, select your VM, and click on Settings/Network/Advanced/Port Forwarding. Now, create a rule for SSH.

Name: SSH
Protocol: TCP
Host IP: leave empty
Host port: 8022 (you can use another port as you like)
Guest IP: leave empty
Guest port: 22 (This is the official Secure Shell “SSH” port)

Click okay to accept your new rule. You can now close the VirtualBox Manager window, but take note of your VM’s name (mine was simply called “Ubuntu Server”).

You can do the previous step using the command line, like the following:

$ VBoxManage modifyvm "Ubuntu Server" −−natpf1 "SSH, tcp, , 8022, , 22"

Now, what you want to do is start your virtual machine in headless mode. You can do this from the Oracle VM VirtualBox Manager using your mouse’s contextual menu but we’ll be using the command line.

For a terminal emulator or the command line, type the following:

$ VBoxManage startvm "Ubuntu Server" --type headless

Now, your VM is starting in headless mode (in the background). Give it a second to boot. (You can take a peek in the VirtualBox Manager to see the booting process from the preview panel).

Once your virtual machine is running, you can now SSH inside it from your terminal.

$ ssh -p 8022 vmusername@127.0.0.1

That’s it! You are now free of the VirtualBox gui environnement, while using your VM environnement in a fast and efficient way.

Leave a comment