Linux curl or wget

What is the difference between curl and wget? [closed]

Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.

Both of these curl and wget are use for downloading files, etc. What are the notable differences one might take in account in order chose one over the other?

Regarding the vote to close as opinion-based: how does asking about the difference between two tools encourage opinion-based answers?

@MichaelMartin-Smucker «Suppose I need to download a web page lets say www.google.com, should I look for wget or curl ?» what is that if not opinion-based?

@muru, It depends on what you mean by «download a web page». If you mean send an http request and receive back the results, curl is ideal. If you mean download a page, other pages it links to, and related assets, curl will not work, and wget is the only option. There are factual differences between them which make this not opinion based.

@muru I guess we just have different interpretations of the sentiment behind the question. In my interpretation, the sentiment is: «I’ve heard of these two tools which seem to do the same thing. What is the difference between them, and when should I choose one over the other? What about in this specific case?» . which seems like a reasonable question to me.

4 Answers 4

After you’ve defined «proper use», use wget .

Recursive! wget’s major strong side compared to curl is its ability to download recursively, or even just download everything that is referred to from a remote resource, be it a HTML page or a FTP directory listing.

curl

  • library. curl is powered by libcurl – a cross-platform library with a stable API that can be used by each and everyone. This difference is major since it creates a completely different attitude on how to do things internally. It is also slightly harder to make a library than a «mere» command line tool.
  • pipes. curl works more like the traditional Unix cat command, it sends more stuff to stdout , and reads more from stdin in a «everything is a pipe» manner. wget is more like cp , using the same analogue.
  • Single shot. curl is basically made to do single-shot transfers of data. It transfers just the URLs that the user specifies, and does not contain any recursive downloading logic nor any sort of HTML parser.
  • More protocols. curl supports FTP, FTPS, Gopher, HTTP, HTTPS, SCP, SFTP, TFTP, TELNET, DICT, LDAP, LDAPS, FILE, POP3, IMAP, SMB/CIFS, SMTP, RTMP and RTSP. Wget only supports HTTP, HTTPS and FTP.
  • More portable. curl builds and runs on lots of more platforms than wget . For example: OS/400, TPF and other more «exotic» platforms that aren’t straight-forward Unix clones.
  • More SSL libraries and SSL support. curl can be built with one out of eleven (11!) different SSL/TLS libraries, and it offers more control and wider support for protocol details. curl supports public key pinning.
  • HTTP auth. curl supports more HTTP authentication methods, especially over HTTP proxies: Basic, Digest, NTLM and Negotiate
  • SOCKS. curl supports several SOCKS protocol versions for proxy access
  • Bidirectional. curl offers upload and sending capabilities. wget only offers plain HTTP POST support.
  • HTTP multipart/form-data sending, which allows users to do HTTP «upload» and in general emulate browsers and do HTTP automation to a wider extent
  • curl supports gzip and inflate Content-Encoding and does automatic decompression
  • curl offers and performs decompression of Transfer-Encoded HTTP, wget doesn’t
  • curl supports HTTP/2 and it does dual-stack connects using Happy Eyeballs
  • Much more developer activity. While this can be debated, I consider three metrics here: mailing list activity, source code commit frequency and release frequency. Anyone following these two projects can see that the curl project has a lot higher pace in all these areas, and it has been so for 10+ years. Compare on openhub
Читайте также:  Linux find chmod all files

wget

  • wget is command line only. There’s no library.
  • Recursive! wget ‘s major strong side compared to curl is its ability to download recursively, or even just download everything that is referred to from a remote resource, be it a HTML page or a FTP directory listing.
  • Older. wget has traces back to 1995, while curl can be tracked back no earlier than the end of 1996.
  • GPL. wget is 100% GPL v3. curl is MIT licensed.
  • GNU. wget is part of the GNU project and all copyrights are assigned to FSF. The curl project is entirely stand-alone and independent with no organization parenting at all with almost all copyrights owned by Daniel.
  • wget requires no extra options to simply download a remote URL to a local file, while curl requires -o or -O .
  • wget supports the Public Suffix List for handling cookie domains, curl does not.
  • wget supports only GnuTLS or OpenSSL for SSL/TLS support
  • wget supports only Basic auth as the only auth type over HTTP proxy
  • wget has no SOCKS support
  • Its ability to recover from a prematurely broken transfer and continue downloading has no counterpart in curl.
  • wget can be typed in using only the left hand on a qwerty keyboard!

