How to ssh to virtual box

How to ssh to virtual box

SSH доступ к Ubuntu в VirtualBox

В качестве гостевой ОС в VirtualBox запущена Ubuntu. На ней развернут LAMP, где гоняются тесты веб-приложений. Чтобы не возится с общими директориями, но иметь возможность общаться с файловой системой гостевой ОС из домашней, реализуем возможность доступа к гостевой ОС по ssh протоколу. FTP поднимать не будем, так как SFTP, мне кажется, будет более, чем достаточно.

В Ubuntu устанавливаем SSH сервер. Я никаких настроек не изменял. Начального конфига более, чем достаточно.

Останавливаем виртуальную машину. И переходим к её настройкам – Настройки > Сеть.

How to ssh to virtual box. Смотреть фото How to ssh to virtual box. Смотреть картинку How to ssh to virtual box. Картинка про How to ssh to virtual box. Фото How to ssh to virtual box

Приведите настройки Адаптера 1 к тем, что вы видите на скриншоте. Если в итоге у вас возникнут какие-то проблемы с сетью гостевой ОС, прежде всего, рекомендую попробовать использовать адаптер иного типа. Я ставлю Intel PRO/1000 MT исходя из железа, используемого на моей машине. Но вы можете попробовать «Паравиртуальную сеть (virtio-net)», например.

How to ssh to virtual box. Смотреть фото How to ssh to virtual box. Смотреть картинку How to ssh to virtual box. Картинка про How to ssh to virtual box. Фото How to ssh to virtual box

Переходите на вкладку Адаптер 2, включите его и также приведите состояние настроек в аналогичное тому, что на скриншоте. Комментарии по поводу типа адаптера не отличаются от предыдущего случая.

Запустите виртуальную машину. При запуске можете получить ошибку (многие сталкиваются на Windows 10, например), где сообщается о невозможности открыть сетевое соединение:

Failed to open/create the internal network ‘HostInterfaceNetworking-VirtualBox Host-Only Ethernet Adapter’ (VERR_INTNET_FLT_IF_NOT_FOUND).
Failed to attach the network LUN (VERR_INTNET_FLT_IF_NOT_FOUND).

Отправляемся в Панель управления\Сеть и Интернет\Сетевые подключения, находим там VirtualBox Host-Only Network соединение и переходим к просмотру его Свойств. В списке используемых компонентов находим VirtualBox NDIS6 Networking Driver и включаем его.

How to ssh to virtual box. Смотреть фото How to ssh to virtual box. Смотреть картинку How to ssh to virtual box. Картинка про How to ssh to virtual box. Фото How to ssh to virtual box

Ошибка не должна больше вас беспокоить. Запускаем виртуальную машину.

Переходим к настройке сетевых интерфейсов в гостевой ОС. Необходимо добиться того, чтобы гостевая ОС имела статический IP адрес, по которому вы и будете к ней подключаться.

С правами root пользователя открываем в режиме редактирования файл /etc/network/interfaces.

Настраиваем интерфейс enp0s8. Содержимое файла необходимо привести к следующему состоянию:

Подключаться к виртуальной машине вы будете по ip 192.168.56.10. Сохраняем измененный файл /etc/network/interfaces, перезагружаем виртуальную машину и пробуем подключиться к ней по SSH.

Комментарии (10)

В Windows 10 добавлена возможность работать с bash Ubuntu из коробки. Я у себя на компе настроил Lamp сервер именно в bash. Не думал на этот счет? Это же удобней чем выделять ресурсы на целую виртуальную машину.

Привычная среда для запуска веб-приложений — Unix. Поэтому, для финального тестирования, виртуальная машина мне нравится больше. Условия идентичны боевым. Для разработки мне удобнее и приятнее Docker.

Там тоже виртуальная машина, просто другая.
да и windows 10 очень любит новое железо, обновляться, и вообще плевать на пользователя.

SSH into VirtualBox VM [Step-by-Step]

Table of Contents

