How to Save Cookies to File Using Wget on Ubuntu
This article demonstrates how to utilize the wget command-line tool on Ubuntu to download files while capturing HTTP cookies. It covers the specific flags needed to store cookie data in a local text file and how to reuse that data for authenticated requests. Follow these steps to manage session states effectively without a graphical browser.
Install Wget
Most Ubuntu installations include wget by default. If it is missing, open your terminal and install it using the following command:
sudo apt update
sudo apt install wgetSave Cookies During Download
To download a file and save the associated cookies to a text file
simultaneously, use the --save-cookies flag. This creates a
file containing the cookie data sent by the server during the
request.
wget --save-cookies cookies.txt https://example.com/file.zipIn this command, cookies.txt will be created in your
current directory. The file stores cookies in the Netscape format, which
is compatible with most command-line tools.
Load Cookies for Subsequent Requests
If you need to download additional files from the same session or
access protected content, use the --load-cookies flag. This
tells wget to read the previously saved cookies and send them with the
new request.
wget --load-cookies cookies.txt https://example.com/protected-file.zipHandling Authentication Sessions
For websites requiring a login, you typically need to perform a POST request to save the session cookies first, then use those cookies to download the file.
- Login and save cookies:
bash wget --save-cookies cookies.txt --post-data 'user=name&pass=word' https://example.com/login - Download using saved cookies:
bash wget --load-cookies cookies.txt https://example.com/secure-download.zip
Ensure you keep the cookies.txt file secure, as it may
contain sensitive session tokens. Delete the file when you no longer
need to maintain the session.