Источник

В чем разница между wget и curl?

Favorite

Добавить в избранное

Главное меню » Linux » В чем разница между wget и curl?

В чем разница между wget и curl?

Н ам часто нужно загружать файлы с удаленных серверов на наш локальный компьютер. На графическом рабочем столе мы можем использовать браузер с графическим интерфейсом и нажать кнопку загрузки. Однако на терминале нам нужно использовать инструменты, разработанные для терминала. При загрузке файлов с терминала часто появляются четыре инструмента: curl , axel , wget и aria2. Хотя axel и aria2 могут быть не очень хорошо известны, большинство пользователей терминалов знают curl и wget.

Читайте также:  Удалить лишние ядра astra linux

В этой статье мы рассмотрим curl и wget, с чего начать, и, что наиболее важно, различия между ними.

Что такое cURL?

cURL — это бесплатная утилита командной строки с открытым исходным кодом, которая позволяет пользователям передавать данные с одного удаленного компьютера на другой с минимальным вмешательством пользователя или без него. CURL широко используется в таких устройствах, как маршрутизаторы, принтеры, телефоны, планшеты, медиаплееры и т. д.

Он поддерживает загрузку и выгрузку с использованием таких протоколов, как HTTP/HTTPS, FTP, SFTP, SCP, IMAP, LDAP/LDAPS, SMB/SMBS, TELNET, POP3, GOPHER и многие, многие другие.

cURL также предоставляет прокси, возобновление передачи, аутентификацию пользователей, сертификаты SSL и многое другое.

Что такое wget?

GNU Wget, обычно называемый wget, — это бесплатная утилита командной строки для передачи файлов с использованием HTTP/HTTPS, FTP и FTPS. Он предоставляет такие функции, как рекурсивные загрузки, управление пропускной способностью, возобновление прерванных передач, фоновые загрузки, рекурсивные зеркальные файлы и каталоги и многое другое.

Как установить cURL и Wget?

cURL и wget — популярные инструменты, легко доступные в основных дистрибутивах Linux; если у вас не установлен какой-либо инструмент, используйте следующие команды для установки:

Debian/Ubuntu:

# установить cURL sudo apt-get install curl # установить wget sudo apt-get install wget

Arch/Manjaro:

# установить cURL sudo pacman -S curl # установить wget sudo pacman -S wget

REHL/CentOS/Fedora:

# установить cURL sudo yum install curl sudo dnf install curl # установить wget sudo yum install wget sudo dnf install wget

Как использовать cURL и Wget (примеры использования)?

Чтобы убедиться, что вы понимаете сходства и различия между cURL и wget, полезно взглянуть на несколько примеров:

Протоколы HTTP/HTTPS:

И cURL, и wget поддерживают протоколы HTTP и HTTPS. Следовательно, если мы загрузим такой веб-сайт, как andreyex.ru:

curl https://andreyex.ru -o andreyex.html curl https://andreyex.ru -o andreyex.html % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 100 256k 0 256k 0 0 166k 0 --:--:-- 0:00:01 --:--:-- 166k

По умолчанию cURL будет печатать содержимое веб-ресурса в терминале. Мы используем флаг -o, чтобы перенаправить вывод в файл.

К wget применимо следующее:

https://andreyex.ru --2021-07-23 16:05:09-- https://andreyex.ru/ Resolving andreyex.ru (andreyex.ru). 213.159.210.167, 172.17.0.1 Connecting to andreyex.ru (andreyex.ru)|213.159.210.167|:443. connected. HTTP request sent, awaiting response. 200 OK Length: unspecified [text/html] Saving to: 'index.html' index.html [ ] 135.22K --.-KB/s in 0.001s 2021-07-23 16:05:09 (161 MB/s) - 'index.html' saved [138463]

Wget, с другой стороны, сохраняет запрошенный ресурс в файл.

Приятно отметить, что оба инструмента загружают ресурс. Подробности ls двух файлов показывают оба размера файлов.

$ Ls -l index.html andreyex.html -rw-RW-r-- 1 andreyex andreyex 262396 июля 20 12:23 index.html -rw-RW-r-- 1 andreyex andreyex 262396 июля 23 12:43 andreyex.html

Протокол FTP:

И cURL, и wget поддерживают загрузку по протоколам FTP. Однако cURL поддерживает загрузку на ftp.

Читайте также:  Использовать дискретную видеокарту linux

Используйте команду ниже для загрузки файлов с FTP-сервера с помощью wget:

wget --user=debian --password=’debian’ ftp://192.168.0.112/backup.zst wget --user=debian --password='debian' ftp://192.168.0.112/backup.zst --2021-06-20 05:29:06-- ftp://192.168.0.112/backup.zst => ‘backup.zst’ Connecting to 192.168.0.112:21. connected. Logging in as debian . Logged in! ==> SYST . done. ==> PWD . done. ==> TYPE I . done. ==> CWD not needed. ==> SIZE backup.zst . done. ==> PASV . done. ==> RETR backup.zst . done. backup.zst [ ] 0 --.-KB/s in 0s 2021-06-20 05:29:06 (0.00 B/s) - ‘backup.zst’ saved [0] Using curl, add the -u flag as: curl -u debian:debian ‘ftp://192.168.0.112/backup.zst’ -o backup.zst curl -u debian:debian 'ftp://192.168.0.112/backup.zst' -o backup.zst % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0 To upload a file to ftp with curl, we use the -T option as: curl -u debian:debian -T “backup1.zst” ftp://192.168.0.112/ftp/

Убедитесь, что каталог существует и у пользователя есть права на запись в него.

Хотя cURL поддерживает большое количество протоколов, он не обеспечивает рекурсивную загрузку. С другой стороны, Wget поддерживает рекурсивные загрузки с использованием параметра –recursive, поскольку протоколы HTTP/HTTPS и FTP/FTPS предлагают такую ​​функциональность.

Сходства между wget и cURL

А теперь глазурь на торте:

  • Оба инструмента поддерживают стандартные протоколы, такие как HTTP, HTTPS, FTP, FTPS.
  • Оба инструмента загружают файлы из Интернета.
  • Оба инструмента поддерживают файлы cookie HTTP.
  • Оба инструмента поддерживают вывод в файл.
  • Как бесплатные, так и активно разрабатываемые инструменты.
  • Оба инструмента поддерживают переводы резюме.
  • Оба инструмента поддерживают HTTP POST.

Различия между wget и cURL

Вот некоторые различия между curl и wget:

  • Wget — это простая утилита для передачи, а curl предлагает гораздо больше.
  • Curl предоставляет библиотеку libcurl, которую можно расширить до приложений с графическим интерфейсом. С другой стороны, Wget — это простая утилита командной строки.
  • Wget поддерживает меньше протоколов по сравнению с cURL.
  • Рекурсивные загрузки не поддерживаются в curl.
  • Wget изначально доступен в системах Linux, а cURL легко доступен в системах Windows.
  • cURL поддерживает множественные параллельные передачи.
  • cURL выполняет декомпрессию HTTP с кодировкой передачи, а wget — нет.
  • cURL поддерживает двунаправленный HTTP, тогда как wget предлагает простой HTTP POST.
  • cURL поддерживает больше методов аутентификации HTTP по сравнению с wget.
  • Wget не поддерживает SOCKS.
  • Wget требует установленного гнулиба.
  • В отличие от curl, в wget по умолчанию включены такие функции, как файлы cookie, отметки времени и последующие перенаправления. cURL требует, чтобы каждый из них был указан явно.

Вывод

В этом руководстве основное внимание уделяется сходству и различию между cURL. Хотя может показаться, что cURL — лучший выбор, есть случаи, когда wget — лучший выбор.

Мой вам совет — выберите то, что вам подходит.

Если вы нашли ошибку, пожалуйста, выделите фрагмент текста и нажмите Ctrl+Enter.

Источник

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