Once you have installed any Linux distribution using the Oracle VirtualBox, the next step would be connect to your VM using any SSH client such as Putty or may be from a different Linux machine. This can be tricky for beginners or users who are using Oracle VirtualBox for the first time.

There can be multiple reasons due to which you are unable to SSH to your VirtualBox VM, some of them can be

Or may be none of the above, and since you are doing it for the first time so you are not sure where to start?

Well GoLinuxCloud to the rescue!!

Follow the steps from this article to first make sure there is no problem with your SSH server and then I will guide you with the steps to SSH into VirtualBox VM.

Lab Environment

I already have installed Oracle VirtualBox on my Windows 10 laptop. To save some time I also have multiple VMs installed which I normally use to practice different topics before converting them into an article.

Today I will be using Ubuntu for my demonstration but the same steps can be used for any other Linux distributions such as Debian, Red Hat, CentOS, Rocky Linux, OEL, SuSE etc

Pre-requisites

First we need to make sure that our SSH Server is UP and running with no issues. So these will be part of your pre-checks before you jump to the next section.

Login to your VirtualBox VM

Login to your VM using the console. These are the list of users on my Ubuntu VM. I will use deepak user to login to the console:

How to ssh to virtual box. Смотреть фото How to ssh to virtual box. Смотреть картинку How to ssh to virtual box. Картинка про How to ssh to virtual box. Фото How to ssh to virtual box

Next click on Activities and search for terminal in the search bar. Next click on the Terminal Icon as shown below:

How to ssh to virtual box. Смотреть фото How to ssh to virtual box. Смотреть картинку How to ssh to virtual box. Картинка про How to ssh to virtual box. Фото How to ssh to virtual box

Is Your SSH server UP and Running?

Next check if sshd service is active and running. The command may vary based on distributions.

On Ubuntu and Debian you can use:

On Red Hat, CentOS, Fedora, Rocky Linux you can use:

Here is a sample output SSH service from my VirtualBox VM:

How to ssh to virtual box. Смотреть фото How to ssh to virtual box. Смотреть картинку How to ssh to virtual box. Картинка про How to ssh to virtual box. Фото How to ssh to virtual box

In case your SSH service in not in Running state then you can manually start the service using:

On Ubuntu and Debian you can use:

On Red Hat, CentOS, Fedora, Rocky Linux you can use:

What Port Number is used by your SSH Server?

Next you should check the port number in use by SSH (SSHD) server. In most cases if you have done a scratch installation then the port number in use would be 22. But just to be sure, let’s verify the same:

You can use either netstat or ss command to check this:

Sample Output:
How to ssh to virtual box. Смотреть фото How to ssh to virtual box. Смотреть картинку How to ssh to virtual box. Картинка про How to ssh to virtual box. Фото How to ssh to virtual box

As you can see, the SSHD server is using port 22 which is the default port. So we have to SSH into VirtualBox using port 22.

Is your firewall blocking SSH Server?

Normally when you are trying to access a VirtualBox VM from the same laptop then the only firewall you encounter would be the firewall installed on the Linux Server.

In most distributions these days we use firewalld so I will share the commands for the same. You can install firewalld if not available:

On Ubuntu and Debian you can use:

On Red Hat, CentOS, Fedora, Rocky Linux you can use:

Execute the following set of commands to get the default values from your VM:

Now that we have these basic information, check if SSH service is enabled in your firewall:

In our case, SSH service is already added in the firewalld. In case it is not present, you can manually add the same using:

If your SSH service is running on a different port then you should manually allow that port in the firewalld. For example, if your SSH server is using port 5022 then you can use the following commands to add port 5022 in the firewall:

Now that we are all sorted out with firewall, so now we can start with the steps to SSH into VirtualBox VM.

Method-1: SSH into VirtualBox using Bridged Network Adapter

The first method to SSH into VirtualBox is to use a bridged network adapter in your Virtual Box network Settings.

Step-1: Access Machine Settings of the VM

You don’t need to power off your VM to use this method. So using your VM console, access the Machine option from the Top Menu and click on Settings as shown below:
How to ssh to virtual box. Смотреть фото How to ssh to virtual box. Смотреть картинку How to ssh to virtual box. Картинка про How to ssh to virtual box. Фото How to ssh to virtual box

