怎么查询Linux中ens的网关怎么设置
怎么查询Linux中ens的网关怎么设置详细介绍
在 Linux 系统中查询和设置 ens 系列网络接口(如 ens33)的网关,主要涉及网络配置文件或命令行工具的操作。以下是具体方法:
一、查询当前网关
无论采用哪种设置方式,都可以先通过命令查询当前生效的网关:
1. 使用
ip 命令(推荐)
bash
route show default
输出示例:
plaintext
default via 192.168.1.1 dev ens33 proto static
其中 192.168.1.1 即为当前网关地址。
2. 使用
route 命令(传统方式)
bash
route
输出示例中,Gateway 列的 0.0.0.0 表示非网关路由,非 0.0.0.0 的地址即为网关(通常对应 ens 接口的行):
plaintext
Kernel IP routing tableDestination Gateway Genmask Flags Metric Ref Use Iface
0.0.0.0 192.168.1.1 0.0.0.0 UG 100 0 0 ens33
二、设置网关(永久生效)
网关的设置方式与 Linux 发行版及网络管理工具(如 NetworkManager、netplan 等)有关,以下是常见场景的操作方法:
场景 1:CentOS/RHEL(使用 ifcfg 配置文件)
- 编辑对应
ens接口的配置文件(路径通常为/etc/sysconfig/network-scripts/ifcfg-ensXX,XX为接口编号,如ifcfg-ens33):
bash/etc/sysconfig/network-scripts/ifcfg-ens33 - 确保以下参数存在(按需修改):
ini - 保存文件后,重启网络服务使配置生效:
bashsystemctl restart network
场景 2:Ubuntu 18.04+(使用 netplan 配置)
Ubuntu 18.04 及以上版本默认使用 netplan 管理网络(配置文件在 /etc/netplan/ 目录下,通常文件名类似 00-installer-config.yaml)。
- 编辑
netplan配置文件:
bash/etc/netplan/00-installer-config.yaml - 配置示例(静态 IP + 网关):
yamlno
192.168.1.100/24
default
192.168.1.1
114.114.114.114 8.8.8.8
若需通过 DHCP 自动获取网关(通常适用于局域网),将
dhcp4: no改为dhcp4: yes,网关会由 DHCP 服务器自动分配。 - 应用配置:
bashnetplan apply
场景 3:Ubuntu 16.04 及以下(使用 interfaces 文件)
旧版本 Ubuntu 使用 /etc/network/interfaces 配置网络:
- 编辑配置文件:
bash/etc/network/interfaces - 配置示例(静态 IP + 网关):
iniauto ens33iface ens33 inet static
address 192.168.1.100 # 本地IP
netmask 255.255.255.0 # 子网掩码
gateway 192.168.1.1 # 目标网关地址
dns-nameservers 114.114.114.114 8.8.8.8 # 可选:DNS服务器
- 重启网络服务:
bash/etc/init.d/networking restart
三、临时设置网关(重启后失效)
若仅需临时修改网关(测试用途),可以使用 ip route 命令:
bash
route del default
route default via .1.1 dev ens33
注意事项
- 网关地址必须与本地 IP 在同一网段(例如本地 IP 为
192.168.1.100/24,网关需为192.168.1.0/24网段内的有效地址)。 - 修改网络配置前建议备份原配置文件,避免操作失误导致网络中断。
- 若使用
NetworkManager(如桌面版 Ubuntu),部分配置可能需要通过nmcli命令或图形界面工具(如nmtui)调整。
通过以上方法,你可以根据具体的 Linux 发行版和需求,查询或设置 ens 接口的网关。