网络命令

网络命令是Linux系统管理的重要工具,掌握这些命令可以帮助您远程管理服务器、传输文件、监控网络状态。本章将详细介绍常用的网络命令及其使用方法。


一、SSH远程连接

1.1 SSH基础

1.1.1 SSH简介

SSH(Secure Shell):安全的远程登录协议。

SSH特点

  • 加密传输数据
  • 支持多种认证方式
  • 端口转发功能
  • 文件传输功能

东巴文理解:SSH就像一条安全的隧道,让您远程控制服务器。

1.1.2 SSH客户端

安装SSH客户端

# Debian/Ubuntu
sudo apt install openssh-client

# CentOS/RHEL
sudo dnf install openssh-clients

基本连接

# 连接远程服务器
ssh username@hostname

# 指定端口连接
ssh -p 2222 username@hostname

# 使用IP地址连接
ssh username@192.168.1.100

# 首次连接提示
# The authenticity of host '192.168.1.100 (192.168.1.100)' can't be established.
# ECDSA key fingerprint is SHA256:abc123...
# Are you sure you want to continue connecting (yes/no)? yes
# Warning: Permanently added '192.168.1.100' (ECDSA) to the list of known hosts.
# username@192.168.1.100's password:

东巴文提示:首次连接会提示确认服务器指纹,输入yes继续。

1.1.3 SSH配置文件

客户端配置文件~/.ssh/config

配置示例

# 创建配置文件
mkdir -p ~/.ssh
chmod 700 ~/.ssh
vim ~/.ssh/config

# 配置内容
# 默认配置
Host *
    ServerAliveInterval 60
    ServerAliveCountMax 3

# 服务器别名
Host myserver
    HostName 192.168.1.100
    User username
    Port 22

# 使用密钥认证
Host git-server
    HostName github.com
    User git
    IdentityFile ~/.ssh/id_rsa_github

# 跳板机配置
Host target-server
    HostName 10.0.0.100
    User username
    ProxyJump jump-server

Host jump-server
    HostName 192.168.1.200
    User jumpuser

# 设置文件权限
chmod 600 ~/.ssh/config

使用别名连接

# 使用别名连接
ssh myserver

# 相当于
ssh username@192.168.1.100

1.2 SSH密钥认证

1.2.1 生成SSH密钥

生成密钥对

# 生成RSA密钥(默认)
ssh-keygen -t rsa

# 生成RSA密钥(指定位数)
ssh-keygen -t rsa -b 4096

# 生成ED25519密钥(推荐)
ssh-keygen -t ed25519

# 生成ECDSA密钥
ssh-keygen -t ecdsa -b 521

# 指定文件名和注释
ssh-keygen -t rsa -b 4096 -C "your_email@example.com" -f ~/.ssh/id_rsa_custom

# 交互过程
# Generating public/private rsa key pair.
# Enter file in which to save the key (/home/user/.ssh/id_rsa): 
# Enter passphrase (empty for no passphrase): 
# Enter same passphrase again: 
# Your identification has been saved in /home/user/.ssh/id_rsa
# Your public key has been saved in /home/user/.ssh/id_rsa_private
# The key fingerprint is:
# SHA256:abc123... your_email@example.com
# The key's randomart image is:
# +---[RSA 4096]----+
# |     .o.         |
# |     ..          |
# |    .  .         |
# |   . .  .        |
# |  . . . S        |
# | . . . .         |
# |  . . .          |
# |   . .           |
# |    .            |
# +----[SHA256]-----+

东巴文最佳实践:推荐使用ED25519密钥,更安全且性能更好。

1.2.2 复制公钥到服务器

使用ssh-copy-id

# 复制公钥到服务器
ssh-copy-id username@hostname

# 指定端口
ssh-copy-id -p 2222 username@hostname

# 指定公钥文件
ssh-copy-id -i ~/.ssh/id_rsa.pub username@hostname

# 输出示例:
# /usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/home/user/.ssh/id_rsa.pub"
# /usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s)
# /usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed
# username@hostname's password: 
# 
# Number of key(s) added: 1
# 
# Now try logging into the machine with: "ssh 'username@hostname'"
# and check to make sure that only the key(s) you wanted were added.

手动复制公钥

# 查看公钥
cat ~/.ssh/id_rsa.pub

# 输出示例:
# ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQ... user@localhost

# 登录服务器
ssh username@hostname

# 创建.ssh目录
mkdir -p ~/.ssh
chmod 700 ~/.ssh