Step-2: Change Network Settings to use “Bridged Adapter”

Next access the Network Settings as shown below. When a VM is installed, then by default NAT Network is chosen for the Adapter. Select your adapter, in my case I have two adapters in which I wish to use Bridged Adapter for my Second Adapter.

So from the drop down menu, select «Bridged Adapter» and leave all other settings to default.

How to ssh to virtual box. Смотреть фото How to ssh to virtual box. Смотреть картинку How to ssh to virtual box. Картинка про How to ssh to virtual box. Фото How to ssh to virtual box

The VirtualBox setting will automatically select your preferred Network. If you have more than one interfaces in your Windows Laptop then you can select the drop down menu from Name and choose your preferred interface. This may not be required in most cases.

Step-3: Configure Network on Linux Server

Now the changes may have been applied runtime on the Oracle VirtualBox VM but we still need to configure our Network in the Ubuntu Server to use the new Network Settings.

Currently these are my network details for Adapter 2. As you can see, the IP Address of enp0s8 is 10.0.3.15/24 which is clearly a NAT IP:

How to ssh to virtual box. Смотреть фото How to ssh to virtual box. Смотреть картинку How to ssh to virtual box. Картинка про How to ssh to virtual box. Фото How to ssh to virtual box

Next check if your selected interface is configured for STATIC IP or DHCP:

So, currently I have these two interfaces, check if the enp0s8 interface is configured with static or dhcp:

Good, so we are using DHCP which makes things easier for us now. But hey you can always assign a static IP Address to your interface but unfortunately that is not the agenda of this article.

In case you do want to switch from static to dhcp then you can execute this command:

Here replace Wired connection 2 with your connection name.

Now that we know our interface is configured with DHCP, we just have to restart our network and it should automatically get the new IP Address from your Router which you are using to connect your Windows 10 laptop.

Use the following command to restart your network:

This will bring down all your interfaces and then start them again. Alternatively to refresh only one of your interface you can use

How to ssh to virtual box. Смотреть фото How to ssh to virtual box. Смотреть картинку How to ssh to virtual box. Картинка про How to ssh to virtual box. Фото How to ssh to virtual box

As you can see, now the IP Address of enp0s8 interface has been changed and it has picked up the IP Address from my Wi-Fi Router.

Step-4: Verify SSH connectivity to Oracle VirtualBox VM

Now that our SSH service and Oracle VirtualBox VM Networking is all set, let’s try to connect to our Ubuntu VM using Putty Client:

How to ssh to virtual box. Смотреть фото How to ssh to virtual box. Смотреть картинку How to ssh to virtual box. Картинка про How to ssh to virtual box. Фото How to ssh to virtual box

Provide your IP Address and Port Number, Click on Open and you should get a login prompt where you can add your username and password.:

How to ssh to virtual box. Смотреть фото How to ssh to virtual box. Смотреть картинку How to ssh to virtual box. Картинка про How to ssh to virtual box. Фото How to ssh to virtual box

So we have successfully performed SSH into our Oracle VirtualBox VM.

Method-2: SSH into VirtualBox VM using NAT

I would recommend users to use this method to SSH into VirtualBox VM. if you recall, in our previous section of this article, I mentioned about connectivity issues when using some kind of VPN.

So for example you are connected to your office VPN and in parallel you also want to work on your Oracle VirtualBox setup. But the SSH won’t work with bridged Adapter due to the VPN as the network has changed.

Most VPN also do not allow configuring DHCP or static IP so there is no way you can connect to your VM using any SSH Client. In such scenarios we prefer to use NAT as it can bypass the VPN network using Port Forwarding.

Step-1: Access Machine Settings of the VM

We again need to modify our Network Settings of the respective VM. This although doesn’t require your VM to be Powered Off. So you can just head over to Machine and click on Settings from the TOP BAR menu of your Virtual Box Console.

