curl을 사용하여 Linux 명령 줄에서 파일을 다운로드하는 방법

Linux curl명령은 파일을 다운로드하는 것보다 훨씬 더 많은 일을 할 수 있습니다. 무엇 curl을 할 수 있는지 , wget.

curl vs. wget : 차이점은 무엇입니까?

사람들은 종종 wgetcurl명령 의 상대적인 강점을 식별하는 데 어려움을 겪습니다 . 명령은 기능적으로 일부 중복됩니다. 그들은 각각 원격 위치에서 파일을 검색 할 수 있지만 이것이 유사성이 끝나는 곳입니다.

wget콘텐츠와 파일을 다운로드하기위한 환상적인 도구입니다. 파일, 웹 페이지 및 디렉토리를 다운로드 할 수 있습니다. 여기에는 웹 페이지의 링크를 탐색하고 전체 웹 사이트에서 콘텐츠를 재귀 적으로 다운로드하는 지능형 루틴이 포함되어 있습니다. 명령 줄 다운로드 관리자로서 타의 추종을 불허합니다.

curl완전히 다른 요구를 충족시킵니다. 예, 파일을 검색 할 수 있지만 검색 할 콘텐츠를 찾는 웹 사이트를 재귀 적으로 탐색 할 수는 없습니다. 무엇 curl실제로하는 일은 그 시스템에 요청을하고, 검색하고 자신의 응답을 표시하여 원격 시스템을 상호 작용할 수 있습니다. 이러한 응답은 웹 페이지 콘텐츠 및 파일 일 수 있지만 curl 요청에서 요청한 "질문"의 결과로 웹 서비스 또는 API를 통해 제공된 데이터를 포함 할 수도 있습니다.

그리고 curl웹 사이트에만 국한되지 않습니다. curlHTTP, HTTPS, SCP, SFTP 및 FTP를 포함한 20 개 이상의 프로토콜을 지원합니다. 그리고 Linux 파이프의 뛰어난 처리로 인해 curl다른 명령 및 스크립트와 더 쉽게 통합 될 수 있습니다.

의 작성자는 과 (와) curl사이의 차이점을 설명하는 웹 페이지를 보유 curl하고 wget있습니다.

컬 설치

이 기사를 조사하는 데 사용 된 컴퓨터 중 Fedora 31과 Manjaro 18.1.0이 curl 이미 설치되어 있습니다. curlUbuntu 18.04 LTS에 설치해야합니다. Ubuntu에서 다음 명령을 실행하여 설치합니다.

sudo apt-get install curl

컬 버전

--version옵션은 curl해당 버전 을  보고합니다. 또한 지원하는 모든 프로토콜을 나열합니다.

컬 버전

웹 페이지 검색

curl웹 페이지를 가리키면 검색됩니다.

컬 //www.bbc.com

그러나 기본 동작은 소스 코드로 터미널 창에 덤프하는 것입니다.

주의 : curl무언가를 파일로 저장하고 싶다고 말하지 않으면 항상 터미널 창에 덤프합니다. 검색중인 파일이 이진 파일 인 경우 결과를 예측할 수 없습니다. 쉘은 2 진 파일의 일부 바이트 값을 제어 문자 또는 이스케이프 시퀀스로 해석하려고 시도 할 수 있습니다.

파일에 데이터 저장

curl에 출력을 파일로 리디렉션하도록 지시합시다.

컬 //www.bbc.com> bbc.html

이번에는 검색된 정보가 보이지 않고 파일로 바로 전송됩니다. 표시 할 터미널 창 출력이 없기 때문에 curl일련의 진행 정보를 출력합니다.

진행 정보가 웹 페이지 소스 코드 전체에 흩어져있어 curl자동으로 억제 되었기 때문에 이전 예제에서는이를 수행하지 않았습니다 .

이 예에서는  curl출력이 파일로 리디렉션되고 진행률 정보를 생성하는 것이 안전함을 감지합니다.

제공되는 정보는 다음과 같습니다.

  • % Total : 검색 할 총 금액입니다.
  • 수신률 : 지금까지 검색된 데이터의 백분율 및 실제 값입니다.
  • % Xferd : 데이터가 업로드되는 경우 전송 된 비율 및 실제.
  • 평균 속도 DLOAD : 평균 다운로드 속도.
  • 평균 속도 업로드 : 평균 업로드 속도.
  • 총 시간 : 예상 총 전송 기간입니다.
  • 보낸 시간 : 지금까지 전송에 대한 경과 시간.
  • 남은 시간 : 전송이 완료 될 때까지 남은 예상 시간
  • 현재 속도 :이 전송의 현재 전송 속도입니다.

출력 curl 을에서 파일로 리디렉션했기 때문에 이제 "bbc.html"이라는 파일이 생겼습니다.

해당 파일을 두 번 클릭하면 기본 브라우저가 열리고 검색된 웹 페이지가 표시됩니다.

브라우저 주소 표시 줄의 주소는 원격 웹 사이트가 아니라이 컴퓨터의 로컬 파일입니다.

파일을 만들기 위해 출력을 리디렉션 할 필요가 없습니다 . 우리는 사용하여 파일을 만들 수 있습니다 -o(출력) 옵션을, 그리고 말하는 curl파일을 만들 수 있습니다. 여기에서 -o옵션을 사용하고 "bbc.html"을 만들 파일 이름을 제공합니다.

curl -o bbc.html //www.bbc.com

진행률 표시 줄을 사용하여 다운로드 모니터링

텍스트 기반 다운로드 정보를 간단한 진행률 표시 줄로 바꾸려면 -#(진행률 표시 줄) 옵션을 사용하십시오 .

