Linux curl with cookies

How to use cURL to send Cookies?

I think adding the -c option tells curl to use your cookie file as the output cookie jar, which might not be what you want.

the format of the -b cookie file is not just var=value , it should be the same as the format of the cookie jar written using -c . Go to a site that sends cookies with this option, and take a look at the resulting file.

The -b cookie_file should either be in Netscape/Mozilla format or plain HTTP headers. Here’s an example of plain http headers: Set-cookie: cookie_name=cookie_value; This is the bare minimum. Don’t forget the semicolon at the end.

10 Answers 10

curl -v --cookie "USER_TOKEN=Yes" http://127.0.0.1:5000/ 

I could see the value in backend using

As long as you never, ever have a boolean for a user token as a cookie, given that they can just authenticate themselves without logging in that way.

According to the man page, for option -b, —cookie , e.g. curl -b , if the argument is a string having the ‘=’ symbol, it’s passed as is, otherwise it’s treated as a filename to read cookie from.

For sending multiple cookies, I had to put a space after ; (I am using a mac) Eg: —cookie «key1=val1; key2=val2»

You can refer to https://curl.haxx.se/docs/http-cookies.html for a complete tutorial of how to work with cookies. You can use

curl -c /path/to/cookiefile http://yourhost/ 

to write to a cookie file and start engine and to use cookie you can use

curl -b /path/to/cookiefile http://yourhost/ 

to read cookies from and start the cookie engine, or if it isn’t a file it will pass on the given string.

IMO you did not enhance on the official doc which is clear as mud — beside the overloading of the -b flag what is the essential diff between -c & -b they both start the engine and point to a cookie file?

@nhed -c writes to the cookie file, -b reads from it. So when sending credentials for a login form you would specify -c to write the resulting cookie to a file, then you would use -b to read from and include the cookie in your next request.

Or do curl -b cookiefile -c cookiefile https://yourhost/ to read and write to the same cookie store like browsers do.

You are using a wrong format in your cookie file. As curl documentation states, it uses an old Netscape cookie file format, which is different from the format used by web browsers. If you need to create a curl cookie file manually, this post should help you. In your example the file should contain following line

127.0.0.1 FALSE / FALSE 0 USER_TOKEN in 

having 7 TAB-separated fields meaning domain, tailmatch, path, secure, expires, name, value.

This should be marked as the official answer, since this truly addresses the point as to why @daydreamer’s setup was failing.

Читайте также:  Kali linux установка времени

Since curl 7.55 headers from file are supported with @

echo ‘Cookie: USER_TOKEN=Yes’ > /tmp/cookie

If you have made that request in your application already, and see it logged in Google Dev Tools, you can use the copy cURL command from the context menu when right-clicking on the request in the network tab. Copy -> Copy as cURL. It will contain all headers, cookies, etc..

I’m using Debian, and I was unable to use tilde for the path. Originally I was using

curl -c "~/cookie" http://localhost:5000/login -d username=myname password=mypassword 
curl -c "/tmp/cookie" http://localhost:5000/login -d username=myname password=mypassword 

-c creates the cookie, -b uses the cookie

so then I’d use for instance:

curl -b "/tmp/cookie" http://localhost:5000/getData 

~ is not expanded to $HOME if it’s put within quotes, in which case it will be treated as a literal tilde. ;]

Another solution using json.

curl -c /tmp/cookie -X POST -d '' -H "Content-Type:application/json" localhost:5000/set curl -b "/tmp/cookie" -d '' -X GET -H "Content-Type:application/json" localhost:5000/get curl -b "/tmp/cookie" -d '' -X GET -H "Content-Type:application/json" localhost:5000/delete 
from flask import Flask, request, session, jsonify from flask_session import Session app = Flask(__name__) app.secret_key = '$#EWFGHJUI*&DEGBHYJU&Y%T#RYJHG%##RU&U' app.config["SESSION_PERMANENT"] = False app.config["SESSION_TYPE"] = "filesystem" Session(app) @app.route('/') def padrao(): return 'backend server-side.' @app.route('/set', methods=['POST']) def set(): resposta = jsonify() dados = request.get_json() try: if 'chave' not in dados: # não tem o atributo chave? resposta = jsonify() else: session[dados['chave']] = dados['valor'] except Exception as e: # em caso de erro. resposta = jsonify() resposta.headers.add("Access-Control-Allow-Origin", "*") return resposta @app.route('/get') def get(): try: dados = request.get_json() retorno = retorno.update() resposta = jsonify(retorno) except Exception as e: resposta = jsonify() resposta.headers.add("Access-Control-Allow-Origin", "*") return resposta @app.route('/delete') def delete(): try: dados = request.get_json() session.pop(dados['chave'], default=None) resposta = jsonify() except Exception as e: # em caso de erro. resposta = jsonify() resposta.headers.add("Access-Control-Allow-Origin", "*") return resposta app.run(debug=True) 

Источник

HTTP Cookies

Cookies are name=contents pairs that an HTTP server tells the client to hold and then the client sends back those to the server on subsequent requests to the same domains and paths for which the cookies were set.

Cookies are either «session cookies» which typically are forgotten when the session is over which is often translated to equal when browser quits, or the cookies are not session cookies they have expiration dates after which the client will throw them away.

