Mac OS X,  Mac Security

Cookie Management With Curl

To tell curl that you can read and write cookies, first we’ll start the engine using an empty cookie jar, using the -b option, which always reads cookies into memory:

curl -b newcookiejar https://krypted.com

If your site can set cookies you can then read them with the -L option

curl -L -b newcookiejar https://krypted.com

The response should be similar to the following:

Reading cookies from file

Curl also supports reading cookies in from the Netscape cookie format, used by defining a cookies.txt file instead:

curl -L -b cookies.txt https://krypted.com

If the server updates the cookies in a response, curl would update that cookie in memory but unless you write something that looks for a new cookie, the next use will read the original cookie again.

To create that file, use the -c option (short for –cookie-jar) as follows:

curl -c cookie-jar.txt https://krypted.com

This will save save all types of cookies (including session cookies). To differentiate, curl supports junk, or session cookies using the –junk-session-cookies options, or -j for short. The following can read these expiring cookies:

curl -j -b cookie-jar.txt https://krypted.com

Use that to start a session and then that same -c to call them on your next use. This could be as simple as the following:

CURL=/usr/bin/curl
COOKIEJAR=cookie-jar.txt
SITE=https://krypted.com/
$CURL -j -b $COOKIEJAR $site

You can also add a username and password to the initial request and then store the cookie. This type of authentication and session management is used frequently, for example in the Munkireport API, as you can see here:

For converting, the -b detects if a file is a Netscape formatted cookie file, parses, then rewrites using the -c option at the end of a line:

curl -b cookie.txt -c cookie-jar.txt https://krypted.com