一、需求描述
无线网卡连接无线用来上互联网。地址为自动获取。
有线网卡连接网络打印机。(打印机直连,打印机地址192.168.1.2。本机地址192.168.1.4,掩码255.255.255.255,网关192.168.1.2)
二、环境:
uos v20
三、查看网卡配置并分析原因:
ifconfig 查看网卡信息
user@user-PC:~$ ifconfig
enp12s0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500
inet 192.168.1.4 netmask 255.255.255.255 broadcast 192.168.1.4
inet6 fe80::cafb:6656:1793:2f6a prefixlen 64 scopeid 0x20<link>
ether 1c:83:41:e2:ea:22 txqueuelen 1000 (Ethernet)
RX packets 7136 bytes 691932 (675.7 KiB)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 3361 bytes 2565073 (2.4 MiB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
lo: flags=73<UP,LOOPBACK,RUNNING> mtu 65536
inet 127.0.0.1 netmask 255.0.0.0
inet6 ::1 prefixlen 128 scopeid 0x10<host>
loop txqueuelen 1000 (Local Loopback)
RX packets 1927 bytes 171024 (167.0 KiB)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 1927 bytes 171024 (167.0 KiB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
wlxc83a35ce0d70: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500
inet 10.15.19.126 netmask 255.255.248.0 broadcast 10.15.23.255
inet6 fe80::ca75:679c:6468:2e20 prefixlen 64 scopeid 0x20<link>
ether c8:3a:35:ce:0d:70 txqueuelen 1000 (Ethernet)
RX packets 99440 bytes 37326953 (35.5 MiB)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 27807 bytes 5313659 (5.0 MiB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
有线网卡:enp12s0
无线网卡:wlxc83a35ce0d70
查看当前路由信息:route
user@user-PC:~$ route
Kernel IP routing table
Destination Gateway Genmask Flags Metric Ref Use Iface
default _gateway 0.0.0.0 UG 600 0 0 wlxc83a35ce0d70
default _gateway 0.0.0.0 UG 600 0 0 enp12s0
10.15.16.0 0.0.0.0 255.255.248.0 U 600 0 0 wlxc83a35ce0d70
192.168.1.2 0.0.0.0 255.255.255.255 UH 20100 0 0 enp12s0
user-PC 0.0.0.0 255.255.255.255 UH 100 0 0 enp12s0
可以看到网络之所以不同,是因为存在两条冲突的默认路由,要保持双网卡上网,需要删除其中一个,并手动指向该网卡的路由。
三、重新配置路由并设置开机自启
在此我选择删除有线网卡enp12s0的路由
删除有线网卡的默认路由并新增一条去往有线网卡的路由
可以直接在Terminal操作
sudo route del -net default netmask 0.0.0.0 dev enp12s0
sudo route add -net 192.168.1.2 netmask 255.255.255.255 dev enp12s0
这种方式只是暂时生效,重启后继续无法双网卡上网
要实现重启后自动修改路由信息,可以选择利用NetworkManager调度网络服务(详情参考https://wiki.archlinux.org/title/NetworkManager_(%E7%AE%80%E4%BD%93%E4%B8%AD%E6%96%87)#%E5%90%AF%E7%94%A8_NetworkManager)
具体方式:
在etc/NetworkManager/dispatcher.d/ 新建脚本文件(在此我命名为02myroutes)
cd /etc/NetworkManager/dispatcher.d
touch 02myroutes.sh
vim 02myroutes.sh
输入i,更改为插入模式
route del -net default netmask 0.0.0.0 dev enp12s0
route add -net 192.168.1.2 netmask 255.255.255.255 dev enp12s0
按ESC 输入wq保存退出
考虑到我的打印机为直连,掩码我配置的为255.255.255.255
将02myroutes文件设置为属于root,并且只有拥有者可写(注:如设置错误,无法自动执行)
sudo chown root:root 02myroutes
sudo chomd 755 02myroutes
使NetworkManager-dispatcher.service在开机时启动:
sudo systemctl enable NetworkManager-dispatcher.service
重启电脑生效