Cookies are set to the client with the Set-Cookie: header and are sent to servers with the Cookie: header.

For a long time, the only spec explaining how to use cookies was the original Netscape spec from 1994.

In 2011, RFC 6265 was finally published and details how cookies work within HTTP. In 2016, an update which added support for prefixes was proposed, and in 2017, another update was drafted to deprecate modification of ‘secure’ cookies from non-secure origins. Both of these drafts have been incorporated into a proposal to replace RFC 6265. Cookie prefixes and secure cookie modification protection has been implemented by curl.

Читайте также:  Command delete files in linux command

curl considers http://localhost to be a secure context, meaning that it will allow and use cookies marked with the secure keyword even when done over plain HTTP for this host. curl does this to match how popular browsers work with secure cookies.

Cookies saved to disk

Netscape once created a file format for storing cookies on disk so that they would survive browser restarts. curl adopted that file format to allow sharing the cookies with browsers, only to see browsers move away from that format. Modern browsers no longer use it, while curl still does.

The Netscape cookie file format stores one cookie per physical line in the file with a bunch of associated meta data, each field separated with TAB. That file is called the cookie jar in curl terminology.

When libcurl saves a cookie jar, it creates a file header of its own in which there is a URL mention that will link to the web version of this document.

The cookie file format is text based and stores one cookie per line. Lines that start with # are treated as comments. An exception is lines that start with #HttpOnly_ , which is a prefix for cookies that have the HttpOnly attribute set.

Each line that specifies a single cookie consists of seven text fields separated with TAB characters. A valid line must end with a newline character.

Fields in the file

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

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

Cookies with curl the command line tool

curl has a full cookie «engine» built in. If you just activate it, you can have curl receive and send cookies exactly as mandated in the specs.

tell curl a file to read cookies from and start the cookie engine, or if it is not a file it will pass on the given string. -b name=var works and so does -b cookiefile .

when used in combination with -b, it will skip all «session cookies» on load so as to appear to start a new cookie session.

tell curl to start the cookie engine and write cookies to the given file after the request(s)

Cookies with libcurl

libcurl offers several ways to enable and interface the cookie engine. These options are the ones provided by the native API. libcurl bindings may offer access to them using other means.

Is used when you want to specify the exact contents of a cookie header to send to the server.

Читайте также:  What is my screen resolution linux

Tell libcurl to activate the cookie engine, and to read the initial set of cookies from the given file. Read-only.

Tell libcurl to activate the cookie engine, and when the easy handle is closed save all known cookies to the given cookie jar file. Write-only.

Provide detailed information about a single cookie to add to the internal storage of cookies. Pass in the cookie as an HTTP header with all the details set, or pass in a line from a Netscape cookie file. This option can also be used to flush the cookies etc.

Tell libcurl to ignore all cookies it is about to load that are session cookies.

Extract cookie information from the internal cookie storage as a linked list.

Cookies with JavaScript

These days a lot of the web is built up by JavaScript. The web browser loads complete programs that render the page you see. These JavaScript programs can also set and access cookies.

Since curl and libcurl are plain HTTP clients without any knowledge of or capability to handle JavaScript, such cookies will not be detected or used.

Often, if you want to mimic what a browser does on such websites, you can record web browser HTTP traffic when using such a site and then repeat the cookie operations using curl or libcurl.

Источник

Как использовать cURL для отправки кукиз

Отправить cookie в cURL можно опцией —cookie:

curl -v --cookie "USER_TOKEN=Yes" http://127.0.0.1:5000/

У опции —cookie есть короткий вариант -b. С этими опциями можно указать как файл, содержащий кукиз, так и строку с паролй ИМЯ=ЗНАЧЕНИЕ. Если аргументом является строка с символом ‘=‘, то он передаётся как есть. В противном случае строка трактуется как имя файла из которого нужно прочитать кукиз.

Сразу несколько кукиз можно передать разделив их точкой с запятой, например:

curl --cookie "key1=val1;key2=val2;…" URL

Если вы хотите сохранить кукиз, то для этого используется опция -c (длинное написание —cookie-jar). Следующий пример запишет полученные от хоста кукиз в файл cookiefile:

curl -c /путь/до/cookiefile http://yourhost/

А следующий пример прочитает кукиз из файла cookiefile и отправит их хосту:

curl -b /путь/до/cookiefile http://yourhost/

Смотрите также примеры в статье «Парсинг сайтов: азы, продвинутые техники, сложные случаи» раздел «cURL и аутентификация в веб-формах (передача данных методом GET и POST)».

Допустимо использовать опции для записи и чтения кукиз одновременно в один и тот же файл, как это делают веб-браузеры:

curl -b cookiefile -c cookiefile https://yourhost/

Если нужно написать файл кукиз вручную, то помните, что в документации curl сказано, что используется старый формат файлов кукиз Netscape, который отличается от формата, используемого веб-браузерами. Если вам нужно создать файл кукиз для curl вручную, то это сообщение должно помочь вам.

Файл должен быть записан примерно так:

127.0.0.1 FALSE / FALSE 0 USER_TOKEN in

то есть содержать 7 разделённых табом поолей: домен, tailmatch, путь, безопасность, истекают, имя, значение.

Источник

Оцените статью
Adblock
detector