curl
curl是一款非常强大的网络工具,用于从命令行下载或上传数据。支持HTTP、HTTPS、FTP、SFTP、SCP、LDAP等多种协议,常用于API接口测试、文件下载、数据传输等场景。
基本语法
curl [选项] [URL...]
主要选项
基本选项
-X, --request
- 指定HTTP请求方法-H, --header
- 添加HTTP头部-d, --data
- 发送POST数据-F, --form
- 发送表单数据-o, --output
- 保存输出到文件-O, --remote-name
- 使用远程文件名保存-L, --location
- 跟随重定向-v, --verbose
- 显示详细信息-s, --silent
- 静默模式-f, --fail
- 在HTTP错误时失败退出
认证和安全
-u, --user
- 用户认证-k, --insecure
- 忽略SSL证书错误--cert
- 客户端证书--key
- 私钥文件--cacert
- CA证书文件
代理和网络
--proxy
- 使用代理服务器--connect-timeout
- 连接超时时间--max-time
- 最大传输时间--retry
- 重试次数--limit-rate
- 限制传输速率
基本使用示例
GET请求
# 基本GET请求
curl http://example.com
# 保存响应到文件
curl -o response.html http://example.com
# 使用远程文件名保存
curl -O http://example.com/file.zip
# 跟随重定向
curl -L http://example.com
# 只显示HTTP头部
curl -I http://example.com
# 显示详细信息
curl -v http://example.com
POST请求
# 发送POST数据
curl -X POST -d 'username=test&password=123' http://example.com/login
# 发送JSON数据
curl -X POST \
-H "Content-Type: application/json" \
-d '{"username":"test","password":"123"}' \
http://example.com/api/login
# 从文件读取数据
curl -X POST -d @data.json http://example.com/api/users
# 发送表单数据
curl -X POST -F 'username=test' -F 'password=123' http://example.com/login
文件上传
# 上传文件
curl -F 'file=@/path/to/file.txt' http://example.com/upload
# 多文件上传
curl -F 'file1=@file1.txt' -F 'file2=@file2.txt' http://example.com/upload
# 指定文件类型
curl -F 'file=@image.jpg;type=image/jpeg' http://example.com/upload
# 指定文件名
curl -F 'file=@data.txt;filename=upload.txt' http://example.com/upload
HTTP方法
常用HTTP方法
# GET请求(默认)
curl http://example.com/api/users
# POST请求
curl -X POST -d 'data=value' http://example.com/api/users
# PUT请求
curl -X PUT -d 'data=updated' http://example.com/api/users/1
# DELETE请求
curl -X DELETE http://example.com/api/users/1
# PATCH请求
curl -X PATCH -d 'field=new_value' http://example.com/api/users/1
# HEAD请求
curl -X HEAD http://example.com/api/users
# OPTIONS请求
curl -X OPTIONS http://example.com/api/users
HTTP头部管理
常用头部
# 设置Content-Type
curl -H "Content-Type: application/json" http://example.com
# 设置Authorization
curl -H "Authorization: Bearer token123" http://example.com
# 设置User-Agent
curl -H "User-Agent: MyApp/1.0" http://example.com
# 设置多个头部
curl -H "Content-Type: application/json" \
-H "Authorization: Bearer token123" \
-H "Accept: application/json" \
http://example.com
# 删除默认头部
curl -H "User-Agent:" http://example.com
Cookie管理
# 发送Cookie
curl -b 'session=abc123; user=john' http://example.com
# 从文件读取Cookie
curl -b cookies.txt http://example.com
# 保存Cookie到文件
curl -c cookies.txt http://example.com
# 同时读取和保存Cookie
curl -b cookies.txt -c cookies.txt http://example.com
# 发送Cookie jar
curl -j -b cookies.txt -c cookies.txt http://example.com
认证方式
基本认证
# HTTP基本认证
curl -u username:password http://example.com
# 只输入用户名,交互式输入密码
curl -u username http://example.com
# 从.netrc文件读取认证信息
curl -n http://example.com
Bearer Token认证
# JWT Token认证
curl -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIs..." http://example.com/api
# API Key认证
curl -H "X-API-Key: your-api-key" http://example.com/api
OAuth认证
# OAuth 2.0 Bearer Token
curl -H "Authorization: Bearer oauth_token" http://example.com/api
SSL/TLS处理
SSL选项
# 忽略SSL证书错误
curl -k https://example.com
# 指定CA证书
curl --cacert ca-bundle.crt https://example.com
# 使用客户端证书
curl --cert client.pem --key client.key https://example.com
# 指定SSL版本
curl --tlsv1.2 https://example.com
# 显示SSL信息
curl -v --trace-ascii - https://example.com
代理和网络设置
代理设置
# HTTP代理
curl --proxy http://proxy.example.com:8080 http://example.com
# SOCKS代理
curl --socks5 proxy.example.com:1080 http://example.com
# 代理认证
curl --proxy http://user:pass@proxy.example.com:8080 http://example.com
# 忽略代理
curl --noproxy localhost,127.0.0.1 http://example.com
超时和重试
# 连接超时
curl --connect-timeout 10 http://example.com
# 总超时时间
curl --max-time 30 http://example.com
# 重试次数
curl --retry 3 http://example.com
# 重试延迟
curl --retry 3 --retry-delay 2 http://example.com
# 限制传输速率
curl --limit-rate 100k http://example.com/largefile.zip
实用应用场景
API测试
# RESTful API测试
# 获取用户列表
curl -H "Accept: application/json" http://api.example.com/users
# 创建用户
curl -X POST \
-H "Content-Type: application/json" \
-d '{"name":"John","email":"john@example.com"}' \
http://api.example.com/users
# 更新用户
curl -X PUT \
-H "Content-Type: application/json" \
-d '{"name":"John Smith","email":"johnsmith@example.com"}' \
http://api.example.com/users/1
# 删除用户
curl -X DELETE http://api.example.com/users/1
文件下载
# 下载文件并显示进度
curl -L -o file.zip http://example.com/file.zip
# 断点续传
curl -C - -o file.zip http://example.com/file.zip
# 下载多个文件
curl -O http://example.com/file1.zip -O http://example.com/file2.zip
# 并行下载
curl -O http://example.com/file1.zip & \
curl -O http://example.com/file2.zip & \
wait
网站检测
# 检查网站响应时间
curl -o /dev/null -s -w "总时间: %{time_total}s\n" http://example.com
# 检查HTTP状态码
curl -o /dev/null -s -w "%{http_code}\n" http://example.com
# 检查响应头
curl -I http://example.com
# 检查重定向
curl -L -I http://example.com
数据提交
# 提交表单
curl -X POST \
-F 'name=John' \
-F 'email=john@example.com' \
-F 'file=@resume.pdf' \
http://example.com/submit
# 提交XML数据
curl -X POST \
-H "Content-Type: application/xml" \
-d '<?xml version="1.0"?><user><name>John</name></user>' \
http://example.com/api/users
高级技巧
输出格式化
# 格式化输出信息
curl -w "状态码: %{http_code}\n响应时间: %{time_total}s\n大小: %{size_download}字节\n" \
-o /dev/null -s http://example.com
# 自定义输出格式
curl -w @curl-format.txt -o /dev/null -s http://example.com
# curl-format.txt内容示例:
# time_namelookup: %{time_namelookup}\n
# time_connect: %{time_connect}\n
# time_appconnect: %{time_appconnect}\n
# time_pretransfer: %{time_pretransfer}\n
# time_redirect: %{time_redirect}\n
#time_starttransfer: %{time_starttransfer}\n
# ----------\n
# time_total: %{time_total}\n
脚本集成
# 条件执行
if curl -f -s http://example.com/health > /dev/null; then
echo "服务正常"
else
echo "服务异常"
fi
# 获取HTTP状态码
STATUS=$(curl -o /dev/null -s -w "%{http_code}" http://example.com)
if [ $STATUS -eq 200 ]; then
echo "请求成功"
fi
# 循环检查服务
while true; do
if curl -f -s http://example.com/health > /dev/null; then
echo "$(date): 服务正常"
else
echo "$(date): 服务异常"
# 可以在这里添加告警逻辑
fi
sleep 60
done
实用脚本示例
API监控脚本
#!/bin/bash
# api_monitor.sh
API_URL="http://api.example.com/health"
LOG_FILE="/var/log/api_monitor.log"
check_api() {
local response_time=$(curl -o /dev/null -s -w "%{time_total}" $API_URL)
local http_code=$(curl -o /dev/null -s -w "%{http_code}" $API_URL)
local timestamp=$(date '+%Y-%m-%d %H:%M:%S')
if [ $http_code -eq 200 ]; then
echo "[$timestamp] API正常 - 响应时间: ${response_time}s" >> $LOG_FILE
else
echo "[$timestamp] API异常 - HTTP状态码: $http_code" >> $LOG_FILE
# 发送告警
send_alert "API异常: HTTP $http_code"
fi
}
send_alert() {
local message="$1"
# 可以集成邮件、短信或即时通讯工具
curl -X POST \
-H "Content-Type: application/json" \
-d "{\"text\":\"$message\"}" \
https://hooks.slack.com/services/YOUR/SLACK/WEBHOOK
}
# 每30秒检查一次
while true; do
check_api
sleep 30
done
批量API测试脚本
#!/bin/bash
# api_test.sh
BASE_URL="http://api.example.com"
AUTH_TOKEN="your-auth-token"
# 测试函数
test_endpoint() {
local method="$1"
local endpoint="$2"
local data="$3"
local expected_code="$4"
echo "测试: $method $endpoint"
if [ -n "$data" ]; then
response=$(curl -X $method \
-H "Authorization: Bearer $AUTH_TOKEN" \
-H "Content-Type: application/json" \
-d "$data" \
-w "%{http_code}" \
-s "$BASE_URL$endpoint")
else
response=$(curl -X $method \
-H "Authorization: Bearer $AUTH_TOKEN" \
-w "%{http_code}" \
-s "$BASE_URL$endpoint")
fi
# 提取状态码(最后3位)
http_code="${response: -3}"
if [ "$http_code" -eq "$expected_code" ]; then
echo "✅ 通过 - 状态码: $http_code"
else
echo "❌ 失败 - 期望: $expected_code, 实际: $http_code"
fi
echo "---"
}
# 运行测试
echo "开始API测试..."
test_endpoint "GET" "/users" "" 200
test_endpoint "POST" "/users" '{"name":"Test User","email":"test@example.com"}' 201
test_endpoint "GET" "/users/1" "" 200
test_endpoint "PUT" "/users/1" '{"name":"Updated User"}' 200
test_endpoint "DELETE" "/users/1" "" 204
echo "测试完成"
文件批量下载脚本
#!/bin/bash
# batch_download.sh
DOWNLOAD_DIR="./downloads"
URL_LIST="urls.txt"
# 创建下载目录
mkdir -p "$DOWNLOAD_DIR"
# 并行下载函数
download_file() {
local url="$1"
local filename=$(basename "$url")
echo "下载: $filename"
if curl -L -f -o "$DOWNLOAD_DIR/$filename" "$url"; then
echo "✅ 完成: $filename"
else
echo "❌ 失败: $filename"
fi
}
# 读取URL列表并并行下载
while IFS= read -r url; do
download_file "$url" &
# 限制并发数为5
(($(jobs -r | wc -l) >= 5)) && wait
done < "$URL_LIST"
# 等待所有下载完成
wait
echo "所有下载完成"
调试和故障排查
调试选项
# 显示详细信息
curl -v http://example.com
# 显示传输详情
curl --trace trace.txt http://example.com
# 显示ASCII格式的传输详情
curl --trace-ascii trace.txt http://example.com
# 只显示时间信息
curl -w "@curl-time.txt" -o /dev/null -s http://example.com
常见问题解决
# SSL证书问题
curl -k https://example.com # 忽略证书错误
# 编码问题
curl --compressed http://example.com # 启用压缩
# 重定向问题
curl -L http://example.com # 跟随重定向
# 超时问题
curl --connect-timeout 30 --max-time 60 http://example.com
配置文件
.curlrc配置文件
# ~/.curlrc
user-agent = "MyApp/1.0"
referer = ";auto"
connect-timeout = 60
max-time = 120
show-error
fail
location
相关工具
wget
- 另一个文件下载工具httpie
- 现代化的HTTP客户端postman
- 图形化API测试工具jq
- JSON处理工具(常与curl配合使用)
curl是Linux环境下最强大和灵活的网络工具之一,无论是运维、开发还是测试,都是不可或缺的工具。掌握其各种用法可以大大提高工作效率。