# 添加公钥
echo "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQ... user@localhost" >> ~/.ssh/authorized_keys

# 设置权限
chmod 600 ~/.ssh/authorized_keys

东巴文提示:确保.ssh目录和authorized_keys文件权限正确。

1.2.3 使用密钥登录

# 使用默认密钥登录
ssh username@hostname

# 指定密钥文件登录
ssh -i ~/.ssh/id_rsa_custom username@hostname

# 在配置文件中指定密钥
Host myserver
    HostName 192.168.1.100
    User username
    IdentityFile ~/.ssh/id_rsa_custom

1.3 SSH服务器配置

1.3.1 安装SSH服务器

# Debian/Ubuntu
sudo apt install openssh-server

# CentOS/RHEL
sudo dnf install openssh-server

# 启动SSH服务
sudo systemctl start sshd

# 设置开机自启
sudo systemctl enable sshd

# 查看状态
sudo systemctl status sshd

# 输出示例:
# ● sshd.service - OpenSSH Daemon
#    Loaded: loaded (/lib/systemd/system/sshd.service; enabled; vendor preset: enabled)
#    Active: active (running) since Mon 2024-01-01 10:00:00 CST; 1h ago
#  Main PID: 1234 (sshd)
#     Tasks: 1 (limit: 4915)
#    Memory: 2.5M
#    CGroup: /system.slice/sshd.service
#            └─1234 /usr/sbin/sshd -D

1.3.2 SSH服务器配置文件

配置文件/etc/ssh/sshd_config

常用配置项

# 编辑配置文件
sudo vim /etc/ssh/sshd_config

# 常用配置
# 监听端口
Port 22

# 监听地址
ListenAddress 0.0.0.0

# 协议版本
Protocol 2

# 允许root登录(不推荐)
PermitRootLogin no

# 允许密钥认证
PubkeyAuthentication yes

# 允许密码认证
PasswordAuthentication yes

# 禁用空密码
PermitEmptyPasswords no

# 允许的用户
AllowUsers user1 user2

# 允许的用户组
AllowGroups sshusers

# 登录超时时间
LoginGraceTime 60

# 最大认证尝试次数
MaxAuthTries 3

# 是否允许X11转发
X11Forwarding yes

# 是否允许TCP转发
AllowTcpForwarding yes

# 子系统配置
Subsystem sftp /usr/lib/openssh/sftp-server

东巴文安全建议

  • 禁用root登录
  • 使用密钥认证,禁用密码认证
  • 修改默认端口
  • 限制登录用户

1.3.3 重启SSH服务

# 检查配置语法
sudo sshd -t

# 重启SSH服务
sudo systemctl restart sshd

# 重新加载配置
sudo systemctl reload sshd

# 查看SSH服务日志
sudo journalctl -u sshd -f

1.4 SSH高级功能

1.4.1 SSH端口转发

本地端口转发

# 本地端口转发
# 将本地8080端口转发到远程服务器的80端口
ssh -L 8080:localhost:80 username@remote-server

# 访问内网服务
# 将本地3306端口转发到内网MySQL服务器
ssh -L 3306:10.0.0.100:3306 username@jump-server

# 使用配置文件
Host tunnel-mysql
    HostName jump-server
    User username
    LocalForward 3306 10.0.0.100:3306

远程端口转发

# 远程端口转发
# 将远程服务器的8080端口转发到本地80端口
ssh -R 8080:localhost:80 username@remote-server

# 允许远程服务器监听所有接口
ssh -R 0.0.0.0:8080:localhost:80 username@remote-server

动态端口转发(SOCKS代理)

# 创建SOCKS代理
ssh -D 1080 username@remote-server

# 使用配置文件
Host socks-proxy
    HostName remote-server
    User username
    DynamicForward 1080

# 配置浏览器使用SOCKS代理
# 代理地址:127.0.0.1
# 代理端口:1080

东巴文理解:SSH端口转发就像建立秘密通道,让数据安全地穿越防火墙。

1.4.2 SSH跳板

使用跳板机

# 方法1:使用-J参数
ssh -J jumpuser@jump-server targetuser@target-server

# 方法2:使用ProxyJump配置
Host target-server
    HostName 10.0.0.100
    User targetuser
    ProxyJump jumpuser@jump-server

# 方法3:使用ProxyCommand配置
Host target-server
    HostName 10.0.0.100
    User targetuser
    ProxyCommand ssh jumpuser@jump-server -W %h:%p

1.4.3 SSH代理

SSH代理:管理SSH密钥的工具。

