如何更方便的通过ssh连接本机VistualBox里面的虚拟机

254 阅读1分钟
原文链接: blog.sodroid.com

文章的实验环境是MacBook,虚拟机用的是VistualBox,安装的是Ubuntu 18.04镜像。

遇到的问题是,我需要在宿主机里面通过ssh通道登录虚拟机,可知方法是让虚拟机的网络设置为 NAT 网络,让虚拟机和宿主机处于同一网段。但会有一个问题存在,就是宿主机切换了网络后,内网ip会改变。找到解决方法后,就有了这篇文章。

一、打开Ubuntu的SSH服务

这里不介绍如何安装Ubuntu虚拟机,可以自行Google搜索。

  • 首先我们通过apt-get工具安装 openssh-clientopenssh-server

sudo apt-get install openssh-client
sudo apt-get install openssh-server
  • 安装成功后,我们运行SSH服务

sudo systemctl enable ssh
sudo systemctl start ssh
  • 然后你可以修改SSH服务的端口,默认是22

sudo vim /etc/ssh/sshd_config
# The strategy used for options in the default sshd_config shipped with
# OpenSSH is to specify options with their default value where
# possible, but leave them commented.  Uncommented options override the
# default value.
Port 22
  • 修改后记得restart SSH 服务

接下来设置虚拟机的网络

  • 设置为 网络地址转换(NAT)

  • 点击 高级 -> 端口转发

  • 设置端口转发

最后把虚拟机加入宿主机的 ~/.ssh/config 里面


$ vi ~/.ssh/config

Host thanos0
HostName 127.0.0.1
Port 2222
User thanos0
  • 通过 ssh thanos0 连接虚拟机即可