萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 作業系統 >  >> Linux 教學

Linux 網路環境配置三大方法圖文教學

Linux 網路配置可透過互動式工具、命令列臨時設定、配置檔永久修改三種方式實現,適用不同場景需求。

方法一:互動式工具 (nmtui / nmcli / system-config-network)

nmtui (文字介面,推薦新手)


nmtui
# 選擇 "Edit a connection" → 編輯/新增 → 設定 IPv4 Manual → Addresses/Gateway/DNS → OK → Activate

nmcli (命令列,適合腳本自動化)


# 查看連線
nmcli con show

# 新增靜態 IP 連線
nmcli con add type ethernet con-name "Wired-static" ifname eth0 \
  ipv4.method manual ipv4.addresses 192.168.1.100/24 \
  ipv4.gateway 192.168.1.1 ipv4.dns "192.168.1.1 8.8.8.8"

# 啟用
nmcli con up "Wired-static"

# 修改現有連線
nmcli con mod "Wired-static" ipv4.dns "1.1.1.1 8.8.8.8"

方法二:ifconfig/ip 命令臨時配置 (重啟失效)


# 舊指令 ifconfig (net-tools)
ifconfig eth0 192.168.1.100 netmask 255.255.255.0 up
route add default gw 192.168.1.1

# 現代 ip 指令 (iproute2,推薦)
ip addr add 192.168.1.100/24 dev eth0
ip link set eth0 up
ip route add default via 192.168.1.1

# 臨時新增 IP (別名)
ip addr add 192.168.1.200/24 dev eth0 label eth0:1

方法三:直接修改網路配置檔 (永久生效)

RHEL/CentOS/Fedora (/etc/sysconfig/network-scripts/ifcfg-eth0)


TYPE=Ethernet
BOOTPROTO=none          # static (none) 或 dhcp
DEFROUTE=yes
NAME=eth0
DEVICE=eth0
ONBOOT=yes
IPADDR=192.168.1.100
PREFIX=24               # 或 NETMASK=255.255.255.0
GATEWAY=192.168.1.1
DNS1=192.168.1.1
DNS2=8.8.8.8
IPV6INIT=no
# NM_CONTROLLED=no      # 若由 NetworkManager 管理設為 yes

Debian/Ubuntu (/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 192.168.1.1 8.8.8.8

# DHCP 範例
# iface eth0 inet dhcp

Netplan (Ubuntu 17.10+)


# /etc/netplan/01-netcfg.yaml
network:
  version: 2
  renderer: networkd
  ethernets:
    eth0:
      addresses: [192.168.1.100/24]
      gateway4: 192.168.1.1
      nameservers:
        addresses: [192.168.1.1, 8.8.8.8]
# 套用
netplan apply

套用變更與驗證


# RHEL 系
systemctl restart network
# 或
nmcli con reload && nmcli con up "Wired-static"

# Debian 系
systemctl restart networking
# 或
ifdown eth0 && ifup eth0

# 通用驗證
ip -br a
ip route
cat /etc/resolv.conf
ping -c 3 8.8.8.8

DHCP 動態獲取配置

  • nmtui/nmcli:IPv4 Method 選 Automatic (DHCP)
  • ifcfg-eth0:BOOTPROTO=dhcp
  • /etc/network/interfaces:iface eth0 inet dhcp
  • Netplan:dhcp4: true

多 IP / VLAN / Bonding 進階配置

  • 多 IP:同一介面多條 IPADDR2/PREFIX2 或 ip addr add
  • VLAN:nmcli con add type vlan con-name vlan10 dev eth0 id 10
  • Bonding (Mode 4 LACP):nmcli con add type bond con-name bond0 mode 802.3ad + 從屬介面

掌握三種配置方式差異:nmtui/nmcli 適合桌面/互動/自動化;ip 指令 適合臨時測試/容器網路;配置檔 適合伺服器永久部署、版控管理、基礎設施即代碼 (IaC)。

copyright © 萬盛學電腦網 all rights reserved