본문으로 바로가기

curl 설치 및 사용법

category 참고소스/Docker 2016. 4. 21. 08:46

개요

curl 은 command line 용 data transfer tool 이다. download/upload 모두 가능하며HTTP/HTTPS/FTP/LDAP/SCP/TELNET/SMTP/POP3 등 주요한 프로토콜을 지원하며 Linux/Unix 계열 및 Windows 등 주요한 OS 에서 구동되므로

여러 플랫폼과 OS에서 유용하게 사용할 수 있다. 또 libcurl 이라는 C 기반의 library 가 제공되므로 C/C++ 프로그램 개발시 위의 protocol 과 연계가 필요하다면 libcurl 을 사용하여 손쉽게 연계할 수 있다. 또 libcurl은 PHP, ruby, PERL 및 여러 언어에 바인딩되어 있으므로 사용하는 언어나 개발환경에 맞게 libcurl 을 사용할 수 있다.
 

설치

Linux나 Mac OS X 에는 기본 탑재되어 있다. Windows는 build 된 바이너리를 설치해도 되고 compiler 가 있다면 소스를 받아서 직접 빌드해도 된다.(curl windows 에서 빌드하기)

Windows 버전은 cygwin나 MinGW 로 빌드한거 보다는 VIsual Studio 로 빌드한 버전을 다운받는게 좋다. (Win32-Generic, Win64 - Generic 항목에서 받으면 된다.) 

CentOS/RHEL 계열에서 최신 버전 설치는 RHEL/CentOS 6 에서 curl 최신 버전 설치 문서를 참고하자.

 

사용법

curl [options...] <url> 형식으로 사용하면 된다.

option 처리는 GNU getopt 를 사용하므로 하이픈 하나를 붙이는 short 형식의 옵션과 하이픈 두개로 시작되는 long 형식의 options 이 있다. 

주요 options (http/https 관련 옵션만 정리)

short
long
설명
비고
-k--insecurehttps 사이트를 SSL certificate 검증없이 연결한다.wget 의 --no-check-certificate 과 비슷한 역할 수행
-l--headHTTP header 만 보여주고 content 는 표시하지 않는다 
-D--dump-header <file><file> 에 HTTP header 를 기록한다. 
-L--location

서버에서 HTTP 301 이나 HTTP 302 응답이 왔을 경우 redirection URL 로 따라간다.

--max-redirs 뒤에 숫자로 redirection 을 몇 번 따라갈지 지정할 수 있다. 기본 값은 50이다

curl -v daum.net 을 실행하면 결과값으로 다음과 같이 HTTP 302 가 리턴된다.

< HTTP/1.1 302 Object Moved
< Location: http://www.daum.net/

-L 옵션을 추가하면 www.daum.net 으로 재접속하여 결과를 받아오게 된다.

-d--dataHTTP Post dataFORM 을 POST 하는 HTTP나 JSON 으로 데이타를 주고받는 REST 기반의 웹서비스 디버깅시 유용한 옵션이다
-v--verbose 동작하면서 자세한 옵션을 출력한다. 
-J--remote-header-name어떤 웹서비스는 파일 다운로드시 Content-Disposition Header 를 파싱해야 정확한 파일이름을 알 수 있을 경우가 있다. -J 옵션을 주면 헤더에 있는 파일 이름으로 저장한다.curl 7.20 이상부터 추가된 옵션
-o--output FILEcurl 은 remote 에서 받아온 데이타를 기본적으로는 콘솔에 출력한다. -o 옵션 뒤에 FILE 을 적어주면 해당 FILE 로 저장한다. (download 시 유용) 
-O--remote-namefile 저장시 remote 의 file 이름으로 저장한다. -o 옵션보다 편리하다. 
-s--silent정숙 모드. 진행 내역이나 메시지등을 출력하지 않는다. -o 옵션으로 remote data 도 /dev/null 로 보내면 결과물도 출력되지 않는다HTTP response code 만 가져오거나 할 경우 유리

 