How to ssh to virtual box. Смотреть фото How to ssh to virtual box. Смотреть картинку How to ssh to virtual box. Картинка про How to ssh to virtual box. Фото How to ssh to virtual box

Step-2: Change Network Settings to use “NAT”

Next access the Network Settings. Choose your Adapter and from the drop down menu select «NAT«.

How to ssh to virtual box. Смотреть фото How to ssh to virtual box. Смотреть картинку How to ssh to virtual box. Картинка про How to ssh to virtual box. Фото How to ssh to virtual box

Step-3: Configure Port Forwarding

Next we need to configure Port Forwarding on your VirtualBox VM’s Network Settings. On the same section as above under Network Settings. Click on Advanced and next click on Port Forwarding:

How to ssh to virtual box. Смотреть фото How to ssh to virtual box. Смотреть картинку How to ssh to virtual box. Картинка про How to ssh to virtual box. Фото How to ssh to virtual box

Next another pop-up window will appear where you should provide the Port forwarding details. Click on the ADD icon to add a new rule. Fill in the below details

How to ssh to virtual box. Смотреть фото How to ssh to virtual box. Смотреть картинку How to ssh to virtual box. Картинка про How to ssh to virtual box. Фото How to ssh to virtual box

Once done, click OK

Step-4: Configure Network on Linux Server

After you have saved the Network Settings changes on the oracle VirtualBox VM, we also need to refresh our network configuration in the Linux server.

We ca again use the same set of commands as we used in the previous section to refresh our network configuration:

This will bring down all your interfaces and then start them again. Alternatively to refresh only one of your interface you can use

Next verify your IP Address:

How to ssh to virtual box. Смотреть фото How to ssh to virtual box. Смотреть картинку How to ssh to virtual box. Картинка про How to ssh to virtual box. Фото How to ssh to virtual box

For a NAT network, you will always get 10.0.2.15/24 IP Address. So this means our configuration is complete, now let’s try to connect to this VM using SSH Client.

Step-5: Verify SSH connectivity to Oracle VirtualBox VM

We will use PuTTY to verify the SSH connectivity towards the Oracle VirtualBox VM. Open a new PuTTY session and provide the details:

The hostname (or IP Address) section must contain the loopback address and provide the same port number as used for Host Port in Port Forwarding section.

How to ssh to virtual box. Смотреть фото How to ssh to virtual box. Смотреть картинку How to ssh to virtual box. Картинка про How to ssh to virtual box. Фото How to ssh to virtual box

Next click on Open and you should get the login prompt to connect to the VM:

How to ssh to virtual box. Смотреть фото How to ssh to virtual box. Смотреть картинку How to ssh to virtual box. Картинка про How to ssh to virtual box. Фото How to ssh to virtual box

Well Done, you have successfully connected to your Oracle VirtualBox VM using SSH.

Should you use NAT or Bridged Adapter for SSH?

You can choose either of the methods but personally I have setup all my VirtualBox VMs with two Network Adapters wherein one is connected with NAT while the other with Bridged Adapter.

The Bridged Adapter is required when we need a multi-node environment so multiple VMs can SSH to each other. The above provided steps of NAT can not be used to SSH from one VM to another. So I use NAT to connect to my VMs from my Windows laptop while the Bridged connection is used to have a multi-VM setup.

Although there are different ways we can enable SSH between VMs but Bridged Adapter would be the better one as with this we also can access external networks. You may also choose to use Host-Only Network or Internal Network. I have already explained each of these different network options available with Oracle VirtualBox in another article.

Summary

In this tutorial we learned two different methods using which you can SSH into VirtualBox VM. I have also shared my personal recommendation which you should use when working with Oracle VirtualBox. I hope the steps from this article was useful, let me know if you have and feedbacks or questions using the comment section.

Further Reading

Related Posts

Didn’t find what you were looking for? Perform a quick search across GoLinuxCloud

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

How to ssh to virtual box. Смотреть фото How to ssh to virtual box. Смотреть картинку How to ssh to virtual box. Картинка про How to ssh to virtual box. Фото How to ssh to virtual box

For any other feedbacks or questions you can either use the comments section or contact me form.