# 启动SSH代理
eval "$(ssh-agent -s)"

# 输出示例:
# Agent pid 12345

# 添加密钥到代理
ssh-add ~/.ssh/id_rsa

# 添加密钥(带密码)
ssh-add ~/.ssh/id_rsa_encrypted

# 查看已添加的密钥
ssh-add -l

# 输出示例:
# 256 SHA256:abc123... user@localhost (ED25519)
# 4096 SHA256:def456... user@localhost (RSA)

# 删除所有密钥
ssh-add -D

# 删除指定密钥
ssh-add -d ~/.ssh/id_rsa

# 锁定代理
ssh-add -x

# 解锁代理
ssh-add -X

东巴文提示:使用SSH代理可以避免重复输入密钥密码。

1.4.4 SSH隧道保持连接

客户端保持连接

# 在~/.ssh/config中添加
Host *
    ServerAliveInterval 60
    ServerAliveCountMax 3

服务器端保持连接

# 在/etc/ssh/sshd_config中添加
ClientAliveInterval 60
ClientAliveCountMax 3

1.5 SSH安全加固

1.5.1 禁用密码认证

# 编辑配置文件
sudo vim /etc/ssh/sshd_config

# 修改配置
PasswordAuthentication no
PubkeyAuthentication yes

# 重启SSH服务
sudo systemctl restart sshd

东巴文警告:确保密钥认证配置正确后再禁用密码认证,否则可能无法登录。

1.5.2 使用Fail2Ban

安装Fail2Ban

# Debian/Ubuntu
sudo apt install fail2ban

# CentOS/RHEL
sudo dnf install fail2ban

# 启动服务
sudo systemctl start fail2ban
sudo systemctl enable fail2ban

配置SSH保护

# 创建配置文件
sudo vim /etc/fail2ban/jail.local

# 配置内容
[sshd]
enabled = true
port = ssh
filter = sshd
logpath = /var/log/auth.log
maxretry = 3
findtime = 600
bantime = 3600

# 重启服务
sudo systemctl restart fail2ban

# 查看状态
sudo fail2ban-client status sshd

# 输出示例:
# Status for the jail: sshd
# |- Filter
# |  |- Currently failed: 0
# |  |- Total failed:     5
# |  `- File list:        /var/log/auth.log
# `- Actions
#    |- Currently banned: 1
#    |- Total banned:     1
#    `- Banned IP list:   192.168.1.100

东巴文理解:Fail2Ban就像门卫,自动拦截多次尝试失败的IP。


二、文件传输命令

2.1 SCP命令

2.1.1 SCP基础

SCP(Secure Copy):基于SSH的安全文件传输工具。

上传文件

# 上传文件到远程服务器
scp local_file.txt username@remote-server:/path/to/destination/

# 上传并重命名
scp local_file.txt username@remote-server:/path/to/remote_file.txt

# 上传目录
scp -r local_directory/ username@remote-server:/path/to/destination/

# 指定端口
scp -P 2222 local_file.txt username@remote-server:/path/to/destination/

# 显示传输进度
scp -v local_file.txt username@remote-server:/path/to/destination/

# 压缩传输
scp -C local_file.txt username@remote-server:/path/to/destination/

# 限制传输速度(KB/s)
scp -l 800 local_file.txt username@remote-server:/path/to/destination/

下载文件

# 从远程服务器下载文件
scp username@remote-server:/path/to/remote_file.txt /local/path/

# 下载目录
scp -r username@remote-server:/path/to/remote_directory/ /local/path/

