【Linux知识】curl命令行从入门到进阶实战
Linux curl 命令行从基础到高级实战指南
一、curl 核心基础
1. curl 基本概念
cURL(Client URL)是一个强大的命令行工具,支持 29 种协议,主要用于数据传输:
- HTTP/HTTPS
- FTP/FTPS
- SCP/SFTP
- SMTP/POP3
- 更多(完整列表见
curl --version
)
graph TDA[curl] --> B[数据传输]A --> C[API测试]A --> D[文件操作]B --> E[HTTP请求]B --> F[FTP上传/下载]C --> G[REST API交互]C --> H[WebSocket测试]D --> I[断点续传]D --> J[批量下载]
2. 核心安装与验证
# 安装(Debian/Ubuntu)
sudo apt install curl# 安装(RHEL/CentOS)
sudo yum install curl# 验证版本
curl --version
# 显示支持的协议列表
curl --version | grep Protocols
二、HTTP 请求实战
1. 基础请求方法
# GET 请求 (默认)
curl https://api.example.com/data# POST 请求
curl -X POST https://api.example.com/create# DELETE 请求
curl -X DELETE https://api.example.com/item/123# 带请求体的 POST
curl -d '{"name":"John"}' -H "Content-Type: application/json" -X POST https://api.example.com/users
2. 头部操作与 Cookie
# 添加自定义头部
curl -H "Authorization: Bearer token123" -H "X-Request-ID: 42" https://api.example.com# 保存 Cookie
curl -c cookies.txt https://login.example.com# 使用 Cookie
curl -b cookies.txt https://dashboard.example.com
3. 响应处理
# 只显示响应头
curl -I https://www.example.com# 显示完整请求信息
curl -v https://api.example.com# 保存响应到文件
curl -o output.json https://api.example.com/data# 保持原始文件名
curl -O https://example.com/files/document.pdf
三、高级 HTTP 技巧
1. 多部分表单提交
# 文件上传
curl -F "file=@photo.jpg" -F "comment=Profile picture" https://upload.example.com# 自定义文件字段名
curl -F "avatar=@user.jpg;filename=custom_name.jpg" https://api.example.com/profile
2. 认证处理
# 基础认证
curl -u username:password https://api.example.com# OAuth 2.0 Bearer Token
curl -H "Authorization: Bearer eyJhbG..." https://api.example.com
3. 协议与版本控制
# 强制 HTTP/1.1
curl --http1.1 https://legacy.example.com# 启用 HTTP/2
curl --http2 https://modern.example.com# 使用 HTTP/3 (需要支持)
curl --http3 https://experimental.example.com
四、文件传输实战
1. FTP 操作
# FTP 下载
curl -u ftpuser:password ftp://ftp.example.com/public/file.zip -o local.zip# FTP 上传
curl -T backup.tar.gz -u ftpuser:password ftp://ftp.example.com/backups/# 列出 FTP 目录内容
curl ftp://ftp.example.com/
2. 高级下载技术
# 断点续传
curl -C - -O http://mirror.example.com/large.iso# 带宽限制(500KB/s)
curl --limit-rate 500K -O http://mirror.example.com/large.iso# 并行下载(使用多个连接)
curl --parallel --parallel-immediate --parallel-max 4 -O http://mirror.example.com/bigfile.part[1-4]
3. 恢复中断的传输
# 下载完成后验证完整性
curl -O https://example.com/data.tar.gz && sha256sum -c data.tar.gz.sha256
五、网络安全与诊断
1. SSL/TLS 处理
# 忽略证书验证 (仅限测试)
curl -k https://self-signed.example.com# 使用自定义 CA
curl --cacert /path/to/ca-cert.pem https://internal.example.com# 输出证书信息
curl --cert-status -v https://secure.example.com# 使用客户端证书
curl --cert client.crt --key client.key https://client-auth.example.com
2. 连接诊断
# 追踪请求各阶段耗时
curl -w "DNS: %{time_namelookup}\n连接建立: %{time_connect}\nSSL握手: %{time_appconnect}\n传输开始: %{time_pretransfer}\n首字节响应: %{time_starttransfer}\n总时间: %{time_total}\n" -o /dev/null -s https://example.com# 只显示状态码
curl -s -o /dev/null -w "%{http_code}" https://example.com# 测试连接超时 (秒)
curl --connect-timeout 10 --max-time 30 https://slow.example.com
3. 错误处理
# 错误自动重试
curl --retry 5 --retry-delay 10 --retry-max-time 60 https://unstable.example.com# 忽略非 2xx 状态码 (-f)
curl -f https://api.example.com || echo "请求失败,状态码: $?"
六、API 集成实战
1. REST API 自动化
#!/bin/bash
API_URL="https://api.example.com/users"
TOKEN="Bearer $(cat ~/.api-token)"# 创建用户
create_user() {curl -s -X POST -H "Authorization: $TOKEN" -H "Content-Type: application/json" \-d '{"name":"'$1'", "email":"'$2'"}' $API_URL | jq
}# 获取用户信息
get_user() {curl -s -H "Authorization: $TOKEN" "$API_URL/$1" | jq
}# 示例使用
user_id=$(create_user "Alice" "alice@example.com" | jq -r '.id')
get_user $user_id
2. GraphQL 查询
curl -X POST -H "Content-Type: application/json" -d '{"query": "query { user(id: \"123\") { name email orders { id amount } } }"
}' https://graphql.example.com | jq
3. WebSocket 连接
curl --include --no-buffer \-H "Connection: Upgrade" \-H "Upgrade: websocket" \-H "Sec-WebSocket-Key: q4xkcO3uOO1QDwlhqw==" \-H "Sec-WebSocket-Version: 13" \https://ws.example.com/chat
七、高级应用技巧
1. 多任务处理
# 并行下载多个文件
cat files.txt | xargs -n 1 -P 4 curl -O# 顺序处理
curl -s https://api.example.com/jobs \| jq -r '.jobs[].download_url' \| while read url; do curl -O "$url"; done
2. 请求性能优化
# HTTP/2 服务器推送
curl --http2-prior-knowledge https://h2.example.com# 压缩传输
curl --compressed https://compress.example.com# 连接持久化
curl --keepalive-time 30 -H "Connection: keep-alive" https://service.example.com/resource1
curl --keepalive-time 30 -H "Connection: keep-alive" https://service.example.com/resource2
3. 网络环境测试
# 模拟慢速连接 (1KB/s)
curl --limit-rate 1K -O http://speedtest.example.com/data.bin# 模拟弱网环境
curl --speed-limit 100 --speed-time 10 https://cdn.example.com
八、配置与工作流优化
1. 持久化配置
# ~/.curlrc 示例
user-agent = "MyApp/1.0"
connect-timeout = 10
max-time = 30
retry = 3
retry-delay = 5
compressed = true
2. 常用别名
# ~/.bashrc 或 ~/.zshrc
alias curltime='curl -w "\
响应时间: %{time_total}秒\n\
DNS查询: %{time_namelookup}\n\
TCP连接: %{time_connect}\n\
SSL握手: %{time_appconnect}\n\
首字节等待: %{time_starttransfer}\n" -o /dev/null -s'alias curldb='curl -s -H "Content-Type: application/json" -H "Authorization: Bearer $(cat ~/.db-token)"'
3. 请求模板文件
# request.template
url = "https://api.example.com/graphql"
header = "Content-Type: application/json"
data = @graphql.query# 执行
curl -K request.template
九、安全最佳实践
graph LRA[安全凭证] --> B[环境变量]C[连接] --> D[强制HTTPS]E[证书] --> F[严格验证]G[敏感数据] --> H[加密处理]
1. 安全处理示例
# 安全凭证使用 (环境变量)
export API_TOKEN="secret123"
curl -H "Authorization: Bearer $API_TOKEN" https://api.example.com# 避免命令历史记录凭证
curl -H "Authorization: Bearer $(< ~/.api-token)" https://api.example.com# 敏感请求日志清理
curl ... | tee /dev/stderr | grep -v 'password'
十、真实案例解决方案
案例 1:监控网站健康
#!/bin/bash
URLS=("https://example.com" "https://api.example.com/health" "https://status.example.com")
for url in "${URLS[@]}"; dostatus=$(curl -s -o /dev/null -w "%{http_code}" $url)[ "$status" -ne 200 ] && echo "服务中断: $url (状态码: $status)"
done
案例 2:下载 GitHub 仓库
# 下载最新 release
curl -s https://api.github.com/repos/user/repo/releases/latest \| grep "browser_download_url.*linux" \| cut -d: -f2,3 \| tr -d \" \| wget -qi -
案例 3:SSL 证书到期监控
curl --insecure -v https://example.com 2>&1 \| grep "expire date" \| awk -F: '{print $2}' \| xargs -I {} date -d {} +%s
十一、总结参考表
任务 | 命令示例 |
---|---|
基本 GET | curl https://example.com |
POST JSON 数据 | curl -d '{"key":"value"}' -H "Content-Type: application/json" -X POST https://api.com |
文件上传 | curl -F "file=@data.zip" https://upload.com |
断点续传 | curl -C - -O https://example.com/largefile.iso |
状态码获取 | curl -s -o /dev/null -w "%{http_code}" https://api.com |
性能测试 | curl -w "\n响应时间: %{time_total}" -o /dev/null https://example.com |
gantttitle curl 学习进度dateFormat YYYY-MM-DDsection 基础技能安装配置 :done, des1, 2023-08-01, 1dHTTP请求 :active, des2, 2023-08-02, 2dsection 中级技能文件传输 : des3, after des2, 3dAPI集成 : des4, after des3, 2dsection 高级技能网络安全 : des5, after des4, 3d性能优化 : des6, after des5, 2d
通过掌握这些从基础到高级的 curl 技术,您将能够:
- 自动化处理各种网络通信任务
- 高效诊断和解决复杂的网络问题
- 构建健壮的API测试和集成工作流
- 提升开发运维效率50%以上
专业提示:结合
jq
处理 JSON 数据可以极大增强工作效率:curl -s https://api.example.com/data | jq '.[] | select(.value > 100)'