curl -x -o bbc.html //www.bbc.com

중단 된 다운로드 다시 시작

종료되거나 중단 된 다운로드를 다시 시작하는 것은 쉽습니다. 크기가 큰 파일 다운로드를 시작하겠습니다. Ubuntu 18.04의 최신 장기 지원 빌드를 사용합니다. 이 --output옵션을 사용하여 저장할 파일의 이름을 "ubuntu180403.iso"로 지정합니다.

curl --output ubuntu18043.iso //releases.ubuntu.com/18.04.3/ubuntu-18.04.3-desktop-amd64.iso

다운로드가 시작되고 완료 될 때까지 작동합니다.

로 다운로드를 강제로 중단하면 Ctrl+C명령 프롬프트로 돌아가고 다운로드가 중단됩니다.

To restart the download, use the -C (continue at) option. This causes curl to restart the download at a specified point or offset within the target file. If you use a hyphen - as the offset, curl will look at the already downloaded portion of the file and determine the correct offset to use for itself.

curl -C - --output ubuntu18043.iso //releases.ubuntu.com/18.04.3/ubuntu-18.04.3-desktop-amd64.iso

The download is restarted. curl reports the offset at which it is restarting.

Retrieving HTTP headers

With the -I (head) option, you can retrieve the HTTP headers only. This is the same as sending the HTTP HEAD command to a web server.

curl -I www.twitter.com

This command retrieves information only; it does not download any web pages or files.

Downloading Multiple URLs

Using xargs we can download multiple URLs at once. Perhaps we want to download a series of web pages that make up a single article or tutorial.

Copy these URLs to an editor and save it to a file called “urls-to-download.txt.” We can use xargs to treat the content of each line of the text file as a parameter which it will feed to curl, in turn.

//tutorials.ubuntu.com/tutorial/tutorial-create-a-usb-stick-on-ubuntu#0 //tutorials.ubuntu.com/tutorial/tutorial-create-a-usb-stick-on-ubuntu#1 //tutorials.ubuntu.com/tutorial/tutorial-create-a-usb-stick-on-ubuntu#2 //tutorials.ubuntu.com/tutorial/tutorial-create-a-usb-stick-on-ubuntu#3 //tutorials.ubuntu.com/tutorial/tutorial-create-a-usb-stick-on-ubuntu#4 //tutorials.ubuntu.com/tutorial/tutorial-create-a-usb-stick-on-ubuntu#5

This is the command we need to use to have xargs pass these URLs to curl one at a time:

xargs -n 1 curl -O < urls-to-download.txt

Note that this command uses the -O (remote file) output command, which uses an uppercase “O.” This option causes curl to save the retrieved  file with the same name that the file has on the remote server.

The -n 1 option tells xargs to treat each line of the text file as a single parameter.

When you run the command, you’ll see multiple downloads start and finish, one after the other.

Checking in the file browser shows the multiple files have been downloaded. Each one bears the name it had on the remote server.

RELATED:How to Use the xargs Command on Linux

Downloading Files From an FTP Server

Using curl with a File Transfer Protocol (FTP) server is easy, even if you have to authenticate with a username and password. To pass a username and password with curl use the -u (user) option, and type the username, a colon “:”, and the password. Don’t put a space before or after the colon.

This is a free-for-testing FTP server hosted by Rebex. The test FTP site has a pre-set username of “demo”, and the password is “password.” Don’t use this type of weak username and password on a production or “real” FTP server.

curl -u demo:password ftp://test.rebex.net

curl figures out that we’re pointing it at an FTP server, and returns a list of the files that are present on the server.

The only file on this server is a “readme.txt” file, of 403 bytes in length. Let’s retrieve it. Use the same command as a moment ago, with the filename appended to it:

curl -u demo:password ftp://test.rebex.net/readme.txt

The file is retrieved and curl displays its contents in the terminal window.

In almost all cases, it is going to be more convenient to have the retrieved file saved to disk for us, rather than displayed in the terminal window. Once more we can use the -O (remote file) output command to have the file saved to disk, with the same filename that it has on the remote server.

curl -O -u demo:password ftp://test.rebex.net/readme.txt

The file is retrieved and saved to disk. We can use ls to check the file details. It has the same name as the file on the FTP server, and it is the same length, 403 bytes.

ls -hl readme.txt

RELATED:How to Use the FTP Command on Linux

Sending Parameters to Remote Servers

Some remote servers will accept parameters in requests that are sent to them. The parameters might be used to format the returned data, for example, or they may be used to select the exact data that the user wishes to retrieve. It is often possible to interact with web application programming interfaces (APIs) using curl.

As a simple example, the ipify website has an API can be queried to ascertain your external IP address.

curl //api.ipify.org

By adding the format parameter to the command, with the value of “json” we can again request our external IP address, but this time the returned data will be encoded in the JSON format.

curl //api.ipify.org?format=json

Here’s another example that makes use of a Google API. It returns a JSON object describing a book. The parameter you must provide is the International Standard Book Number (ISBN) number of a book. You can find these on the back cover of most books, usually below a barcode. The parameter we’ll use here is “0131103628.”

curl //www.googleapis.com/books/v1/volumes?q=isbn:0131103628

The returned data is comprehensive:

Sometimes curl, Sometimes wget

If I wanted to download content from a website and have the tree-structure of the website searched recursively for that content, I’d use wget.

If I wanted to interact with a remote server or API, and possibly download some files or web pages, I’d use curl. Especially if the protocol was one of the many not supported by wget.