curl の cookie オプションまとめ

いつもなんだっけ?となって検索しているので、ちゃんと man ページを読んだ。

cookie を送信するにはこの2つのオプションを使用できる。
-b, --cookie <data|filename>
-H, --header <header/@file>

レスポンスの cookie を保存する場合はこちらのオプションを使う。今回はスキップ。
-c, --cookie-jar <filename>

オプションの使い方をひとつずつ見ていこう。

1. -b <data>

curl "https://example.com" -b "cookie_name=cookie_value"

2. -b <filename>

curl "https://example.com" -b /path/to/cookie.txt

ファイルフォーマットは plain HTTP headers (Set-Cookie style)Netscape/Mozilla cookie file format に対応しているとのこと。
それぞれ下記のように記述する。

# plain HTTP headers (Set-Cookie style)
cat /path/to/cookie.txt

Set-Cookie: cookie_name=cookie_value; Domain=example.com
# Netscape/Mozilla cookie file format
cat /path/to/cookie.txt

.example.com    TRUE    /    FALSE    0    cookie_name    cookie_value

Netscape/Mozilla cookie file format の詳細についてはこちらが参考になる。
なお、区切り文字はスペースではなく、タブなので注意。

https://curl.se/docs/http-cookies.html

Fields in the file
Field number, what type and example data and the meaning of it:

string example.com - the domain name
boolean FALSE - include subdomains
string /foobar/ - path
boolean TRUE - send/receive over HTTPS only
number 1462299217 - expires at - seconds since Jan 1st 1970, or 0
string person - name of the cookie
string daniel - value of the cookie

3. -H <header>

curl "https://example.com" -H "Cookie: cookie_name=cookie_value"

4. -H <@file>

curl "https://example.com" -H @/path/to/header.txt
cat /path/to/header.txt

Cookie: cookie_name=cookie_value

以上。