Thank You for your support!!

How to SSH into your VirtualBox Guest

Having the capability to SSH into your Guest OS can come in handy when you don’t want to use the GUI of your Virtual Machine. Simply start your VM in a headless mode and SSH in and out of it without having multiple windows open in your terminal.

For those who are new to the idea of SSH, we will have a short introduction to the workings of SSH before diving into the setup. Also we would need to discuss the network related settings of your VM to make sure you have access to that VM from anywhere in your LAN.

How SSH-keys works?

Here’s simplified model of how SSH works. You create a pair of keys on your local computer. A public key and a private key. Messages encrypted using Public key can be decrypted using the private key and vice versa. These keys are usually stored on your local computer at a path

/.ssh/id_rsa (private key) and

/.ssh/id_rsa.pem (the public key).

You then go to your remote server, login to a console as a regular or root user, open up the file

The .pem extension signifies that that file is the public key that you can share with anyone. The id_rsa part just signifies what encryption cipher is being used (in this case it happens to be RSA). The private key can further be protected by a passphrase which you would have to enter, everytime you want to login to a remote server using that private key.

If you have a Mac, Linux or any other UNIX-like system as your local computer you can generate and manage keys using terminal, and you can also SSH into remote servers using the same terminal. For Windows users, I’d suggest use PuTTY or Git Bash the latter being my personal preference. The commands are pretty much the same once you have an SSH client.

SSH-keys Setup

First make sure, if there are no ssh-keys already in your home directory. Check the contents of your home directory’s .ssh folder. If in doubt, back up its contents before executing the following command. Programs like Filezilla use SSH keys all the time, without the user’s knowledge so this step is rather crucial.

In your local machine, open the terminal and enter the command:

This will be followed up by the following prompts with values in bracket indicating the default values. Proceed with the prompts and give your keys a secure passphrase.

How to ssh to virtual box. Смотреть фото How to ssh to virtual box. Смотреть картинку How to ssh to virtual box. Картинка про How to ssh to virtual box. Фото How to ssh to virtual box

Verify that the keys are created by checking the contents of your

If you see files matching the default values displayed in the ssh-keygen prompt then everything has worked fine.

How to ssh to virtual box. Смотреть фото How to ssh to virtual box. Смотреть картинку How to ssh to virtual box. Картинка про How to ssh to virtual box. Фото How to ssh to virtual box

Now open up a console to your Virtual Machine. First check if your VM has SSH server running or not.

How to ssh to virtual box. Смотреть фото How to ssh to virtual box. Смотреть картинку How to ssh to virtual box. Картинка про How to ssh to virtual box. Фото How to ssh to virtual box

If it is not installed, use your package manager to search and install OpenSSH server. Once that is done make sure that your VM’s firewall is open on port number 22. For example, if you are using Ubuntu as a VM, the default firewall ufw should either be disabled or should allow port 22 connections like so:

How to ssh to virtual box. Смотреть фото How to ssh to virtual box. Смотреть картинку How to ssh to virtual box. Картинка про How to ssh to virtual box. Фото How to ssh to virtual box

If if is not open at port 22, use the follow command:

Next open up the file

/.ssh/authorized_keys on your VM, using your favorite text editor. You may want to enable host-to-guest or bidirectional clipboard for this next step.

Inside this file (at the bottom of the file, if it is not empty) paste in the contents of your public key. The last part where it says your name and the local host where the keys were generated is not that important as the rest of the string.

How to ssh to virtual box. Смотреть фото How to ssh to virtual box. Смотреть картинку How to ssh to virtual box. Картинка про How to ssh to virtual box. Фото How to ssh to virtual box

(Optional) Not using SSH-keys

If you trust your local network, then you can use the less secure method of using your UNIX password, to ssh into your VM. Open up the file /etc/ssh/sshd_config on your VM and replace the line:

Once that is in place, restart your SSH server.

Now you can use the regular password that you use to login to your VM to ssh into it as well.

Your Virtual Machine and Network

