背景
給VirtualBox虛擬機(裝載了Ubuntu16.04系統)配置了兩張網卡,網絡模式分別為“網絡地址轉換(NAT)”和“僅主機(Host-Only)適配器”,其中,enp0s3網卡(NAT)用于外網訪問,而enp0s8網卡(Host-Only)用于主機訪問虛擬機。然而,虛擬機啟動后,卻不能訪問外網。
定位
網絡配置文件如下:
# vi /etc/network/interface
...
# The primary network interface
auto enp0s3
iface enp0s3 inet dhcp
auto enp0s8
iface enp0s8 inet static
address 192.168.137.16
netmask 255.255.255.0
gateway 192.168.137.1
eth0使用dhcp,eth1使用static。eth0的實際網絡如下:
# ifconfig
enp0s3: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500
inet 10.0.2.15 netmask 255.255.255.0 broadcast 10.0.2.255
inet6 fe80::a00:27ff:fe55:2858 prefixlen 64 scopeid 0x20<link>
ether 08:00:27:55:28:58 txqueuelen 1000 (Ethernet)
RX packets 6 bytes 1476 (1.4 KB)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 33 bytes 3108 (3.1 KB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
打開其路由,才發現了問題。
# route -n
Kernel IP routing table
Destination Gateway Genmask Flags Metric Ref Use Iface
0.0.0.0 192.168.137.1 0.0.0.0 UG 0 0 0 enp0s8
10.0.2.0 0.0.0.0 255.255.255.0 U 0 0 0 enp0s3
192.168.137.0 0.0.0.0 255.255.255.0 U 0 0 0 enp0s8
enp0s8網卡成為了默認路由,這就導致其他路由不能匹配到的網段都會走enp0s8這個網卡,而我們實際上配置與外網連接的虛擬網卡是enp0s3,環境自然就連接不了外網了。我們可以嘗試手動來刪除現在的默認路由。
# route del default
# route add default gw 10.0.2.2 dev enp0s3
# route -n
Kernel IP routing table
Destination Gateway Genmask Flags Metric Ref Use Iface
default gateway 0.0.0.0 UG 0 0 0 enp0s3
10.0.2.0 0.0.0.0 255.255.255.0 U 0 0 0 enp0s3
192.168.137.0 0.0.0.0 255.255.255.0 U 0 0 0 enp0s8
路由設置成功,OS也可以訪問外網了。但這只是修改了本次的路由設置,OS重啟后就失效了,因此我們需要將配置持久化。
持久化路由配置
我們將路由持久化設置在網絡配置文件/etc/network/interfaces中。在網卡啟動后添加對應的路由增刪的代碼,與route命令類似,只是在句首加上up即可。
# vi /etc/network/interfaces
...
auto enp0s3
iface enp0s3 inet dhcp
up route add default gw 10.0.2.2 dev enp0s3
auto enp0s8
iface enp0s8 inet static
address 192.168.137.16
netmask 255.255.255.0
gateway 192.168.137.1
up route del default dev enp0s8
注意:up route add default gw [gateway-addr] dev [dev-name],該語句中,[dev-name]表示外網網卡的名稱,即上面的enp0s3,而[gateway-addr]表示外網網卡使用的網關ip地址。
那么,如何獲取這個外網網卡的網關地址呢?virtualbox如下規定:
In NAT mode, the guest network interface is assigned to the IPv4 range 10.0.x.0/24 by default where x corresponds to the instance of the NAT interface +2. So x is 2 when there is only one NAT instance active. In that case the guest is assigned to the address 10.0.2.15, the gateway is set to 10.0.2.2 and the name server can be found at 10.0.2.3.
簡單的說,就是如果第0個網卡是NAT網卡,那么其網段的第三個數字就0+2=2就是10.0.2.0,網關為10.0.2.2,name server則是10.0.2.3.以此類推。
參考:鏈接地址
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。