# 使用通配符
scp username@remote-server:/path/to/*.txt /local/path/

服务器间传输

# 从服务器1传输到服务器2
scp user1@server1:/path/to/file.txt user2@server2:/path/to/destination/

# 通过本地转发
scp -3 user1@server1:/path/to/file.txt user2@server2:/path/to/destination/

东巴文提示:SCP适合小文件传输,大文件推荐使用rsync。

2.2 Rsync命令

2.2.1 Rsync基础

Rsync:高效的文件同步和传输工具。

Rsync特点

  • 增量传输
  • 支持压缩
  • 保持权限和时间戳
  • 支持排除规则

基本语法

rsync [选项] 源 目标

常用选项

选项 说明
-a 归档模式,保持权限、时间戳等
-v 显示详细信息
-h 人类可读格式
-z 压缩传输
-P 显示进度和断点续传
-r 递归传输
-u 跳过已存在且更新的文件
--delete 删除目标端多余文件
--exclude 排除文件
--include 包含文件

2.2.2 本地文件同步

# 同步目录
rsync -avh /source/directory/ /destination/directory/

# 同步并删除目标端多余文件
rsync -avh --delete /source/directory/ /destination/directory/

# 显示进度
rsync -avhP /source/directory/ /destination/directory/

# 排除文件
rsync -avh --exclude='*.log' /source/directory/ /destination/directory/

# 排除多个文件
rsync -avh --exclude={'*.log','*.tmp','*.bak'} /source/directory/ /destination/directory/

# 包含和排除规则
rsync -avh --include='*.txt' --exclude='*' /source/directory/ /destination/directory/

# 模拟运行(不实际传输)
rsync -avh --dry-run /source/directory/ /destination/directory/

东巴文提示:注意路径末尾的斜杠,有斜杠表示目录内容,无斜杠表示目录本身。

2.2.3 远程文件同步

# 上传到远程服务器
rsync -avhP /local/directory/ username@remote-server:/remote/path/

# 从远程服务器下载
rsync -avhP username@remote-server:/remote/directory/ /local/path/

# 使用SSH指定端口
rsync -avhP -e 'ssh -p 2222' /local/directory/ username@remote-server:/remote/path/

# 使用SSH密钥
rsync -avhP -e 'ssh -i ~/.ssh/id_rsa' /local/directory/ username@remote-server:/remote/path/

# 限制带宽(KB/s)
rsync -avhP --bwlimit=1000 /local/directory/ username@remote-server:/remote/path/

# 显示统计信息
rsync -avhP --stats /local/directory/ username@remote-server:/remote/path/

2.2.4 Rsync实战案例

备份网站目录

# 备份网站目录到远程服务器
rsync -avhP --delete \
  --exclude='logs/*.log' \
  --exclude='tmp/*' \
  /var/www/html/ \
  backup@backup-server:/backup/web/

# 输出示例:
# sending incremental file list
# ./
# index.html
#     12.34K 100%   10.23MB/s    0:00:00 (xfr#1, to-chk=99/101)
# images/
# images/logo.png
#     45.67K 100%   15.45MB/s    0:00:00 (xfr#2, to-chk=97/101)
# 
# sent 58.23K bytes  received 1.23K bytes  39.64K bytes/sec
# total size is 1.23M  speedup is 20.67

定时备份脚本

#!/bin/bash
# 网站备份脚本

# 配置变量
SOURCE="/var/www/html/"
DEST="backup@backup-server:/backup/web/"
LOG="/var/log/backup.log"
DATE=$(date +%Y%m%d_%H%M%S)

# 执行备份
echo "[$DATE] 开始备份..." >> $LOG
rsync -avhP --delete \
  --exclude='logs/*.log' \
  --exclude='tmp/*' \
  --log-file=$LOG \
  $SOURCE $DEST

# 检查结果
if [ $? -eq 0 ]; then
    echo "[$DATE] 备份成功" >> $LOG
else
    echo "[$DATE] 备份失败" >> $LOG
    # 发送邮件通知
    echo "备份失败,请检查日志:$LOG" | mail -s "备份失败通知" admin@example.com
fi

东巴文最佳实践:定期备份重要数据,并验证备份的完整性。

2.3 FTP命令

2.3.1 FTP基础

FTP(File Transfer Protocol):文件传输协议。

安装FTP客户端

# Debian/Ubuntu
sudo apt install ftp

# CentOS/RHEL
sudo dnf install ftp

连接FTP服务器

# 连接FTP服务器
ftp ftp.example.com

# 输出示例:
# Connected to ftp.example.com.
# 220 Welcome to FTP server.
# Name (ftp.example.com:user): username
# 331 Please specify the password.
# Password:
# 230 Login successful.
# Remote system type is UNIX.
# Using binary mode to transfer files.
# ftp>

FTP常用命令

# FTP内部命令
ftp> help              # 显示帮助
ftp> ls                # 列出远程文件
ftp> cd directory      # 切换远程目录
ftp> pwd               # 显示远程当前目录
ftp> lcd /local/path   # 切换本地目录
ftp> binary            # 二进制模式
ftp> ascii             # ASCII模式
ftp> get file.txt      # 下载文件
ftp> mget *.txt        # 下载多个文件
ftp> put file.txt      # 上传文件
ftp> mput *.txt        # 上传多个文件
ftp> delete file.txt   # 删除远程文件
ftp> mkdir directory   # 创建远程目录
ftp> rmdir directory   # 删除远程目录
ftp> bye               # 退出FTP
ftp> quit              # 退出FTP

东巴文提示:FTP传输不加密,建议使用SFTP或SCP。

2.4 SFTP命令

2.4.1 SFTP基础

SFTP(SSH File Transfer Protocol):基于SSH的安全文件传输协议。

连接SFTP服务器

# 连接SFTP服务器
sftp username@remote-server

# 指定端口
sftp -P 2222 username@remote-server

# 输出示例:
# Connected to remote-server.
# sftp>

SFTP常用命令

# SFTP内部命令
sftp> help                  # 显示帮助
sftp> ls                    # 列出远程文件
sftp> lls                   # 列出本地文件
sftp> cd /remote/path       # 切换远程目录
sftp> lcd /local/path       # 切换本地目录
sftp> pwd                   # 显示远程当前目录
sftp> lpwd                  # 显示本地当前目录
sftp> get file.txt          # 下载文件
sftp> get -r directory      # 下载目录
sftp> put file.txt          # 上传文件
sftp> put -r directory      # 上传目录
sftp> rm file.txt           # 删除远程文件
sftp> rmdir directory       # 删除远程目录
sftp> mkdir directory       # 创建远程目录
sftp> chmod 755 file.txt    # 修改权限
sftp> chown user file.txt   # 修改所有者
sftp> exit                  # 退出SFTP
sftp> quit                  # 退出SFTP

东巴文理解:SFTP就像加密的FTP,更安全可靠。


三、网络下载工具

3.1 Wget命令

3.1.1 Wget基础

Wget:命令行下载工具。

基本下载

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

# 指定保存文件名
wget -O myfile.zip http://example.com/file.zip

# 断点续传
wget -c http://example.com/large_file.zip

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

# 限速下载(字节/秒)
wget --limit-rate=200k http://example.com/file.zip

# 显示下载进度
wget --progress=bar http://example.com/file.zip

# 静默模式
wget -q http://example.com/file.zip

# 输出示例:
# --2024-01-01 10:00:00--  http://example.com/file.zip
# Resolving example.com... 93.184.216.34
# Connecting to example.com|93.184.216.34|:80... connected.
# HTTP request sent, awaiting response... 200 OK
# Length: 12345678 (12M) [application/zip]
# Saving to: 'file.zip'
# 
# file.zip                100%[==================================>]  11.77M  1.23MB/s    in 9.6s    
# 
# 2024-01-01 10:00:10 (1.23 MB/s) - 'file.zip' saved [12345678/12345678]

3.1.2 批量下载

# 从文件读取URL下载
wget -i urls.txt

# urls.txt内容示例:
# http://example.com/file1.zip
# http://example.com/file2.zip
# http://example.com/file3.zip

# 下载网站镜像
wget -m http://example.com/

# 递归下载
wget -r http://example.com/

# 递归下载指定层级
wget -r -l 2 http://example.com/

# 只下载特定文件类型
wget -r -A "*.pdf" http://example.com/

# 排除特定文件类型
wget -r -R "*.jpg,*.png" http://example.com/

3.1.3 认证下载

# HTTP基本认证
wget --user=username --password=password http://example.com/protected/

# 从.netrc读取认证信息
wget --netrc http://example.com/protected/

# FTP认证
wget --ftp-user=username --ftp-password=password ftp://example.com/file.zip

3.1.4 代理设置

# 使用HTTP代理
wget -e use_proxy=yes -e http_proxy=proxy.example.com:8080 http://example.com/

# 使用环境变量
export http_proxy=http://proxy.example.com:8080
export https_proxy=http://proxy.example.com:8080
wget http://example.com/

# 配置文件(~/.wgetrc)
use_proxy = on
http_proxy = http://proxy.example.com:8080
https_proxy = http://proxy.example.com:8080
ftp_proxy = http://proxy.example.com:8080

东巴文提示:Wget适合批量下载和网站镜像。

3.2 Curl命令

3.2.1 Curl基础

Curl:强大的数据传输工具。

基本使用

# 获取网页内容
curl http://example.com

# 下载文件
curl -O http://example.com/file.zip

# 指定保存文件名
curl -o myfile.zip http://example.com/file.zip

# 显示响应头
curl -i http://example.com

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

# 输出示例:
# HTTP/1.1 200 OK
# Date: Mon, 01 Jan 2024 10:00:00 GMT
# Server: Apache/2.4.41 (Ubuntu)
# Last-Modified: Sun, 31 Dec 2023 10:00:00 GMT
# Content-Type: text/html
# Content-Length: 12345
# Connection: keep-alive

# 显示进度条
curl -# -O http://example.com/file.zip

# 静默模式
curl -s http://example.com

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

3.2.2 HTTP请求

# GET请求
curl http://example.com/api

# POST请求
curl -X POST http://example.com/api

# POST表单数据
curl -X POST -d "name=value" http://example.com/api

# POST JSON数据
curl -X POST -H "Content-Type: application/json" -d '{"name":"value"}' http://example.com/api

# 上传文件
curl -X POST -F "file=@local_file.txt" http://example.com/upload

# PUT请求
curl -X PUT -d "data" http://example.com/api

# DELETE请求
curl -X DELETE http://example.com/api/1

# 自定义请求头
curl -H "Authorization: Bearer token" http://example.com/api

# 多个请求头
curl -H "Content-Type: application/json" -H "Authorization: Bearer token" http://example.com/api

# 发送Cookie
curl -b "name=value" http://example.com

# 保存Cookie
curl -c cookies.txt http://example.com

# 使用Cookie文件
curl -b cookies.txt http://example.com

3.2.3 认证请求

# HTTP基本认证
curl -u username:password http://example.com/protected

# Bearer Token认证
curl -H "Authorization: Bearer token" http://example.com/api

# OAuth认证
curl -H "Authorization: OAuth token" http://example.com/api

# 客户端证书认证
curl --cert client.crt --key client.key https://example.com

3.2.4 高级功能

# 跟随重定向
curl -L http://example.com

# 限制重定向次数
curl -L --max-redirs 5 http://example.com

# 设置超时时间
curl --max-time 30 http://example.com

# 设置连接超时
curl --connect-timeout 10 http://example.com

# 重试请求
curl --retry 3 http://example.com

# 重试延迟
curl --retry-delay 5 --retry 3 http://example.com

# 限速(字节/秒)
curl --limit-rate 100K http://example.com

# 使用代理
curl -x http://proxy.example.com:8080 http://example.com

# SOCKS代理
curl --socks5 proxy.example.com:1080 http://example.com

# 并发下载多个文件
curl -O http://example.com/file1.zip -O http://example.com/file2.zip

3.2.5 Curl实战案例

API测试

# 测试REST API
curl -X GET http://api.example.com/users

# 创建用户
curl -X POST \
  -H "Content-Type: application/json" \
  -d '{"name":"张三","email":"zhangsan@example.com"}' \
  http://api.example.com/users

# 更新用户
curl -X PUT \
  -H "Content-Type: application/json" \
  -d '{"name":"李四"}' \
  http://api.example.com/users/1

# 删除用户
curl -X DELETE http://api.example.com/users/1

监控网站状态

#!/bin/bash
# 网站监控脚本

URL="http://example.com"
STATUS=$(curl -s -o /dev/null -w "%{http_code}" $URL)

if [ $STATUS -eq 200 ]; then
    echo "网站正常,状态码:$STATUS"
else
    echo "网站异常,状态码:$STATUS" | mail -s "网站异常通知" admin@example.com
fi

东巴文理解:Curl是网络调试的瑞士军刀,功能强大且灵活。


四、网络监控工具

4.1 实时流量监控

4.1.1 iftop命令

iftop:实时网络流量监控工具。

# 安装iftop
sudo apt install iftop  # Debian/Ubuntu
sudo dnf install iftop  # CentOS/RHEL

# 监控所有网络接口
sudo iftop

# 监控指定接口
sudo iftop -i eth0

# 显示端口号
sudo iftop -P

# 显示DNS解析
sudo iftop -n

# 显示源端口和目标端口
sudo iftop -P -n

# 输出示例:
# Listening on eth0
#    12.5Kb          25.0Kb          37.5Kb          50.0Kb    62.5Kb
# └────────────────┴───────────────┴───────────────┴───────────────┴────────────────
# 192.168.1.100:ssh      => 192.168.1.1:54321      1.23Kb  1.45Kb  1.23Kb
#                        <=                        456b    512b    456b
# 192.168.1.100:http     => 192.168.1.50:12345     2.34Kb  2.56Kb  2.34Kb
#                        <=                        1.23Kb  1.34Kb  1.23Kb
# ────────────────────────────────────────────────────────────────────────────────
# TX:             cum:   12.3KB   peak:   5.67Kb  rates:   3.57Kb  4.01Kb  3.57Kb
# RX:                    23.4KB           10.23Kb           1.69Kb  1.85Kb  1.69Kb
# TOTAL:                 35.7KB           15.90Kb           5.26Kb  5.86Kb  5.26Kb

东巴文理解:iftop就像网络流量监控器,实时显示数据传输情况。

4.1.2 nload命令

nload:网络流量监控工具。

# 安装nload
sudo apt install nload  # Debian/Ubuntu
sudo dnf install nload  # CentOS/RHEL

# 监控所有网络接口
nload

# 监控指定接口
nload eth0

# 设置刷新间隔(毫秒)
nload -t 500

# 设置单位
nload -u M

# 输出示例:
# Device eth0 [192.168.1.100] (1/2):
# ===================================================================================
# Incoming:
#             Curr: 1.23 MBit/s
#             Avg: 1.45 MBit/s
#             Min: 0.00 Bit/s
#             Max: 5.67 MBit/s
#             Ttl: 1.23 GByte
# Outgoing:
#             Curr: 567.00 KBit/s
#             Avg: 678.00 KBit/s
#             Min: 0.00 Bit/s
#             Max: 2.34 MBit/s
#             Ttl: 567.00 MByte

4.1.3 nethogs命令

nethogs:按进程监控网络流量。

# 安装nethogs
sudo apt install nethogs  # Debian/Ubuntu
sudo dnf install nethogs  # CentOS/RHEL

# 监控所有网络接口
sudo nethogs

# 监控指定接口
sudo nethogs eth0

# 设置刷新间隔(秒)
sudo nethogs -d 2

# 显示模式(KB/s或B/s)
sudo nethogs -t

# 输出示例:
# PID     USER    PROGRAM              DEV        SENT      RECEIVED
# 1234    nginx   nginx                eth0       1.23KB    2.34KB
# 5678    mysql   mysqld               eth0       0.45KB    1.23KB
# 9012    user    chrome               eth0       5.67KB    12.34KB
# ?       root    unknown TCP                      0.00KB    0.00KB
# 
# TOTAL                                          7.35KB    15.91KB

东巴文提示:nethogs可以找出占用带宽最多的进程。

4.2 网络连接监控

4.2.1 netstat命令

netstat:网络统计信息工具。

# 查看所有连接
netstat -a

# 查看TCP连接
netstat -t

# 查看UDP连接
netstat -u

# 查看监听端口
netstat -l

# 查看端口号和PID
netstat -tulpn

# 查看路由表
netstat -r

# 查看网络统计
netstat -i

# 持续监控
netstat -c

# 查看特定端口
netstat -tulpn | grep :80

# 统计连接状态
netstat -nat | awk '{print $6}' | sort | uniq -c

# 输出示例:
#      5 ESTABLISHED
#     10 LISTEN
#      2 TIME_WAIT

4.2.2 ss命令

ss:socket统计工具(netstat的替代品)。

# 查看所有连接
ss -a

# 查看TCP连接
ss -t

# 查看UDP连接
ss -u

# 查看监听端口
ss -l

# 查看端口号和PID
ss -tulpn

# 查看已建立的连接
ss -tu

# 查看进程信息
ss -p

# 查看内存使用
ss -m

# 查看统计信息
ss -s

# 查看特定端口
ss -tulpn | grep :80

# 查看特定状态的连接
ss -tu state established

4.3 网络性能测试

4.3.1 iperf命令

iperf:网络性能测试工具。

# 安装iperf3
sudo apt install iperf3  # Debian/Ubuntu
sudo dnf install iperf3  # CentOS/RHEL

# 服务器端启动
iperf3 -s

# 输出示例:
# -----------------------------------------------------------
# Server listening on 5201
# -----------------------------------------------------------

# 客户端测试
iperf3 -c server-ip

# 输出示例:
# Connecting to host server-ip, port 5201
# [  5]   0.00-1.00   sec   112 MBytes   941 Mbits/sec    sender
# [  5]   0.00-1.00   sec   112 MBytes   941 Mbits/sec    receiver
# [  5]   1.00-2.00   sec   112 MBytes   941 Mbits/sec    sender
# [  5]   1.00-2.00   sec   112 MBytes   941 Mbits/sec    receiver
# - - - - - - - - - - - - - - - - - - - - - - - - -
# [ ID] Interval           Transfer     Bitrate         Retr
# [  5]   0.00-10.00  sec  1.12 GBytes   964 Mbits/sec    0             sender
# [  5]   0.00-10.00  sec  1.12 GBytes   964 Mbits/sec                  receiver

# 多线程测试
iperf3 -c server-ip -P 4

# 反向测试(下载)
iperf3 -c server-ip -R

# 指定测试时间
iperf3 -c server-ip -t 30

# 指定带宽
iperf3 -c server-ip -b 100M

# UDP测试
iperf3 -c server-ip -u

东巴文理解:iperf就像网络速度计,测量网络的实际性能。

4.3.2 ping命令

ping:测试网络连通性和延迟。

# 测试连通性
ping -c 4 google.com

# 输出示例:
# PING google.com (142.250.189.238) 56(84) bytes of data.
# 64 bytes from 142.250.189.238: icmp_seq=1 ttl=117 time=10.5 ms
# 64 bytes from 142.250.189.238: icmp_seq=2 ttl=117 time=10.3 ms
# 64 bytes from 142.250.189.238: icmp_seq=3 ttl=117 time=10.4 ms
# 64 bytes from 142.250.189.238: icmp_seq=4 ttl=117 time=10.2 ms
# 
# --- google.com ping statistics ---
# 4 packets transmitted, 4 received, 0% packet loss, time 3005ms
# rtt min/avg/max/mdev = 10.234/10.375/10.526/10.079 ms

# 持续ping
ping google.com

# 指定间隔
ping -i 0.5 google.com

# 指定包大小
ping -s 1000 google.com

# 设置TTL
ping -t 64 google.com

# 设置超时
ping -W 5 google.com

# 洪水ping(慎用)
ping -f google.com

4.4 网络诊断工具

4.4.1 mtr命令

mtr:结合ping和traceroute的工具。

# 安装mtr
sudo apt install mtr  # Debian/Ubuntu
sudo dnf install mtr  # CentOS/RHEL

# 实时诊断
mtr google.com

# 输出示例:
#                              My traceroute  [v0.93]
# localhost (192.168.1.100)                        2024-01-01T10:00:00+0800
# Keys:  Help   Display mode   Restart statistics   Order of fields   quit
#                                       Packets               Pings
#  Host                               Loss%   Snt   Last   Avg  Best  Wrst StDev
#   1. _gateway                       0.0%    10    1.2   1.3   1.1   1.5   0.1
#   2. 10.0.0.1                       0.0%    10    5.6   5.7   5.5   5.9   0.1
#   3. 172.16.0.1                     0.0%    10   10.1  10.2  10.0  10.4   0.1
#   4. ???
#   5. 142.250.189.238                0.0%    10   15.6  15.7  15.5  15.9   0.1

# 生成报告
mtr -r -c 10 google.com > mtr_report.txt

# 生成CSV报告
mtr -r -c 10 --csv google.com > mtr_report.csv

东巴文提示:mtr可以持续监控网络质量,发现网络问题。

4.4.2 nmap命令

nmap:网络扫描和安全审计工具。

# 安装nmap
sudo apt install nmap  # Debian/Ubuntu
sudo dnf install nmap  # CentOS/RHEL

# 扫描主机
nmap 192.168.1.100

# 扫描多个主机
nmap 192.168.1.1-254

# 扫描网段
nmap 192.168.1.0/24

# 扫描端口
nmap -p 80,443 192.168.1.100

# 扫描端口范围
nmap -p 1-1000 192.168.1.100

# 扫描所有端口
nmap -p- 192.168.1.100

# 操作系统检测
nmap -O 192.168.1.100

# 服务版本检测
nmap -sV 192.168.1.100

# 全面扫描
nmap -A 192.168.1.100

# 输出示例:
# Starting Nmap 7.80 ( https://nmap.org ) at 2024-01-01 10:00 CST
# Nmap scan report for 192.168.1.100
# Host is up (0.00012s latency).
# PORT     STATE SERVICE
# 22/tcp   open  ssh
# 80/tcp   open  http
# 443/tcp  open  https
# 3306/tcp open  mysql
# MAC Address: 00:0C:29:12:34:56 (VMware)
# 
# Nmap done: 1 IP address (1 host up) scanned in 0.23 seconds

东巴文警告:未经授权扫描他人网络可能违法,请谨慎使用。


五、本章小结

5.1 核心要点

✅ 掌握SSH远程连接 ✅ 学会文件传输命令 ✅ 熟练使用下载工具 ✅ 掌握网络监控工具 ✅ 了解网络安全配置

5.2 验证清单

完成本章学习后,请确认您能够:

  • 使用SSH连接远程服务器
  • 配置SSH密钥认证
  • 使用SCP和Rsync传输文件
  • 使用Wget和Curl下载文件
  • 使用iftop和nethogs监控网络

东巴文(db-w.cn) - 让Linux学习更简单