Skip to content

网络配置

本章将介绍 Linux 网络配置,包括网络接口管理、IP 地址配置、路由设置、DNS 配置、防火墙管理以及远程连接等内容。

网络基础

网络接口命名

bash
# 传统命名
eth0, eth1, eth2...    # 以太网接口
wlan0, wlan1...        # 无线接口
lo                     # 本地回环

# 新式命名(systemd)
enp0s3                 # 以太网(en)+ PCI 位置
wlp2s0                 # 无线(wl)+ PCI 位置
ens33                  # 以太网 + 插槽号

# 查看网络接口
ip link show
ip a

# 查看简短信息
ip -br a

网络配置文件

bash
# Debian/Ubuntu
/etc/network/interfaces        # 传统配置
/etc/netplan/*.yaml           # Netplan 配置(新版)

# RHEL/CentOS
/etc/sysconfig/network-scripts/ifcfg-eth0    # 传统配置
/etc/sysconfig/network-scripts/route-eth0    # 路由配置

# 通用配置文件
/etc/hosts                    # 主机名解析
/etc/resolv.conf              # DNS 配置
/etc/hostname                 # 主机名
/etc/services                 # 服务端口映射

ip 命令

查看网络信息

bash
# ip - 强大的网络配置工具

# 查看所有网络接口
ip link show
ip link
ip a

# 查看指定接口
ip link show eth0

# 查看 IP 地址
ip addr show
ip a show eth0

# 简短格式
ip -br a

# 查看路由表
ip route show
ip r

# 查看 ARP 表
ip neigh show
ip n

# 查看网络统计
ip -s link show eth0

# 查看详细统计
ip -s -s link show eth0

配置 IP 地址

bash
# 添加 IP 地址
sudo ip addr add 192.168.1.100/24 dev eth0

# 添加多个 IP 地址
sudo ip addr add 192.168.1.101/24 dev eth0

# 删除 IP 地址
sudo ip addr del 192.168.1.100/24 dev eth0

# 清除所有 IP 地址
sudo ip addr flush dev eth0

# 启用接口
sudo ip link set eth0 up

# 禁用接口
sudo ip link set eth0 down

# 修改 MAC 地址
sudo ip link set eth0 address 00:11:22:33:44:55

# 修改 MTU
sudo ip link set eth0 mtu 9000

# 修改接口名称
sudo ip link set eth0 name lan0

路由管理

bash
# 查看路由表
ip route show

# 添加默认网关
sudo ip route add default via 192.168.1.1

# 添加静态路由
sudo ip route add 10.0.0.0/8 via 192.168.1.1

# 添加路由到指定接口
sudo ip route add 192.168.2.0/24 dev eth1

# 删除路由
sudo ip route del 10.0.0.0/8

# 删除默认网关
sudo ip route del default

# 替换路由
sudo ip route replace default via 192.168.1.2

# 查看到达目标的路径
ip route get 8.8.8.8

# 清空路由表
sudo ip route flush table main

网络接口配置

Netplan 配置(Ubuntu)

bash
# Netplan 配置文件
/etc/netplan/*.yaml

# 查看配置
cat /etc/netplan/00-installer-config.yaml

# DHCP 配置示例
network:
  version: 2
  renderer: networkd
  ethernets:
    eth0:
      dhcp4: true

# 静态 IP 配置示例
network:
  version: 2
  renderer: networkd
  ethernets:
    eth0:
      addresses:
        - 192.168.1.100/24
      routes:
        - to: default
          via: 192.168.1.1
      nameservers:
        addresses:
          - 8.8.8.8
          - 8.8.4.4
      search:
        - example.com

# 多接口配置
network:
  version: 2
  renderer: networkd
  ethernets:
    eth0:
      addresses: [192.168.1.100/24]
      routes:
        - to: default
          via: 192.168.1.1
    eth1:
      addresses: [10.0.0.100/24]

# 应用配置
sudo netplan apply

# 测试配置(自动回滚)
sudo netplan try

# 生成配置
sudo netplan generate

NetworkManager 配置

bash
# nmcli - NetworkManager 命令行工具

# 查看设备状态
nmcli device status

# 查看连接
nmcli connection show

# 查看连接详情
nmcli connection show "Wired connection 1"

# 创建新连接(DHCP)
sudo nmcli connection add type ethernet con-name "eth0" ifname eth0

# 创建静态 IP 连接
sudo nmcli connection add type ethernet con-name "static" ifname eth0 \
  ip4 192.168.1.100/24 gw4 192.168.1.1

# 修改连接
sudo nmcli connection modify "static" ipv4.addresses 192.168.1.101/24
sudo nmcli connection modify "static" ipv4.gateway 192.168.1.1
sudo nmcli connection modify "static" ipv4.dns "8.8.8.8,8.8.4.4"

# 启用连接
sudo nmcli connection up "static"

# 禁用连接
sudo nmcli connection down "static"

# 删除连接
sudo nmcli connection delete "static"

# 启用/禁用设备
sudo nmcli device connect eth0
sudo nmcli device disconnect eth0

# 查看网络状态
nmcli general status

# 查看设备详情
nmcli device show eth0

传统配置文件(RHEL/CentOS)

bash
# ifcfg 配置文件
/etc/sysconfig/network-scripts/ifcfg-eth0

# DHCP 配置
DEVICE=eth0
BOOTPROTO=dhcp
ONBOOT=yes

# 静态 IP 配置
DEVICE=eth0
BOOTPROTO=static
IPADDR=192.168.1.100
NETMASK=255.255.255.0
GATEWAY=192.168.1.1
DNS1=8.8.8.8
DNS2=8.8.4.4
ONBOOT=yes

# 重启网络服务
sudo systemctl restart network

# 或使用 nmcli
sudo nmcli connection reload
sudo nmcli connection up eth0

DNS 配置

resolv.conf

bash
# /etc/resolv.conf - DNS 配置文件

# 查看当前配置
cat /etc/resolv.conf

# 示例配置
nameserver 8.8.8.8
nameserver 8.8.4.4
search example.com local
options timeout:2 attempts:3

# 字段说明:
# nameserver - DNS 服务器地址
# search     - 搜索域名
# domain     - 本地域名
# options    - 选项

# 注意:现代系统可能由 systemd-resolved 或 NetworkManager 管理
# 直接修改可能被覆盖

# 使用 systemd-resolved
sudo systemctl status systemd-resolved
sudo resolvectl status

# 设置 DNS
sudo resolvectl dns eth0 8.8.8.8 8.8.4.4

/etc/hosts

bash
# /etc/hosts - 本地主机名解析

# 查看配置
cat /etc/hosts

# 格式
# IP地址    主机名    别名

# 示例
127.0.0.1       localhost
192.168.1.100   server1.example.com server1
192.168.1.101   server2.example.com server2

# 添加条目
echo "192.168.1.200  myserver" | sudo tee -a /etc/hosts

# 测试解析
getent hosts server1

网络诊断工具

ping - 测试连通性

bash
# ping - 测试网络连通性

# 基本测试
ping 8.8.8.8

# 测试主机名
ping google.com

# 指定次数
ping -c 4 8.8.8.8

# 指定间隔(秒)
ping -i 2 8.8.8.8

# 指定包大小
ping -s 1000 8.8.8.8

# 设置 TTL
ping -t 64 8.8.8.8

# 洪水 ping(需要 root)
sudo ping -f 8.8.8.8

# 显示时间戳
ping -D 8.8.8.8

traceroute - 路由追踪

bash
# traceroute - 追踪数据包路由

# 基本用法
traceroute google.com

# 使用 ICMP
traceroute -I google.com

# 使用 TCP
traceroute -T google.com

# 指定端口
traceroute -p 80 google.com

# 指定最大跳数
traceroute -m 30 google.com

# 指定源地址
traceroute -s 192.168.1.100 google.com

# tracepath - 简化版路由追踪
tracepath google.com

netstat 和 ss

bash
# netstat - 网络统计(旧工具)

# 查看所有连接
netstat -a

# 查看 TCP 连接
netstat -t

# 查看 UDP 连接
netstat -u

# 查看监听端口
netstat -l

# 显示数字地址
netstat -n

# 显示进程信息
netstat -p

# 常用组合
netstat -tlnp    # TCP 监听端口 + 进程
netstat -ulnp    # UDP 监听端口 + 进程
netstat -an      # 所有连接,数字显示

# ss - 新一代网络统计工具

# 查看所有连接
ss -a

# 查看 TCP 连接
ss -t

# 查看 UDP 连接
ss -u

# 查看监听端口
ss -l

# 显示数字地址
ss -n

# 显示进程信息
ss -p

# 常用组合
ss -tlnp    # TCP 监听端口 + 进程
ss -ulnp    # UDP 监听端口 + 进程
ss -s       # 统计摘要

# 查看指定端口
ss -tlnp | grep :80
ss -tlnp sport = :80

# 查看指定状态的连接
ss -t state established
ss -t state time-wait

curl 和 wget

bash
# curl - 数据传输工具

# 获取网页
curl https://example.com

# 保存到文件
curl -o page.html https://example.com
curl -O https://example.com/file.zip

# 显示响应头
curl -I https://example.com

# 显示详细信息
curl -v https://example.com

# 发送 POST 请求
curl -X POST -d "key=value" https://example.com/api

# 发送 JSON
curl -H "Content-Type: application/json" -d '{"key":"value"}' https://example.com/api

# 携带认证
curl -u user:pass https://example.com
curl -H "Authorization: Bearer token" https://example.com

# 下载文件
curl -O -C - https://example.com/largefile.zip

# 测试响应时间
curl -w "DNS: %{time_namelookup}s\nConnect: %{time_connect}s\nTotal: %{time_total}s\n" -o /dev/null -s https://example.com

# wget - 文件下载工具

# 下载文件
wget https://example.com/file.zip

# 指定保存名称
wget -O myfile.zip https://example.com/file.zip

# 断点续传
wget -c https://example.com/largefile.zip

# 后台下载
wget -b https://example.com/file.zip

# 递归下载网站
wget -r -np -k https://example.com

# 限速下载
wget --limit-rate=1m https://example.com/file.zip

# 下载多个文件
wget -i urls.txt

nslookup 和 dig

bash
# nslookup - DNS 查询

# 查询域名
nslookup google.com

# 指定 DNS 服务器
nslookup google.com 8.8.8.8

# 查询特定记录
nslookup -type=mx google.com
nslookup -type=ns google.com
nslookup -type=txt google.com

# dig - 高级 DNS 查询

# 基本查询
dig google.com

# 指定 DNS 服务器
dig @8.8.8.8 google.com

# 查询特定记录
dig google.com MX
dig google.com NS
dig google.com TXT
dig google.com A
dig google.com AAAA

# 简短输出
dig +short google.com

# 显示 DNS 解析过程
dig +trace google.com

# 反向解析
dig -x 8.8.8.8

防火墙管理

ufw - Ubuntu 防火墙

bash
# ufw (Uncomplicated Firewall) - Ubuntu 默认防火墙

# 查看状态
sudo ufw status
sudo ufw status verbose

# 启用防火墙
sudo ufw enable

# 禁用防火墙
sudo ufw disable

# 重置规则
sudo ufw reset

# 允许端口
sudo ufw allow 22
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp

# 允许服务
sudo ufw allow ssh
sudo ufw allow http
sudo ufw allow https

# 拒绝端口
sudo ufw deny 23

# 允许特定 IP
sudo ufw allow from 192.168.1.100

# 允许特定 IP 访问特定端口
sudo ufw allow from 192.168.1.100 to any port 22

# 允许网段
sudo ufw allow from 192.168.1.0/24

# 删除规则
sudo ufw delete allow 80

# 查看规则编号
sudo ufw status numbered

# 删除指定编号的规则
sudo ufw delete 3

# 限制连接(防止暴力破解)
sudo ufw limit ssh

# 日志
sudo ufw logging on
sudo ufw logging medium

firewalld - RHEL/CentOS 防火墙

bash
# firewalld - RHEL/CentOS 默认防火墙

# 查看状态
sudo systemctl status firewalld
sudo firewall-cmd --state

# 启动/停止
sudo systemctl start firewalld
sudo systemctl stop firewalld
sudo systemctl enable firewalld

# 查看所有规则
sudo firewall-cmd --list-all

# 查看开放的端口
sudo firewall-cmd --list-ports

# 开放端口
sudo firewall-cmd --add-port=80/tcp
sudo firewall-cmd --add-port=443/tcp

# 永久开放端口
sudo firewall-cmd --permanent --add-port=80/tcp

# 移除端口
sudo firewall-cmd --remove-port=80/tcp
sudo firewall-cmd --permanent --remove-port=80/tcp

# 开放服务
sudo firewall-cmd --add-service=http
sudo firewall-cmd --add-service=https
sudo firewall-cmd --permanent --add-service=http

# 查看可用服务
sudo firewall-cmd --get-services

# 查看区域
sudo firewall-cmd --get-zones
sudo firewall-cmd --get-active-zones

# 设置默认区域
sudo firewall-cmd --set-default-zone=public

# 允许特定 IP
sudo firewall-cmd --add-source=192.168.1.100

# 端口转发
sudo firewall-cmd --add-forward-port=port=80:proto=tcp:toport=8080

# 重新加载配置
sudo firewall-cmd --reload

iptables - 底层防火墙

bash
# iptables - Linux 内核级防火墙

# 查看规则
sudo iptables -L
sudo iptables -L -n -v
sudo iptables -L --line-numbers

# 查看指定链
sudo iptables -L INPUT

# 允许端口
sudo iptables -A INPUT -p tcp --dport 22 -j ACCEPT
sudo iptables -A INPUT -p tcp --dport 80 -j ACCEPT

# 拒绝端口
sudo iptables -A INPUT -p tcp --dport 23 -j DROP

# 允许特定 IP
sudo iptables -A INPUT -s 192.168.1.100 -j ACCEPT

# 拒绝特定 IP
sudo iptables -A INPUT -s 192.168.1.100 -j DROP

# 允许已建立的连接
sudo iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

# 允许本地回环
sudo iptables -A INPUT -i lo -j ACCEPT

# 设置默认策略
sudo iptables -P INPUT DROP
sudo iptables -P FORWARD DROP
sudo iptables -P OUTPUT ACCEPT

# 删除规则
sudo iptables -D INPUT 1

# 清空所有规则
sudo iptables -F

# 保存规则
sudo iptables-save > /etc/iptables/rules.v4
sudo iptables-restore < /etc/iptables/rules.v4

远程连接

SSH 连接

bash
# ssh - 安全远程连接

# 基本连接
ssh user@192.168.1.100
ssh -p 2222 user@192.168.1.100

# 使用密钥连接
ssh -i ~/.ssh/id_rsa user@192.168.1.100

# 执行远程命令
ssh user@192.168.1.100 'ls -la'

# 端口转发(本地)
ssh -L 8080:localhost:80 user@remote

# 端口转发(远程)
ssh -R 8080:localhost:80 user@remote

# 动态端口转发(SOCKS 代理)
ssh -D 1080 user@remote

# 保持连接
ssh -o ServerAliveInterval=60 user@remote

# 后台运行
ssh -fN user@remote

# 复制文件
scp file.txt user@remote:/path/
scp -r directory/ user@remote:/path/

# 使用 rsync
rsync -avz file.txt user@remote:/path/
rsync -avz -e "ssh -p 2222" file.txt user@remote:/path/

SSH 密钥管理

bash
# 生成 SSH 密钥
ssh-keygen -t rsa -b 4096
ssh-keygen -t ed25519

# 指定文件名
ssh-keygen -f ~/.ssh/mykey

# 添加注释
ssh-keygen -t rsa -b 4096 -C "myemail@example.com"

# 复制公钥到远程
ssh-copy-id user@remote
ssh-copy-id -i ~/.ssh/mykey.pub user@remote

# 手动复制公钥
cat ~/.ssh/id_rsa.pub | ssh user@remote 'cat >> ~/.ssh/authorized_keys'

# 管理密钥代理
eval "$(ssh-agent -s)"
ssh-add ~/.ssh/id_rsa
ssh-add -l    # 列出已添加的密钥
ssh-add -d ~/.ssh/id_rsa    # 删除密钥
ssh-add -D    # 删除所有密钥

# SSH 配置文件 ~/.ssh/config
Host myserver
    HostName 192.168.1.100
    User username
    Port 2222
    IdentityFile ~/.ssh/mykey
    ServerAliveInterval 60

# 使用配置连接
ssh myserver

小结

本章介绍了 Linux 网络配置:

内容命令功能
接口管理ip, nmcli网络接口配置
IP 配置ip addr, netplanIP 地址管理
路由管理ip route路由表管理
DNSresolv.conf, hosts域名解析
诊断ping, traceroute, ss网络诊断
防火墙ufw, firewalld, iptables防火墙管理
远程连接ssh, scp, rsync远程访问

常用命令速查

bash
# 网络信息
ip a                            # 查看 IP 地址
ip r                            # 查看路由
ss -tlnp                        # 查看监听端口

# 网络诊断
ping google.com                 # 测试连通性
traceroute google.com           # 路由追踪
dig google.com                  # DNS 查询

# 防火墙
sudo ufw allow 80               # 开放端口
sudo ufw status                 # 查看状态

# 远程连接
ssh user@host                   # SSH 连接
scp file user@host:/path/       # 复制文件

下一步

下一章我们将学习 Shell 脚本编程,了解如何编写自动化脚本。