Cookie 管理是 cURL 在处理需要身份验证的 Web 应用时的关键功能。cURL 提供了多种方式来发送、接收和持久化 Cookie。
发送 Cookie
bash# 方式一:使用 -b 参数 curl -b "session_id=abc123" https://api.example.com/profile # 方式二:使用 -H 设置 Cookie 头 curl -H "Cookie: session_id=abc123" https://api.example.com/profile # 发送多个 Cookie curl -b "session_id=abc123; user_id=456; theme=dark" \ https://api.example.com/profile # 从文件读取 Cookie curl -b cookies.txt https://api.example.com/profile
接收和保存 Cookie
bash# 保存服务器返回的 Cookie 到文件 curl -c cookies.txt https://api.example.com/login # 同时发送和接收 Cookie curl -b cookies.txt -c cookies.txt \ -d "username=admin&password=123456" \ https://api.example.com/login # 显示详细 Cookie 信息 curl -v https://api.example.com/login 2>&1 | grep "Set-Cookie"
Cookie 文件格式
cURL 使用 Netscape 格式的 Cookie 文件:
shell# Netscape HTTP Cookie File # https://curl.haxx.se/docs/http-cookies.html # This file was generated automatically by curl .example.com TRUE / FALSE 0 session_id abc123 .example.com TRUE / FALSE 1735689600 user_id 456
字段说明:
- 域名(Domain)
- 是否包含子域名(TRUE/FALSE)
- 路径(Path)
- 是否安全连接(TRUE/FALSE)
- 过期时间(Unix 时间戳,0 表示会话 Cookie)
- Cookie 名称
- Cookie 值
完整登录流程示例
bash# 步骤 1:访问登录页面,获取初始 Cookie curl -c cookies.txt -b cookies.txt \ https://api.example.com/login # 步骤 2:提交登录表单,保存会话 Cookie curl -c cookies.txt -b cookies.txt \ -X POST \ -d "username=admin&password=123456" \ https://api.example.com/login # 步骤 3:使用会话 Cookie 访问受保护页面 curl -b cookies.txt https://api.example.com/dashboard # 步骤 4:登出(清除会话) curl -b cookies.txt https://api.example.com/logout
Cookie 相关参数
| 参数 | 作用 | 示例 |
|---|---|---|
-b 或 --cookie | 发送 Cookie | -b "name=value" 或 -b cookies.txt |
-c 或 --cookie-jar | 保存 Cookie | -c cookies.txt |
-j 或 --junk-session-cookies | 忽略会话 Cookie | 读取文件时跳过会话 Cookie |
高级用法
bash# 使用 Cookie Jar 进行会话管理 curl -b cookies.txt -c cookies.txt -L \ -X POST \ -H "Content-Type: application/json" \ -d '{"username":"admin","password":"123456"}' \ https://api.example.com/api/login # 查看 Cookie 文件内容 cat cookies.txt # 清除所有 Cookie(删除文件) rm cookies.txt # 仅保留持久化 Cookie(过滤会话 Cookie) curl -b cookies.txt -j -c persistent_cookies.txt \ https://api.example.com/data
注意事项
- 安全性:Cookie 文件包含敏感信息,注意权限设置(chmod 600)
- 过期时间:定期清理过期的 Cookie
- 跨域限制:Cookie 遵循同源策略,注意域名和路径匹配
- 会话 vs 持久:会话 Cookie 在浏览器关闭后失效,持久 Cookie 有过期时间