For you to ssh into your VM, both your local computer (the one with the private key) and the VM should be on the same network. So you can reach to that VM’s IP address. We will show you how to add the VM to your LAN.

Let’s consider the example of a typical home router setup. Your computer, along with other devices, is connected to the home router. This router also acts as a DHCP server, meaning it assigns each device that’s connected to it, a unique private IP address. Your desktop gets an IP, so does your phone and your laptop. Only the devices that are connected to this router can talk to one another via their IP addresses.

Enable bridged networking mode in the settings of your VM and the VM will show up as being connected to your home router (or a similar DHCP server) with a private IP. If a second device is connected to the same network (say, to the same home router) then it can be used to ssh into the VM.

Open VirtualBox Manager, select your target VM, open up the Settings → Network and select Bridge Networking instead of NAT.

How to ssh to virtual box. Смотреть фото How to ssh to virtual box. Смотреть картинку How to ssh to virtual box. Картинка про How to ssh to virtual box. Фото How to ssh to virtual box

As you can see my host is connected using Wireless so that connection is also shared by the VM, if you are using Ethernet, a different interface name would show up which is fine.

Now, my VM, which is named ubuntuvm, shows up on my LAN setup as following. Check your router settings to see if the same works for you.

How to ssh to virtual box. Смотреть фото How to ssh to virtual box. Смотреть картинку How to ssh to virtual box. Картинка про How to ssh to virtual box. Фото How to ssh to virtual box

Once you know the IP address of your VM, you can SSH into it by running the command:

How to ssh to virtual box. Смотреть фото How to ssh to virtual box. Смотреть картинку How to ssh to virtual box. Картинка про How to ssh to virtual box. Фото How to ssh to virtual box

If you have put a passphrase for your private key in the above steps, you would be prompted to re-enter it.

That’s it! Now you can start your VMs in headless mode and just ssh into them from anywhere in your house. Hope you found this tutorial interesting, let us know if there’s any topic you would want us to cover.

About the author

How to ssh to virtual box. Смотреть фото How to ssh to virtual box. Смотреть картинку How to ssh to virtual box. Картинка про How to ssh to virtual box. Фото How to ssh to virtual box

Ranvir Singh

I am a tech and science writer with quite a diverse range of interests. A strong believer of the Unix philosophy. Few of the things I am passionate about include system administration, computer hardware and physics.

by Sijin George | Mar 20, 2019

VirtualBox allows to create different guest virtual machines on top of the same host. And, it provides isolation from the host too.

But, what if you need to access the guest machine via SSH?

That’s where Network Address Translation (NAT) helps. It allows SSH access even to the virtual servers.

At Bobcares, we often get requests from customers to enable VirtualBox SSH NAT settings as part of our Infrastructure Management Services.

Today, we’ll see how our Dedicated Engineers setup SSH via NAT in Virtualbox and solve common issues with it.

How VirtualBox NAT helps?

Let’s now take a look on the need for having special settings to SSH to the guest server.

VirtualBox support Network Address Translation aka NAT. NAT simply maps an address to another.

Usually, by enabling NAT networking for any guest server, VirtualBox automatically performs IP address translation between the guest VM and host’s network. And, there is no need to configure anything on the host machine or on the local network in guest. However, this makes guest VM not reachable or visible from external networks. Thus, it creates problems when you want to access the guest VM directly.

Fortunately, by enabling port forwarding for port 22, we can SSH to the guest machine from the host.

Steps to enable SSH on VirtualBox

Now, let’s see how our Dedicated Engineers setup port forwarding for VirtualBox NAT. There are options to do this either from the GUI or from the command line. We’ll check both methods here.

1. Port forwarding from GUI

Firstly, let’s see how to do this from the VirtualBox web interface.

On VirtualBox, to allow SSH access, we need to edit the network settings of the guest VM.

For this, we first choose the guest VM, then open “Settings” >> “Network” >> “Advanced” section. This will show additional network adapter options. Then, we click on “Port Forwarding” button.

Here, we add a new port forwarding rule. It will contain a name for the rule, protocol, host IP, port and guest IP and port.

