5

为DietPi系统设置网卡优先级

 11 months ago
source link: https://wusiyu.me/dietpi-network-interface-metric/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

为DietPi系统设置网卡优先级

%E6%88%AA%E5%B1%8F2023-07-09-22.31.08.png

当你的设备同时带有WiFi和有线网时,你就会希望让系统优先使用有线网,一些系统(比如使用NetworkManager的)会自动完成这件事,但DietPi并没有。

各种Linux的网络配置方案会各不相同,比如桌面Linux和新一些的服务器Linux会使用较为现代的NetworkManager,Ubuntu搞过一个netplan,树莓派官方系统Raspbian直接用dhcpcd来管理网络,而DietPi使用Debian传统的/etc/network/interface(ifupdown),这篇文章的方法也适用于其他使用/etc/network/interface配置方案的系统。

首先编辑/etc/network/interface,为接口设置metric值,格式类似metric 100,数字越小表示表示优先级越高,DietPi中修改完类似如下(注意该文件在dietpi-config中调整网络接口设置后会被覆盖):

root@DietPi:~# cat /etc/network/interfaces
# Location: /etc/network/interfaces
# Please modify network settings via: dietpi-config
# Or create your own drop-ins in: /etc/network/interfaces.d/

# Drop-in configs
source interfaces.d/*

# Ethernet
allow-hotplug eth0
iface eth0 inet dhcp
address 192.168.0.100
netmask 255.255.255.0
gateway 192.168.0.1
#dns-nameservers 192.168.10.2
metric 100

# WiFi
allow-hotplug wlan0
iface wlan0 inet dhcp
address 192.168.0.100
netmask 255.255.255.0
gateway 192.168.0.1
#dns-nameservers 192.168.10.2
pre-up iw dev wlan0 set power_save off
post-down iw dev wlan0 set power_save on
wpa-conf /etc/wpa_supplicant/wpa_supplicant.conf
metric 600

此外,经过测试,这里的metric值不会对本地网络路由中的metric生效(下面的后两行),导致在访问内网机器时,(甚至是ssh 内网ip时的回程),仍然可能使用错误的网卡:

root@DietPi:~# route
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
default         openwrt         0.0.0.0         UG    100    0        0 eth0
default         openwrt         0.0.0.0         UG    600    0        0 wlan0
192.168.10.0    0.0.0.0         255.255.255.0   U     0      0        0 eth0
192.168.10.0    0.0.0.0         255.255.255.0   U     0      0        0 wlan0

解决方法是安装ifmetric软件包,但我们不需要用这个命令其手动设置metric,而是ifmetric会在接口启动时自动根据/etc/network/interface中的配置进行设置(软件包提供了/etc/network/if-up.d/ifmetric)。

随后重启网络服务,可以发现metric被正确设置了:

root@DietPi:~# route
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
default         openwrt         0.0.0.0         UG    100    0        0 eth0
default         openwrt         0.0.0.0         UG    600    0        0 wlan0
192.168.10.0    0.0.0.0         255.255.255.0   U     100    0        0 eth0
192.168.10.0    0.0.0.0         255.255.255.0   U     600    0        0 wlan0

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK