Often we create virtual machines in VirtualBox only to access it via terminal. In this case, we don't really need a GUI interface. Of course, we can log in to the machine and then execute some commands from the terminal inside the virtual machine. However, isn't it more convenient if we can log in from the host machine via ssh, which we may configure to suit our work style? This article briefly describes two ways to SSH into virtual machines in VirtualBox.
Using NAT Network setting
This one is super simple, and you just need to ssh via a port in the host (e.g., localhost).
With the virtual machine is in the power-off state, open VirtualBox and select Network setting. Make sure that Enable Network Adapter option is checked, and the Attached to option is set to NAT. Then, click the Port Forwarding button to open Port Forwarding Rules window.
In the Port Forwarding Rules, add a new rule by clicking the 'plus' button. Enter the following rules.
- Name: ssh (you can use any name you want)
- Protocol: TCP
- Host Port: 3022 (any port is fine as long as it is not being used by the host)
- Guest IP: (you can leave this empty)
- Guest Port: 22
Start the virtual machine, and try to log in to the machine using the following command:
ssh -p <host-port> <username>@localhost
For example for the above setting, we can log in using
ssh -p 3022 hasan@localhost
Using the Bridge Adapter Network setting
In this case, the virtual machine will have an IP address from the local network to which the host belongs.
With the virtual machine is in power-off state, open VirtualBox and select Network setting. Make sure that Enable Network Adapter option is checked, and the Attached to option is set to Bridge Adapter.
Now, we need to check the IP address assigned to the virtual machine. Start the virtual machine, log in to it, open terminal and execute the following command:
Find an IP address that belongs to the same local network of the host. For example, from the following result, I found that the IP address is:
All set, and finally we can access the virtual machine from the host using the following command:
For the above IP addres, I can ssh into my machine using:
Please note that the above setting assumes
ssh service is already installed in the virtual machine. If not, please install it beforehand.