一、普通上网模式:
对于有线网络,如果默认没有安装图形界面,进入了 multi-user.target中时,是没有使用NetworkManager管理网络的,此时需要手动配置才能上网
首先得到网卡名称:ip addr or ls /sys/class/net/,以下假设网卡名为eth0,实际中应替换为自己实际的名称。
设置文件为:/etc/network/interfaces
使用DHCP方式,在文件底部添加:
auto eth0
allow-hotplug eth0
iface eth0 inet dhcp
手动设置IP上网,在文件底部添加:
auto eth0
iface eth0 inet static
address 192.168.0.7
netmask 255.255.255.0
gateway 192.168.0.254
重启网络服务sudo systemctl restart networking.service
详细的设置方法可以使用man interfaces得到,也可以参考这里:https://wiki.debian.org/NetworkConfiguration
二、更推荐的作法是使用NetworkManager来管理网络
sudo apt install networkmanager(debian12包名改为了network-manager)安装NetworkManager包后,命令行中多出两个命令,一个是nmcli纯命令的网络配置工具,一个是nmtui的终端图形配置工具。
在文件/etc/network/interfaces中注释掉下面两行
allow-hotplug eth0
iface eth0 inet dhcp
在/etc/NetworkManager/NetworkManager.conf中把managed=false改为managed=true
nmtui打开图形界面,直接配置就好,当然也可以在这里设置无线连接的。
sudo systemctl restart NetworkManager.service重启服务。
如果你不喜欢nmtui图形化的方式,那就使用nmcli命令来配置网络(redhat 9.x同样适用):
配置文件最终写入的文件位置:/etc/NetworkManager/system-connections/xxx.nmconnection
查看NetworkManager管理的配置文件:sudo nmcli connection show,得到配置文件名字office
NAME UUID TYPE DEVICE
office d2841104-ee92-378e-855b-1b7b39c87acb ethernet ens160
lo 56b0209b-3695-4ac6-9bde-b06b9653b7ae loopback lo
可以创建不同的配置文件,在需要的时候激活对应的配置文件即可:
# 创建一个新的名为home的配置文件,绑定了类型为ethernet网卡ens160sudo nmcli connection add con-name "home" ifname "ens160" type ethernet
每创建一个新的配置文件,在/etc/NetworkManager/system-connections/目录中会多出一个x.nmconnection文件,查看现在的配置文件,会发现多了一个:
NAME UUID TYPE DEVICE
office 3b757737-5053-41d3-a251-bd07ed867437 ethernet ens160
lo 56b0209b-3695-4ac6-9bde-b06b9653b7ae loopback lo
home d2841104-ee92-378e-855b-1b7b39c87acb ethernet --
激活使用名为home的配置文件进行网络连接:sudo nmcli connection up home,再次查看配置文件,得到:
NAME UUID TYPE DEVICE
home 3b757737-5053-41d3-a251-bd07ed867437 ethernet ens160
lo 56b0209b-3695-4ac6-9bde-b06b9653b7ae loopback lo
office d2841104-ee92-378e-855b-1b7b39c87acb ethernet --
由上可知,如果一个设备ens160绑定了多个配置文件,激活的配置文件在首行,并且DEVICE列显示对应的设备名称。
配置文件是可以改名的,配置文件home改名为samuel's home.:sudo nmcli connection modify "home" connection.id "samuel's home"
联网dhcp或手动设置:
配置文件office采用dhcp方式连网:sudo nmcli connection modify office ipv4.method auto
配置文件office手动设置ip等信息:sudo nmcli connection modify office ipv4.method manual ipv4.addresses 172.16.63.100 ipv4.gateway 172.16.63.2 ipv4.dns 172.16.63.2 ipv4.dns-search example.com,此时查看一下NetworkManager管理的配置文件的内容:
# /etc/NetworkManager/system-connections/xxx.nmconnection[ipv4]
address1=172.16.63.100/32,172.16.63.2
dns=172.16.63.2;
dns-search=example.com;
method=manual
不要忘记激活以使用新的配置文件:sudo nmcli connection up office
在python等脚本中也可以直接修改存放的配置文件内容/etc/NetworkManager/system-connections/xxx.nmconnection,并且激活sudo nmcli connection up office以使用修改后的配置文件。此种方法需要注意重新启动主机才会生效。