Linux教程 / 第 120 节
第12章:网络基础命令
掌握网络诊断和远程连接,成为网络问题排查高手
本章目标
- 理解基本的网络概念(IP、端口、DNS等)
- 掌握网络诊断命令(ping、traceroute、netstat等)
- 学会使用SSH进行远程连接和管理
- 能够排查常见的网络连接问题
12.1 网络基础概念
12.1.1 IP地址
IPv4地址: 由4个0-255的数字组成,用点分隔
192.168.1.100
10.0.0.1
172.16.0.50
特殊IP地址:
127.0.0.1: 本地回环地址(localhost)0.0.0.0: 所有接口192.168.x.x: 私有网络10.x.x.x: 私有网络172.16.x.x - 172.31.x.x: 私有网络
IPv6地址: 128位,用冒号分隔
2001:0db8:85a3:0000:0000:8a2e:0370:7334
::1 (本地回环)
12.1.2 端口号
端口号范围: 0-65535
常用端口:
22: SSH80: HTTP443: HTTPS21: FTP3306: MySQL5432: PostgreSQL6379: Redis27017: MongoDB8080: 常用Web开发端口3000: Node.js默认端口
12.1.3 DNS
DNS (Domain Name System) 将域名转换为IP地址
www.google.com → 142.250.185.46
github.com → 140.82.113.4
12.2 查看网络配置
12.2.1 查看网络接口 - ip
# 查看所有网络接口
ip addr
# 或简写
ip a
# 查看特定接口
ip addr show eth0
# 查看接口统计信息
ip -s link
# 输出示例:
# 1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536
# inet 127.0.0.1/8 scope host lo
# 2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500
# inet 192.168.1.100/24 brd 192.168.1.255 scope global eth0
# inet6 fe80::a00:27ff:fe4e:66a1/64 scope link
字段说明:
lo: 本地回环接口eth0: 以太网接口wlan0: 无线网络接口inet: IPv4地址inet6: IPv6地址UP: 接口已启用
12.2.2 传统命令 - ifconfig
# 查看所有接口(需要安装net-tools)
ifconfig
# 查看特定接口
ifconfig eth0
# 启用/禁用接口(需要root)
sudo ifconfig eth0 up
sudo ifconfig eth0 down
⚠️ 注意: ifconfig已被ip命令取代,但仍广泛使用
12.2.3 查看路由表
# 查看路由表
ip route
# 或
route -n
# 输出示例:
# default via 192.168.1.1 dev eth0
# 192.168.1.0/24 dev eth0 proto kernel scope link src 192.168.1.100
字段说明:
default: 默认网关via: 通过哪个网关dev: 使用哪个网络接口
12.2.4 查看DNS配置
# 查看DNS服务器
cat /etc/resolv.conf
# 输出示例:
# nameserver 8.8.8.8
# nameserver 8.8.4.4
12.3 网络连通性测试
12.3.1 ping - 测试连通性
# 基本用法
ping google.com
# 发送指定次数的包
ping -c 4 google.com
# 设置包大小(字节)
ping -s 1000 google.com
# 设置超时时间(秒)
ping -W 2 google.com
# 只显示摘要
ping -c 10 -q google.com
# 输出示例:
# PING google.com (142.250.185.46) 56(84) bytes of data.
# 64 bytes from 142.250.185.46: icmp_seq=1 ttl=117 time=15.2 ms
# 64 bytes from 142.250.185.46: icmp_seq=2 ttl=117 time=14.8 ms
#
# --- google.com ping statistics ---
# 2 packets transmitted, 2 received, 0% packet loss, time 1001ms
# rtt min/avg/max/mdev = 14.800/15.000/15.200/0.200 ms
实战场景: 诊断网络问题
# 1. 测试本地回环
ping -c 3 127.0.0.1
# 成功 → 网络栈正常
# 2. 测试网关
ping -c 3 192.168.1.1
# 成功 → 本地网络正常
# 3. 测试外网IP
ping -c 3 8.8.8.8
# 成功 → 互联网连接正常
# 4. 测试域名
ping -c 3 google.com
# 成功 → DNS解析正常
# 失败 → DNS问题
12.3.2 traceroute - 路由追踪
# 安装traceroute
sudo apt-get install traceroute # Ubuntu/Debian
sudo yum install traceroute # CentOS/RHEL
# 基本用法
traceroute google.com
# 使用ICMP(需要root)
sudo traceroute -I google.com
# 限制跳数
traceroute -m 15 google.com
# 输出示例:
# traceroute to google.com (142.250.185.46), 30 hops max, 60 byte packets
# 1 192.168.1.1 (192.168.1.1) 1.234 ms 1.123 ms 1.056 ms
# 2 10.0.0.1 (10.0.0.1) 5.678 ms 5.432 ms 5.234 ms
# 3 * * *
# 4 142.250.185.46 (142.250.185.46) 15.234 ms 15.123 ms 15.056 ms
用途: 查看数据包经过的路由,诊断网络延迟
12.3.3 mtr - 增强版traceroute
# 安装mtr
sudo apt-get install mtr
# 基本用法(实时更新)
mtr google.com
# 报告模式(发送10个包后退出)
mtr -r -c 10 google.com
# 优势:
# - 实时更新
# - 显示丢包率
# - 显示平均延迟
12.4 端口和连接管理
12.4.1 netstat - 网络统计
# 查看所有监听端口
netstat -tuln
# 查看所有连接
netstat -tun
# 查看进程信息
sudo netstat -tulnp
# 查看路由表
netstat -r
# 常用选项:
# -t: TCP连接
# -u: UDP连接
# -l: 监听状态
# -n: 数字格式(不解析域名)
# -p: 显示进程信息
# 输出示例:
# Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program
# tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN 1234/sshd
# tcp 0 0 127.0.0.1:3306 0.0.0.0:* LISTEN 5678/mysqld
实战场景: 查看端口占用
# 查看8080端口是否被占用
sudo netstat -tulnp | grep :8080
# 如果输出:
# tcp 0 0 0.0.0.0:8080 0.0.0.0:* LISTEN 1234/node
# 说明端口被PID 1234的node进程占用
12.4.2 ss - 现代替代品
# ss比netstat更快,推荐使用
# 查看所有监听端口
ss -tuln
# 查看所有连接
ss -tun
# 查看进程信息
sudo ss -tulnp
# 查看特定端口
ss -tuln | grep :80
# 查看TCP连接统计
ss -s
# 输出示例:
# Total: 500
# TCP: 200 (estab 50, closed 100, orphaned 0, timewait 50)
12.4.3 lsof - 查看打开的文件和端口
# 查看所有网络连接
sudo lsof -i
# 查看特定端口
sudo lsof -i :8080
# 查看特定协议
sudo lsof -i tcp
sudo lsof -i udp
# 查看特定进程的网络连接
sudo lsof -i -p PID
# 查看特定用户的网络连接
sudo lsof -i -u username
# 输出示例:
# COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
# node 1234 user 10u IPv4 12345 0t0 TCP *:8080 (LISTEN)
实战场景: 找出占用端口的进程
# 方法1: lsof
sudo lsof -i :8080
# 方法2: netstat
sudo netstat -tulnp | grep :8080
# 方法3: ss
sudo ss -tulnp | grep :8080
# 方法4: fuser
sudo fuser 8080/tcp
12.5 DNS查询
12.5.1 nslookup
# 基本查询
nslookup google.com
# 指定DNS服务器
nslookup google.com 8.8.8.8
# 查询特定记录类型
nslookup -type=MX google.com # 邮件服务器
nslookup -type=NS google.com # 域名服务器
nslookup -type=A google.com # IPv4地址
nslookup -type=AAAA google.com # IPv6地址
# 输出示例:
# Server: 8.8.8.8
# Address: 8.8.8.8#53
#
# Non-authoritative answer:
# Name: google.com
# Address: 142.250.185.46
12.5.2 dig - 强大的DNS工具
# 安装dig
sudo apt-get install dnsutils # Ubuntu/Debian
sudo yum install bind-utils # CentOS/RHEL
# 基本查询
dig google.com
# 简洁输出
dig google.com +short
# 指定DNS服务器
dig @8.8.8.8 google.com
# 查询特定记录
dig google.com MX
dig google.com NS
dig google.com A
dig google.com AAAA
# 反向查询(IP到域名)
dig -x 142.250.185.46
# 追踪DNS查询路径
dig google.com +trace
# 输出示例:
# ; <<>> DiG 9.16.1 <<>> google.com
# ;; ANSWER SECTION:
# google.com. 300 IN A 142.250.185.46
12.5.3 host - 简单DNS查询
# 基本查询
host google.com
# 查询特定记录
host -t MX google.com
host -t NS google.com
# 反向查询
host 142.250.185.46
# 输出示例:
# google.com has address 142.250.185.46
# google.com has IPv6 address 2404:6800:4003:c00::71
12.6 SSH远程连接
12.6.1 SSH基础
SSH (Secure Shell) 是安全的远程登录协议
基本连接:
# 连接到远程服务器
ssh username@hostname
# 指定端口
ssh -p 2222 username@hostname
# 示例
ssh alice@192.168.1.100
ssh root@example.com
12.6.2 SSH密钥认证
生成SSH密钥:
# 生成RSA密钥对
ssh-keygen -t rsa -b 4096 -C "your_email@example.com"
# 生成ED25519密钥对(更安全,更快)
ssh-keygen -t ed25519 -C "your_email@example.com"
# 交互过程:
# Enter file in which to save the key (/home/user/.ssh/id_rsa): [回车]
# Enter passphrase (empty for no passphrase): [输入密码或回车]
# Enter same passphrase again: [再次输入]
# 生成的文件:
# ~/.ssh/id_rsa (私钥,保密!)
# ~/.ssh/id_rsa.pub (公钥,可分享)
复制公钥到服务器:
# 方法1: 使用ssh-copy-id(推荐)
ssh-copy-id username@hostname
# 方法2: 手动复制
cat ~/.ssh/id_rsa.pub | ssh username@hostname "mkdir -p ~/.ssh && cat >> ~/.ssh/authorized_keys"
# 方法3: 直接编辑
ssh username@hostname
mkdir -p ~/.ssh
chmod 700 ~/.ssh
nano ~/.ssh/authorized_keys
# 粘贴公钥内容
chmod 600 ~/.ssh/authorized_keys
使用密钥登录:
# 自动使用默认密钥
ssh username@hostname
# 指定密钥文件
ssh -i ~/.ssh/custom_key username@hostname
12.6.3 SSH配置文件
客户端配置 (~/.ssh/config):
# 创建配置文件
nano ~/.ssh/config
# 配置示例
Host myserver
HostName 192.168.1.100
User alice
Port 22
IdentityFile ~/.ssh/id_rsa
Host github
HostName github.com
User git
IdentityFile ~/.ssh/github_key
Host *
ServerAliveInterval 60
ServerAliveCountMax 3
# 设置权限
chmod 600 ~/.ssh/config
# 使用配置
ssh myserver # 等同于 ssh alice@192.168.1.100
服务器配置 (/etc/ssh/sshd_config):
# 编辑配置(需要root)
sudo nano /etc/ssh/sshd_config
# 常用安全配置
Port 22 # 修改默认端口提高安全性
PermitRootLogin no # 禁止root直接登录
PasswordAuthentication no # 禁用密码登录,只允许密钥
PubkeyAuthentication yes # 启用密钥认证
MaxAuthTries 3 # 最大认证尝试次数
ClientAliveInterval 300 # 保持连接
ClientAliveCountMax 2
# 重启SSH服务使配置生效
sudo systemctl restart sshd
12.6.4 SSH高级用法
端口转发(隧道):
# 本地端口转发
# 将本地8080端口转发到远程服务器的80端口
ssh -L 8080:localhost:80 username@hostname
# 访问 http://localhost:8080 实际访问远程的80端口
# 远程端口转发
# 将远程8080端口转发到本地80端口
ssh -R 8080:localhost:80 username@hostname
# 动态端口转发(SOCKS代理)
ssh -D 1080 username@hostname
# 配置浏览器使用localhost:1080作为SOCKS代理
执行远程命令:
# 执行单条命令
ssh username@hostname "ls -la"
# 执行多条命令
ssh username@hostname "cd /var/log && tail -n 20 syslog"
# 执行本地脚本
ssh username@hostname 'bash -s' < local-script.sh
文件传输 - scp:
# 上传文件到服务器
scp local-file.txt username@hostname:/remote/path/
# 下载文件从服务器
scp username@hostname:/remote/file.txt /local/path/
# 上传目录(递归)
scp -r local-directory username@hostname:/remote/path/
# 指定端口
scp -P 2222 file.txt username@hostname:/path/
# 使用压缩(加快传输)
scp -C large-file.tar.gz username@hostname:/path/
文件传输 - rsync:
# rsync比scp更高效,支持增量传输
# 同步目录到服务器
rsync -avz local-directory/ username@hostname:/remote/path/
# 从服务器同步到本地
rsync -avz username@hostname:/remote/path/ local-directory/
# 常用选项:
# -a: 归档模式(保留权限、时间等)
# -v: 详细输出
# -z: 压缩传输
# -P: 显示进度,支持断点续传
# --delete: 删除目标中多余的文件
# 实战示例:部署网站
rsync -avz --delete public/ user@server:/var/www/html/
12.7 网络下载
12.7.1 wget
# 下载文件
wget https://example.com/file.zip
# 下载并重命名
wget -O custom-name.zip https://example.com/file.zip
# 断点续传
wget -c https://example.com/large-file.iso
# 后台下载
wget -b https://example.com/file.zip
tail -f wget-log # 查看进度
# 限速下载(KB/s)
wget --limit-rate=200k https://example.com/file.zip
# 下载整个网站(镜像)
wget -r -np -k https://example.com/
# 使用代理
wget -e use_proxy=yes -e http_proxy=127.0.0.1:1080 https://example.com/file.zip
12.7.2 curl
# 下载文件
curl -O https://example.com/file.zip
# 下载并重命名
curl -o custom-name.zip https://example.com/file.zip
# 断点续传
curl -C - -O https://example.com/large-file.iso
# 跟随重定向
curl -L https://example.com/redirect
# 显示详细信息
curl -v https://example.com
# 只显示HTTP头
curl -I https://example.com
# POST请求
curl -X POST -d "param1=value1¶m2=value2" https://api.example.com
# 发送JSON
curl -X POST -H "Content-Type: application/json" -d '{"key":"value"}' https://api.example.com
# 使用代理
curl -x http://127.0.0.1:1080 https://example.com
# 测试API
curl -X GET https://api.github.com/users/octocat
12.8 防火墙基础
12.8.1 ufw (Ubuntu)
# 启用防火墙
sudo ufw enable
# 禁用防火墙
sudo ufw disable
# 查看状态
sudo ufw status
sudo ufw status verbose
# 允许端口
sudo ufw allow 22
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
# 拒绝端口
sudo ufw deny 23
# 删除规则
sudo ufw delete allow 80
# 允许特定IP
sudo ufw allow from 192.168.1.100
# 允许特定IP访问特定端口
sudo ufw allow from 192.168.1.100 to any port 22
# 重置防火墙
sudo ufw reset
12.8.2 firewalld (CentOS/RHEL)
# 启动防火墙
sudo systemctl start firewalld
sudo systemctl enable firewalld
# 查看状态
sudo firewall-cmd --state
sudo firewall-cmd --list-all
# 允许服务
sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --permanent --add-service=https
# 允许端口
sudo firewall-cmd --permanent --add-port=8080/tcp
# 移除端口
sudo firewall-cmd --permanent --remove-port=8080/tcp
# 重新加载配置
sudo firewall-cmd --reload
12.9 实战场景
场景1: 诊断网站无法访问
# 1. 测试DNS解析
nslookup example.com
dig example.com +short
# 2. 测试网络连通性
ping -c 4 example.com
# 3. 测试端口是否开放
telnet example.com 80
# 或
nc -zv example.com 80
# 4. 查看路由
traceroute example.com
# 5. 测试HTTP响应
curl -I https://example.com
# 6. 检查本地DNS缓存
sudo systemd-resolve --flush-caches # Ubuntu
场景2: 配置SSH免密登录
# 本地机器操作:
# 1. 生成密钥(如果没有)
ssh-keygen -t ed25519 -C "your_email@example.com"
# 2. 复制公钥到服务器
ssh-copy-id user@server
# 3. 测试登录
ssh user@server
# 4. 配置别名(可选)
nano ~/.ssh/config
# 添加:
# Host myserver
# HostName server.example.com
# User username
# IdentityFile ~/.ssh/id_ed25519
# 5. 使用别名登录
ssh myserver
场景3: 部署Web应用
# 1. 连接到服务器
ssh user@server
# 2. 更新系统
sudo apt-get update && sudo apt-get upgrade -y
# 3. 安装Nginx
sudo apt-get install nginx -y
# 4. 启动Nginx
sudo systemctl start nginx
sudo systemctl enable nginx
# 5. 配置防火墙
sudo ufw allow 22
sudo ufw allow 80
sudo ufw allow 443
sudo ufw enable
# 6. 上传网站文件(本地执行)
rsync -avz --delete ./public/ user@server:/var/www/html/
# 7. 设置权限
ssh user@server "sudo chown -R www-data:www-data /var/www/html"
# 8. 测试
curl http://server-ip
场景4: 监控网络连接
# 查看当前连接数
ss -s
# 查看ESTABLISHED连接
ss -tun state established
# 查看连接最多的IP
netstat -ntu | awk '{print $5}' | cut -d: -f1 | sort | uniq -c | sort -nr | head -10
# 实时监控网络流量
sudo apt-get install iftop
sudo iftop -i eth0
# 或使用nethogs(按进程)
sudo apt-get install nethogs
sudo nethogs eth0
场景5: 端口扫描
# 使用nmap扫描端口
sudo apt-get install nmap
# 扫描单个主机
nmap 192.168.1.100
# 扫描端口范围
nmap -p 1-1000 192.168.1.100
# 扫描常用端口
nmap --top-ports 100 192.168.1.100
# 检测操作系统
sudo nmap -O 192.168.1.100
# 扫描网段
nmap 192.168.1.0/24
12.10 常见问题
Q1: SSH连接超时怎么办?
A:
# 1. 检查网络连通性
ping server-ip
# 2. 检查端口是否开放
telnet server-ip 22
nc -zv server-ip 22
# 3. 检查防火墙
sudo ufw status
sudo firewall-cmd --list-all
# 4. 检查SSH服务
sudo systemctl status sshd
# 5. 查看SSH日志
sudo tail -f /var/log/auth.log # Ubuntu
sudo tail -f /var/log/secure # CentOS
Q2: 如何修改SSH默认端口?
A:
# 1. 编辑配置
sudo nano /etc/ssh/sshd_config
# 修改: Port 2222
# 2. 更新防火墙
sudo ufw allow 2222/tcp
# 3. 重启SSH
sudo systemctl restart sshd
# 4. 测试新端口
ssh -p 2222 user@server
Q3: 如何查看网络流量?
A:
# 方法1: iftop
sudo iftop -i eth0
# 方法2: nethogs(按进程)
sudo nethogs
# 方法3: vnstat(统计)
sudo apt-get install vnstat
vnstat -i eth0
Q4: DNS解析失败怎么办?
A:
# 1. 检查DNS配置
cat /etc/resolv.conf
# 2. 测试DNS服务器
nslookup google.com 8.8.8.8
# 3. 临时修改DNS
sudo nano /etc/resolv.conf
# 添加: nameserver 8.8.8.8
# 4. 清除DNS缓存
sudo systemd-resolve --flush-caches
Q5: 如何测试网络速度?
A:
# 安装speedtest-cli
sudo apt-get install speedtest-cli
# 测试速度
speedtest-cli
# 或使用fast.com
curl -s https://raw.githubusercontent.com/sivel/speedtest-cli/master/speedtest.py | python3 -
本章总结
核心命令回顾
| 命令 | 用途 | 示例 |
|---|---|---|
ip addr | 查看网络接口 | ip addr show eth0 |
ping | 测试连通性 | ping -c 4 google.com |
traceroute | 路由追踪 | traceroute google.com |
ss | 查看连接 | ss -tulnp |
dig | DNS查询 | dig google.com +short |
ssh | 远程连接 | ssh user@host |
scp | 文件传输 | scp file user@host:/path/ |
curl | HTTP请求 | curl -O https://example.com/file |
网络诊断流程
- 测试本地:
ping 127.0.0.1 - 测试网关:
ping 192.168.1.1 - 测试外网:
ping 8.8.8.8 - 测试DNS:
ping google.com - 查看路由:
traceroute google.com
SSH安全最佳实践
- ✅ 使用密钥认证,禁用密码登录
- ✅ 修改默认端口(22)
- ✅ 禁止root直接登录
- ✅ 限制登录尝试次数
- ✅ 使用防火墙限制访问IP
下一步
- 学习FTP文件传输(第13章)
- 掌握更多文件传输方式
- 了解自动化部署流程
练习题:
- 测试到google.com的网络连通性和路由
- 配置SSH密钥登录到远程服务器
- 使用rsync同步本地目录到服务器
- 查看本机所有监听的端口
参考答案:
# 1.
ping -c 4 google.com
traceroute google.com
# 2.
ssh-keygen -t ed25519
ssh-copy-id user@server
ssh user@server
# 3.
rsync -avz local-dir/ user@server:/remote/path/
# 4.
sudo ss -tulnp
💡 提示: 网络命令是运维的基础,熟练掌握这些工具能快速定位和解决网络问题!