For example, to enable SSH access on a guest machine with IP 10.0.2.15 on port 2522, our Support Engineers set up the rule from the panel as

How to ssh to virtual box. Смотреть фото How to ssh to virtual box. Смотреть картинку How to ssh to virtual box. Картинка про How to ssh to virtual box. Фото How to ssh to virtual box

When we power on the guest VM, it will automatically enable this rule. However, to confirm that port 2522 is listening, we check using the netstat command.

Now, we can SSH to the guest VM using

Here, the SSH login request sent to 127.0.0.1:2522 will automatically be translated into 10.0.2.15:22 by VirtualBox. Thus, we can now SSH to the guest VM.

2. Port forwarding from command line

Similarly, we can add port forwarding from the command line too. Let’s check on how to do this too.

Here, we make use of the VirtualBox command-line management interface called VBoxManage.

To create a port forwarding rule for guest VM named “Centos” with IP address 10.0.2.15 and SSH port 22, mapped to local host at port 2522, our Dedicated Engineers use the command:

Here, the name of the rule should be set as unique.

After creating the rule, we verify it using

And, this will show the rule in the results.

From our experience in managing VirtualBox, we often see customers having problems with SSH on guest VMs. Let’s see where customers go wrong in NAT setup and how we fix them.

1. Port problems

Often, problems can arise while choosing the SSH port. Recently, one of our customers reported problems with SSH access to his VirtualBox guest machine. The error said:

Here, our Support Engineers started investigation by checking the SSH configuration and the port forwarding rule. In this case, the forwarding rule was set up on port 2222, while customer was using 22 instead. And, we corrected the customer to use the correct SSH port and that fixed the problem.

2. Network settings

Similarly, network settings also can create problems with access to VirtualBox guests.

The network settings depend on the type of access required on guest VMs. For example, when the guest server need only access via internal network, our Dedicated Engineers setup the network interface as host-only adapter. Here, the machine will not have access to the internet.

And, for machines that need internet access too, we set the Adapter 1 as NAT and set Adapter 2 as a Host-Only adapter. Thus, when users report connection problems, we always ensure that the network adapter is set correctly on the server.

Conclusion

To conclude, VirtualBox SSH NAT settings decide on the access to the guest machines. Today, we saw how our Dedicated Engineers setup port forwarding rules to enable SSH access on guest machines and fix common problems with it.

Related posts:

PREVENT YOUR SERVER FROM CRASHING!

Never again lose customers to poor server speed! Let us help you.

Our server experts will monitor & maintain your server 24/7 so that it remains lightning fast and secure.

Как подключиться к виртуальной машине VirtualBox по SSH

После установки серверного дистрибутива Linux на виртуальную машину VirtualBox вы можете обнаружить, что подключение по SSH не работает. Это связано с тем, что по умолчанию на VirtualBox используется подключение к интернету с помощью NAT.

При таком способе подключения у вас нет возможности подключаться к виртуальной машине из своей реальной операционной системы. В частности, вы не сможете подключиться по SSH.

В данной статье мы рассмотрим сразу два способа, как можно решить эту проблему. Первый вариант – проброс портов через NAT, а второй – использование сетевого моста. Оба этих способа сохраняют доступ к интернету на виртуальной машине.

Проброс портов для SSH

Для проброса портов вам нужно знать IP адрес, который присваивается виртуальной машине. Для этого запустите виртуальную машину и выполните на ней команду « ip addr » или « ifconfig ». В ответ вы получите информацию о сетевых подключениях, в которой будет указан и IP адрес. В нашем случае был получен IP адрес – « 10.0.2.15 ».

Обратите внимание, если в вашей системе нет команды « ifconfig », то ее нужно будет установить отдельно. В случае Debian и Ubuntu Linux это можно сделать с помощью команды « apt-get install net-tools ».

How to ssh to virtual box. Смотреть фото How to ssh to virtual box. Смотреть картинку How to ssh to virtual box. Картинка про How to ssh to virtual box. Фото How to ssh to virtual box

