SSH To Guest or Remote OS
I often have to work with virtual machines and/or remote servers. When its more convenient to use local developer tools, I rely on SSH and SSHFS. This post describes how to setup SSH to connect to a Ubuntu VirtualBox VM. The information can also be applied to other remotes hosts. Connecting to a remote OS via SSH is the first step in extending the use of your local tools for remote development. A subsequent blog post describes how to configure SSHFS.
Download and install VirtualBox to the host operating system (host OS). Create or import a new virtual machine with your preferred OS. For this post, Ubuntu OS (guest OS) will be running inside of Oracle VirtualBox.
SSH provides secure login to remote machines over a network, and more. From the VirtualBox Manager start the Ubuntu VM (graphically) and open the terminal application in Ubuntu.
Install the OpenSSH daemon/server (sshd) with the command
sudo apt-get install openssh-server. Then run the following commands to - enable SSH, start the SSH daemon, and check it’s status.
Check the Ubuntu OS version per the output of the
sudo systemctl enable ssh
sudo systemctl start ssh
sudo systemctl status ssh
sudo service ssh start
sudo service ssh status
Allow SSH through the Ubuntu firewall (ufw), if active. Check firewall status with the command
sudo ufw status. Allow SSH through the firewall (port 22) using the command
sudo ufw allow ssh.
To find the guest OS on the network we can use its IP address or use port forwarding to send all traffic from host to guest via a designated port.
Select settings from the VirtualBox manager then network -> advanced -> port forwarding.
Add a new port forwarding rule that maps host OS port 2222 to guest OS port 22 such that;
- Protocol: TCP
- Host IP: 127.0.0.1
- Host Port: 2222
- Guest IP: N/A (empty)
- Guest Port: 22
From the host OS - open a terminal/command prompt window and SSH to the guest OS;
ssh <guest username>@localhost -p 2222
If port forwarding doesn’t work or you prefer to connect via IP address, find the guest OS IP from the output of the
ifconfig command. Open the settings window, shown above, select network -> attached to -> host-only adapter save selection. Using the guest OS IP address, create a SSH connection;
ssh <guest os username>@<guest os ip>
Copy your public key to the guest/remote host using
ssh-copy-id. See references for generating a RSA key pair. To facilitate the use of scripts, don’t include a passphrase while generating keys.
ssh-copy-id <remote username>@<remote ip> -i ~/.ssh/<public key>.pub
Example command for a guest OS running in VirtualBox:
ssh-copy-id ubuntu@localhost -i ~/.ssh/gen-nopass_ras.pub -p 2222
User authorization with RSA public key has been achieved. The command
ssh ubuntu@localhost -p 2222 no longer prompts for a password.