今天在VirtualBox中安装虚拟机之后,发现网络通过Net方式可以联网,但是物理主机却不能 ping 通虚拟机,由于我需要在物理主机访问虚拟主机的服务,并且要保证虚拟主机也能联网。虽然通过桥接可以实现,但是由于网络需要通过Web方式认证之后才能上网,而虚拟机是ubuntu-server版的没有提供桌面环境,因此桥接方式也不可行。
VirtualBox中提供了一种Host Only的联网方式,通过此种方式,VirtualBox会在物理机中建立一个虚拟网卡,这样就可以将虚拟机和物理机配置到同一网络下,进而实现物理主机和虚拟主机的互通,但这样虚拟主机就无法连接互联网。
既然一张网卡不能同时为Net和Host Only两种连接方式,那么我们可以通过为虚拟机新建一张网卡,将两张网卡分别设置为Net和Host Only,这样应该就能实现物理主机与虚拟主机互通,并保证虚拟主机连接互联网的需求了。
在添加网卡之后,启动虚拟机,执行ifconfig发现依然只有一张网卡信息。执行sudo lshw -C network命令发现系统实际上是有两张网卡的,但是由于 network:1 DISABLED,因此通过ifconfig命令查看时没有发现其相关的信息。打开 /etc/network/interface 其内容如下:
# This file describes the network interfaces available on your system # and how to activate them. For more information, see interfaces(5). source /etc/network/interfaces.d/* # The loopback network interface auto lo iface lo inet loopback # The primary network interface auto enp0s3 iface enp0s3 inet dhcp在 /etc/network/interfaces 文件末尾加入如下内容:
auto enp0s8 iface enp0s8 inet dhcp修改完成后利用sudo service networking restart重启网卡,运行ifconfig命令可以看到网卡启用成功,此时,ping物理主机及互联网均可成功。
VirtualBox 非桥接物理主机与虚拟主机互联及上网配置(物理主机已能上网)
为虚拟机配置两张网卡,一张设置为Net模式,另一张设置为Host Only模式;利用sudo lshw -C network查看网卡相关信息,确认网卡没有被禁用;若网卡被禁,修改 /etc/network/interface 文件,在文件末尾加入下面的内容启用网卡。其中 network_name 是被禁网卡的逻辑名称。
auto network_name iface network_name inet dhcp
重启网卡sudo service networking restart。