사용예(Example, Sample)

HTTP/HTTPS Download

HTTP로 다운로드

다운로드 받은 파일을 콘솔로 출력
curl http://www.gnu.org/software/bash/manual/html_node/index.html
지정한 이름으로 저장
curl -o index.html http://www.gnu.org/software/bash/manual/html_node/index.html
서버의 filename 으로 저장
curl -O  http://www.gnu.org/software/bash/manual/html_node/index.html
여러 url 에서 동시에 다운로드
curl -O  http://www.gnu.org/software/bash/manual/html_node/index.html -O http://www.gnu.org/savannah-checkouts/gnu/libiconv/documentation/libiconv-1.13/iconv.1.html

이어받기

-C/--continue-at  <offset> 옵션을 주면 이어받기 가능(offset 에 - 를 주면 전송이후 부분부터 이어받음)

이어 받기
curl -C - -O  http://www.gnu.org/software/bash/manual/html_node/index.html

특정일 이전/이후 변경되었으면 받기

 -z/--time-cond <time>

HTTP 헤더에 If-Modified-Since: 헤더를 추가하여 특정일 이후에 변경되었으면 다운로드 수행

아래 예제는 2011년 12월 21일 이후에 변경되었으면 다운로드 수행

curl -z 21-Dec-11 http://www.example.com/yy.html

날자앞에 - 를 추가하면 If-Unmodified-Since: 헤더를 추가하여 특정일 이전에 변경되었으면 다운로드 수행

아래 예제는 2011년 12월 21일 이전에 변경되었으면 다운로드함 (날자에 - 추가)

curl -z -21-Dec-11 http://www.example.com/yy.html

http response code 만 출력

HTTP Header 나 contents 는 빼고 HTTP Response code 만 출력한다. 서버의 정상 작동 여부 점검때 유용하다.

curl -s -o /dev/null -w "%{http_code}\n" http://www.example.com/yy.html

HTTP 인증

id/pwd 가 필요한 사이트의 경우 -u(–user) 옵션 뒤에 userid:password 를 지정하여 인증할 수 있다.

curl -v -u userid:password http://www.example.com/user.html

결과값에 HTTP Header 포함

-i 옵션을 사용하면 서버의 응답에 서버가 보낸 HTTP 헤더를 추가하여 출력한다. 디버깅에 유용한다.

curl -i https://api.github.com -u valid_username:valid_password

 

HTTP/HTTPS POST

HTTP FORM POST 

-X POST 옵션을 추가하거나 -d( --data) 옵션을 지정하면 기본값으로 POST 로 설정됨

FORM 파일
<form method="POST" action="post.php">
    <input type=text name="first_name">
    <input type=text name="last_name">
    <input type=submit name=press value=" OK ">
 </form>

POST 데이타는 "param1=value1&param2=value2" 형식으로 전달

curl -d "first_name=Bruce&last_name=Wayne&press=%20OK%20" http://posttestserver.com/post.php

 

데이타에 공백이나 기타 특수 문자가 있을 경우 URL encoding 을 해야 한다.

공백일 경우 일일이 + 로 변환해서 전송해야 하지만 최신 버전의 curl(7.18.0 이후) 은 FORM 파라미터를 URL Encoding 해주는 --data-urlencode 옵션을 사용하면 별도로 인코딩을 해주지 않아도 된다.

curl --data-urlencode "first_name=Bruce" --data-urlencode "last_name=Wayne" --data-urlencode "press= OK " http://posttestserver.com/post.php

Hidden field 전송시 일반 필드처럼 name=value 형식으로 전송하면 된다.

 

HTTP POST File

file POST할 경우 file name 앞에 @ 를 붙여줌 

curl -d @myPostfile http://posttestserver.com/post.php

HTTP POST Binary File