После того как мы узнали IP адрес виртуальную машину нужно выключить и открыть ее настройки в программе VirtualBox.

How to ssh to virtual box. Смотреть фото How to ssh to virtual box. Смотреть картинку How to ssh to virtual box. Картинка про How to ssh to virtual box. Фото How to ssh to virtual box

В настройках виртуальной машины нужно открыть раздел « Сеть », открыть дополнительные настройки и перейти к пробросу портов.

How to ssh to virtual box. Смотреть фото How to ssh to virtual box. Смотреть картинку How to ssh to virtual box. Картинка про How to ssh to virtual box. Фото How to ssh to virtual box

После этого откроется окно для проброса портов. Здесь нужно нажать на кнопку « Добавить » и заполнить следующие данные:

После проброса порта закрываем все окна с помощью кнопки « ОК ».

How to ssh to virtual box. Смотреть фото How to ssh to virtual box. Смотреть картинку How to ssh to virtual box. Картинка про How to ssh to virtual box. Фото How to ssh to virtual box

После этого можно подключаться к виртуальной машине по SSH. Для этого можно использовать клиент OpenSSH, который доступен в Windows 10. Поскольку порт « 2222 » на основной системе был проброшен на порт « 22 » на виртуальной машине, то для подключения по SSH нам нужно выполнить следующую команду:

Где « user » — это имя пользователя, а « 2222 » — используемый порт на основной системе.

How to ssh to virtual box. Смотреть фото How to ssh to virtual box. Смотреть картинку How to ssh to virtual box. Картинка про How to ssh to virtual box. Фото How to ssh to virtual box

How to ssh to virtual box. Смотреть фото How to ssh to virtual box. Смотреть картинку How to ssh to virtual box. Картинка про How to ssh to virtual box. Фото How to ssh to virtual box

Как видно по скриншоту вверху, данный способ отлично работает, и мы успешно подключились по SSH к виртуальной машине VirtualBox.

Подключение через сетевой мост

Также есть альтернативный способ подключения к виртуальной машине по SSH для этого нужно изменить тип подключения с « NAT » на « Сетевой мост ». В этом случае виртуальная машина будет подключена к вашей локальной сети и получит IP адрес от вашего роутера из того же диапазона, что и ваша основная система.

Для этого нужно выключить виртуальную машину и зайти в ее свойства в программе VirtualBox. В настройках нужно зайти в раздел « Сеть » и включить тип подключения « Сетевой мост ».

How to ssh to virtual box. Смотреть фото How to ssh to virtual box. Смотреть картинку How to ssh to virtual box. Картинка про How to ssh to virtual box. Фото How to ssh to virtual box

После этого нужно запустить виртуальную машину и выполнить на ней команду « ip addr » или « ifconfig » для того, чтобы узнать, какой IP адрес она получила от роутера. В нашем случае был получен IP адрес « 192.168.1.214 ».

How to ssh to virtual box. Смотреть фото How to ssh to virtual box. Смотреть картинку How to ssh to virtual box. Картинка про How to ssh to virtual box. Фото How to ssh to virtual box

После этого к виртуальной машине можно подключаться по SSH. Для этого нужно просто использовать IP адрес, который был ей присвоен роутером. Например, для того чтобы подключиться с помощью клиента OpenSSH нужно выполнить следующую команду:

Где « user » — это имя пользователя, а « 192.168.1.214 » — это ее IP адрес.

How to ssh to virtual box. Смотреть фото How to ssh to virtual box. Смотреть картинку How to ssh to virtual box. Картинка про How to ssh to virtual box. Фото How to ssh to virtual box

Аналогично работает и подключение с помощью PuTTY. Вводим « 192.168.1.214 » и подключаемся по стандартному порту « 22 ».

How to ssh to virtual box. Смотреть фото How to ssh to virtual box. Смотреть картинку How to ssh to virtual box. Картинка про How to ssh to virtual box. Фото How to ssh to virtual box

Как и предыдущий способ, вариант с использованием сетевого моста отлично работает, при этом виртуальная машина не теряет доступа к интернету.

Источники информации:

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *