插件窝 干货文章 如何在Linux上设置网络接口

如何在Linux上设置网络接口

配置 sudo bash 83    来源:    2025-04-15

在Linux上设置网络接口可以通过命令行工具或配置文件完成,以下是详细步骤和常见方法:


一、使用 ip 命令(推荐)

ip 是现代Linux发行版中替代旧版 ifconfig 的工具,功能更强大。

1. 查看当前网络接口

ip addr show
# 或简写
ip a

2. 启用/禁用接口

# 启用接口(如eth0)
sudo ip link set eth0 up

# 禁用接口
sudo ip link set eth0 down

3. 分配IP地址

# 临时分配IP(重启失效)
sudo ip addr add 192.168.1.100/24 dev eth0

4. 设置默认网关

sudo ip route add default via 192.168.1.1

二、使用 ifconfig(旧版工具,部分系统需安装)

# 安装(Debian/Ubuntu)
sudo apt install net-tools

# 查看接口
ifconfig

# 分配IP
sudo ifconfig eth0 192.168.1.100 netmask 255.255.255.0

三、通过配置文件(永久生效)

不同Linux发行版的配置文件路径不同:

1. Debian/Ubuntu(使用netplan/etc/network/interfaces

  • 方法1:传统配置

    sudo nano /etc/network/interfaces
    

    示例内容:

    auto eth0
    iface eth0 inet static
      address 192.168.1.100
      netmask 255.255.255.0
      gateway 192.168.1.1
      dns-nameservers 8.8.8.8
    
  • 方法2:Netplan(新版Ubuntu) 编辑YAML文件(如/etc/netplan/01-netcfg.yaml):

    network:
    version: 2
    ethernets:
      eth0:
        dhcp4: no
        addresses: [192.168.1.100/24]
        gateway4: 192.168.1.1
        nameservers:
          addresses: [8.8.8.8, 1.1.1.1]
    

    应用配置:

    sudo netplan apply
    

2. RHEL/CentOS/Fedora

编辑配置文件: bash sudo nano /etc/sysconfig/network-scripts/ifcfg-eth0 示例内容: plaintext DEVICE=eth0 BOOTPROTO=static IPADDR=192.168.1.100 NETMASK=255.255.255.0 GATEWAY=192.168.1.1 DNS1=8.8.8.8 ONBOOT=yes 重启网络服务: bash sudo systemctl restart NetworkManager # 或旧版 sudo service network restart

3. Arch Linux

使用systemd-networkdNetworkManager,例如: bash sudo nano /etc/systemd/network/eth0.network 示例内容: ```plaintext [Match] Name=eth0

[Network] Address=192.168.1.100/24 Gateway=192.168.1.1 DNS=8.8.8.8 启用服务:bash sudo systemctl enable --now systemd-networkd ```


四、设置DNS

临时修改:

sudo nano /etc/resolv.conf
# 添加
nameserver 8.8.8.8

注意:某些系统会覆盖此文件,建议通过配置文件永久修改。

永久修改:

  • Debian/Ubuntu:在/etc/network/interfaces或Netplan配置中添加DNS。
  • RHEL/CentOS:在ifcfg-eth0中添加DNS1=8.8.8.8

五、验证配置

# 检查IP
ip addr show eth0

# 测试连通性
ping 8.8.8.8

# 检查路由
ip route show

# 检查DNS
nslookup example.com

常见问题

  1. 接口未找到

    • 确认接口名:ip link show(现代系统可能使用enp0s3等命名)。
    • 检查驱动:lspci | grep -i ethernet
  2. 配置不生效

    • 重启网络服务或系统。
    • 禁用NetworkManager干扰(传统系统):
      bash sudo systemctl stop NetworkManager sudo systemctl disable NetworkManager
  3. DHCP获取IP
    在配置文件中将BOOTPROTOdhcp4设为yes/true


通过以上方法,您可以灵活地配置Linux网络接口。根据发行版选择合适的工具和配置文件即可。