curl 은 POST 시 데이타를 text 로 취급하므로 binary 데이타는 깨질 수 있다. 제대로 전송하려면 --data-binary 옵션을 추가해야 한다.

curl --data-binary @myBinary.jpg http://posttestserver.com/post.php

HTTP File Upload Form

다음과 같은 파일 업로드 FORM 이 있을때

<form method="POST" enctype='multipart/form-data' action="upload.php">
 <input type=file name=upload>
 <input type=submit name=press value="OK">
</form>

localfilename 은 upload 할 파일명, submit 은 press=OK

curl --form upload=@localfilename --form press=OK http://localhost/upload.php

 

HTTP Header 설정

특정한 HTTP Header 를 설정해서 보내야 할 경우(Ex: json data등) -H (–header) 옵션으로 헤더를 설정할 수 있다.

Content-Type Header 설정

curl -d @myJson.js -H "Content-Type: application/json" http://localhost:8080/jsonEcho

User-Agent 설정

특정 브라우저인(Browser) 것처럼 동작하기 위해서는 -A ( --user-agent) 옵션을 사용할 수 있다. (http://www.useragentstring.com/)

 

USER-AGENT CHROME 24.0
Chrome 24.0 으로 User-Agent 설정
curl -d @myJson.js -H "Content-Type: application/json" --user-agent "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.14 (KHTML, like Gecko) Chrome/24.0.1292.0 Safari/537.14" http://localhost:8080/jsonEcho
USER-AGENT MSIE(INTERNET EXPLORER) 10.0
IE 10.0
curl -d @myJson.js -H "Content-Type: application/json" --user-agent "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0)" http://localhost:8080/jsonEcho

 

USER-AGENT FIREFOX 29.0
Firefox 29.0
curl -d @myJson.js -H "Content-Type: application/json" --user-agent "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:29.0) Gecko/20120101 Firefox/29.0" http://localhost:8080/jsonEcho

Referer 설정

Referer 를 체크하는 사이트일 경우 -e (–referer) 옵션으로 Referer URL 을 설정할 수 있다.

curl --referer http://www.example.come/from  http://www.example.com/to

아니면 -H 옵션으로 referer 헤더를 지정해도 된다.

SSL/TLS 옵션

TLS Version 지정

SSL 의 후속 버전인 TLS 의 버전을 지정할 수 있다.  지정하지 않을 경우 서버와 negotiation하여 결정한다.

  • -1, --tlsv1     Use => TLSv1 (SSL)
  • --tlsv1.0       Use TLSv1.0 (SSL)
  • --tlsv1.1       Use TLSv1.1 (SSL)
  • --tlsv1.2       Use TLSv1.2 (SSL)
curl --tlsv1.2 https://www.example.come

SSL Version 지정

다음 옵션으로 사용할 SSL 의 버전을 지정할 수 있다. 지정하지 않을 경우 서버와 negotiation하여 결정한다. SSL 은 오래 됐으니 SSL 보다는 TLS 를 사용하는게 좋다.

  • -2, --sslv2         Use SSLv2 (SSL)
  • -3, --sslv3         Use SSLv3 (SSL)
curl --sslv3 https://www.example.come

REST API 와 연계

위의 옵션들이 익숙해졌으면 REST 기반의 웹서비스를 개발할 때 curl 을 이용해서 테스트 및 디버깅을 수행할 수 있다. REST API 를 제공하는 유명한 Web App 와 연계하는 방법을 정리해 본다.

curl로 Atlassian JIRA REST API 연계하기

 

Sonatype nexus Admin API

관리자 암호 변경

curl -v -k -d "{"data":{"userId":"admin","oldPassword":"admin123","newPassword":"admin1234"}}" -u admin:admin123 https://my-nexus-site/nexus/service/local/users_changepw

 

 

'참고소스 > Docker' 카테고리의 다른 글

Docker 기본 사용법  (0) 2017.02.20