Linux

[Linux] curl 명령어

TTOII 2022. 4. 5. 03:14
728x90

✔︎ curl 명령어란 ? 

리눅스에서 curl 이라는 http 메세지를 Shell 상에서 요청하여 결과를 확인하는 명령어이며, http를 이용하여 경로의 데이터를 가져온다. 

REST API를 제공하는 서비스와 연계되는 클라이언트를 개발할 때 서버의 동작을 터미널에서 확인해 볼 수 있다.

 

✔︎ curl 명령어 옵션

short long 설명
-k --insecure https 프로토콜에서 SSL 인증서에 대한 검증없이 연결
-l --head HTTP 헤더만 보여주고 컨텐츠는 표시하지 않음
-D --dump-header <file> HTTP 헤더를 file에 기록 (덤프)
-L --location HTTP 301, 302 응답을 받은 경우 리디렉션 URL로 따라간다. 
--max-redirs 옵션 뒤에 숫자로 몇 번의 리디렉션까지 따라갈 것인지를 적을 수 있다. 기본 값은 50이다.
-d --data HTTP Post 요청 데이터 입력
-v --verbose 동작하면서 세세한 내용을 출력
-J --remote-header-name 헤더에 있는 파일 이름으로 다운로드 파일을 저장
-o --output FILE curl로 받아온 내용을 FILE 이라는 이름의 파일로 저장
-O --remote-name 파일 저장시 리모트에 저장되어 있던 이름을 그대로 가져와서 로컬에 저장
-s --silent 진행 내용이나 메시지들을 출력하지 않음
-X --request 요청시 사용할 메소드의 종류 (GET, POST, PUT, PATCH, DELETE)

 

✔︎ curl 사용 예제

curl [options] [URL]

가장 간단한 형태로 옵션 없이 호출될 경우, 지정된 리소스를 표준 출력에 표시한다.

이 명령은 터미널 창에 www.google.com  홈페이지의 소스 코드를 출력한다.

프로토콜을 지정하지 않은 경우 curl은 사용할 프로토콜을 추측하려고 시도하며 이 프로토콜은 HTTP로 기본 설정된다.

curl www.google.com

출력을 파일에 저장

curl의 명령 결과를 저장하려면 -o 또는 -O 옵션을 사용한다.

Lowercase -o는 미리 정의된 파일 이름을 사용해 파일을 저장한다. 

curl -o vue-v2.6.10.js https://cdn.jsdelivr.net/npm/vue/dist/vue.js
curl -O https://cdn.jsdelivr.net/npm/vue/dist/vue.js
[ec2-user@ip-10-0-128-208 html]$ curl -O https://cdn.jsdelivr.net/npm/vue/dist/vue.js
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100  335k    0  335k    0     0  3855k      0 --:--:-- --:--:-- --:--:-- 3861k
[ec2-user@ip-10-0-128-208 html]$ ls
index.html  vue.js

 

여러 파일을 다운로드

여러 파일을 한번에 다운로드 하려면 여러 -O 옵션과 다운로드 하려는 파일의 URL을 차례로 사용한다.

다음 예에서는 Arch Linux 및 Debian ISO 파일을 다운로드 한다.

curl -O http://mirrors.edge.kernel.org/archlinux/iso/2018.06.01/archlinux-2018.06.01-x86_64.iso  \
     -O https://cdimage.debian.org/debian-cd/current/amd64/iso-cd/debian-9.4.0-amd64-netinst.iso

 

다운로드를 다시 시작

-C - 옵션을 사용해 다운로드를 재개할 수 있다. 

이 기능은 대용량 파일을 다운로드 하는 동안 연결이 끊긴 경우 유용하며 처음부터 다운로드하는 대신 이전 파일을 계속할 수 있다.

예를 들어 다음 명령을 사용해 Ubuntu 18.04 ISO 파일을 다운로드 하는 경우이다.

curl -O http://releases.ubuntu.com/18.04/ubuntu-18.04-live-server-amd64.iso

만약 연결이 유실되면 다음을 사용해 다운로드를 재개할 수 있다.

curl -C - -O http://releases.ubuntu.com/18.04/ubuntu-18.04-live-server-amd64.iso

 

URL의 HTTP 헤더를 가져오기

HTTP 헤더는 사용자 에이전트, 내용 유형 및 인코딩과 같은 정보를 포함하는 콜론 구분 키 값 쌍이다.

헤더는 요청 또는 응답과 함께 클라이언트와 서버 간에 전달된다.

-I 옵션을 사용해 지정된 리소스의 HTTP 헤더만 가져온다.

curl -I --http2 https://www.ubuntu.com/
[ec2-user@ip-10-0-128-208 html]$ curl -I --http2 https://www.ubuntu.com/
HTTP/2 301 
server: nginx/1.14.0 (Ubuntu)
date: Mon, 04 Apr 2022 17:59:18 GMT
content-type: text/html
content-length: 175
location: https://ubuntu.com/
link: <https://assets.ubuntu.com>; rel=preconnect; crossorigin, <https://assets.ubuntu.com>; rel=preconnect, <https://res.cloudinary.com>; rel=preconnect
x-cache-status: HIT from content-cache-il3/1

 

웹 사이트가 HTTP/2를 지원하는지 테스트

특정 URL이 새 HTTP/2 프로토콜을 지원하는지 확인하려면 -I와 함께 HTTP 헤더를 --http2 옵션과 함께 가져온다.

-s 옵션은 curl을 출력없이 실행하고 진행률 미터와 오류 메세지를 숨긴다.

만약 원격 서버가 HTTP/2를 지원하는 경우, curl은 HTTP/2.0 200을 인쇄한다.

지원하지 않으면 HTTP/1.1 200을 응답한다. 

curl -I --http2 -s https://linuxize.com/ | grep HTTP

 

Redirect URL을 따라가는 명령어

서버 링크가 다시 다른 URL로 re-direct 되어 있는 경우 -L 옵션을 사용해 최종 대상에 도달할 때까지 모든 리다이렉션을 따르도록 한다. 

예를 들어 https://example.com/url_org이 http://example.com/url_redirect 로 연결되어 있다면 url_redirect까지 접속한다.

[ec2-user@ip-10-0-128-208 html]$ curl google.com
<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">
<TITLE>301 Moved</TITLE></HEAD><BODY>
<H1>301 Moved</H1>
The document has moved
<A HREF="http://www.google.com/">here</A>.
</BODY></HTML>
[ec2-user@ip-10-0-128-208 html]$ curl -L google.com
<!doctype html><html itemscope="" itemtype="http://schema.org/WebPage" lang="en"><head><meta content="Search the world's information, including webpages, images, videos and more. Google has many special features to help you find exactly what you're looking for." name="description"><meta content="noodp" name="robots"><meta content="text/html; charset=UTF-8" http-equiv="Content-Type"><meta content="/images/branding/googleg/1x/googleg_standard_color_128dp.png" itemprop="image"><title>Google</title><script nonce="ivvK79JV58lk4QF7+qT5sw==">(function(){window.google={kEI:'MjRLYpjtL_mckPIP-MGWkAM',kEXPI:'0,202454,3,1100079,56873,6058,207,4804,2316,383,246,5,1354,4013,1237,1122516,1197695,380796,16114,17444,1953,9287,17572,4859,1361,9290,3022,2823,14764,4020,978,13228,3847,3599,593,6434,12441,10298,5079,1593,1279,2742,149,1103,840,1983,4314,3514,606,2023,1777,520,14670,3227,2845,7,17450,16320,1850,15325,432,3,346,1244,1,5444,149,11323,991,1661,4,1528,2304,6462,577,22023,3050,2658,4164,3193,30,894,1,12733,2980,10815,5993,1435,5791,2566,4094,17,4035,3,3541,1,14711,2096,10375,14972,2,14022,1649,350,374,342,255,2993,285,1272,744,5852,10463,1160,5679,1020,2378,2721,16548,1713,1,8,7754,4568,6255,3005,3721,1,2774,12881,1039,1252,5835,14968,1550,2782,2204,2083,390,1412,1395,445,2,2,1,1508,4886,18232,152,1407,10,1,436,8155,113,2453,4016,568,231,2,3,124,58,2,1291,968,594,859,4355,2215,421,880,1972,936,1562,4987,792,1399,3048,174,1449,3,1,5829,85,142,1144,242,1168,914,415,371,172,601,3967,966,1760,201,757,748,607,24,30,750,100,750,1182,232,1961,95,184,2369,75,26,201,110,375,2754,124,741,333,233,443,996,309,4,145,453,433,10,59,11,2,418,934,227,303,1332,402,5445641,3893,101,1214,8796696,882,444,3,1877,1,2562,1,748,141,795,563,1,4265,1,1,2,1331,4142,2609,155,17,13,72,139,4,2,20,2,169,13,19,46,5,39,96,548,29,2,2,1,2,1,2,2,7,4,1,2,2,2,2,2,2,353,513,186,1,1,158,3,2,2,2,2,2,4,2,3,3,269,1601,141,1002,71,241,126,7,2,8,7,2,5,1,5,3,24,23951476,2772895,1265680,3,3112,3,450,1964,2935,159,1358,4726,3,2173,4214,1104,2555,956,9',kBL:'zIb2'};google.sn='webhp';google.kHL='en';})();(function(){
var f=this||self;var h,k=[];function l(a){for(var b;a&&(!a.getAttribute||!(b=a.getAttribute("eid")));)a=a.parentNode;return b||h}function m(a){for(var b=null;a&&(!a.getAttribute||!(b=a.getAttribute("leid")));)a=a.parentNode;return b}
function n(a,b,c,d,g){var e="";c||-1!==b.search("&ei=")||(e="&ei="+l(d),-1===b.search("&lei=")&&(d=m(d))&&(e+="&lei="+d));d="";!c&&f._cshid&&-1===b.search("&cshid=")&&"slh"!==a&&(d="&cshid="+f._cshid);c=c||"/"+(g||"gen_204")+"?atyp=i&ct="+a+"&cad="+b+e+"&zx="+Date.now()+d;/^http:/i.test(c)&&"https:"===window.location.protocol&&(google.ml&&google.ml(Error("a"),!1,{src:c,glmm:1}),c="");return c};h=google.kEI;google.getEI=l;google.getLEI=m;google.ml=function(){return null};google.log=function(a,b,c,d,g){if(c=n(a,b,c,d,g)){a=new Image;var e=k.length;k[e]=a;a.onerror=a.onload=a.onabort=function(){delete k[e]};a.src=c}};google.logUrl=n;}).call(this);(function(){
google.y={};google.sy=[];google.x=function(a,b){if(a)var c=a.id;else{do c=Math.random();while(google.y[c])}google.y[c]=[a,b];return!1};google.sx=function(a){google.sy.push(a)};google.lm=[];google.plm=function(a){google.lm.push.apply(google.lm,a)};google.lq=[];google.load=function(a,b,c){google.lq.push([[a],b,c])};google.loadAll=function(a,b){google.lq.push([a,b])};google.bx=!1;google.lx=function(){};}).call(this);google.f={};(function(){
document.documentElement.addEventListener("submit",function(b){var a;if(a=b.target){var c=a.getAttribute("data-submitfalse");a="1"===c||"q"===c&&!a.elements.q.value?!0:!1}else a=!1;a&&(b.preventDefault(),b.stopPropagation())},!0);document.documentElement.addEventListener("click",function(b){var a;a:{for(a=b.target;a&&a!==document.documentElement;a=a.parentElement)if("A"===a.tagName){a="1"===a.getAttribute("data-nohref");break a}a=!1}a&&b.preventDefault()},!0);}).call(this);</script><style>#gbar,#guser{font-size:13px;padding-top:1px !important;}#gbar{height:22px}#guser{padding-bottom:7px !important;text-align:right}.gbh,.gbd{border-top:1px solid #c9d7f1;font-size:1px}.gbh{height:0;position:absolute;top:24px;width:100%}@media all{.gb1{height:22px;margin-right:.5em;vertical-align:top}#gbar{float:left}}a.gb1,a.gb4{text-decoration:underline !important}a.gb1,a.gb4{color:#00c !important}.gbi .gb4{color:#dd8e27 !important}.gbf .gb4{color:#900 !important}
</style><style>body,td,a,p,.h{font-family:arial,sans-serif}body{margin:0;overflow-y:scroll}#gog{padding:3px 8px 0}td{line-height:.8em}.gac_m td{line-height:17px}form{margin-bottom:20px}.h{color:#1558d6}em{font-weight:bold;font-style:normal}.lst{height:25px;width:496px}.gsfi,.lst{font:18px arial,sans-serif}.gsfs{font:17px arial,sans-serif}.ds{display:inline-box;display:inline-block;margin:3px 0 4px;margin-left:4px}input{font-family:inherit}body{background:#fff;color:#000}a{color:#4b11a8;text-decoration:none}a:hover,a:active{text-decoration:underline}.fl a{color:#1558d6}a:visited{color:#4b11a8}.sblc{padding-top:5px}.sblc a{display:block;margin:2px 0;margin-left:13px;font-size:11px}.lsbb{background:#f8f9fa;border:solid 1px;border-color:#dadce0 #70757a #70757a #dadce0;height:30px}.lsbb{display:block}#WqQANb a{display:inline-block;margin:0 12px}.lsb{background:url(/images/nav_logo229.png) 0 -261px repeat-x;border:none;color:#000;cursor:pointer;height:30px;margin:0;outline:0;font:15px arial,sans-serif;vertical-align:top}.lsb:active{background:#dadce0}.lst:focus{outline:none}</style><script nonce="ivvK79JV58lk4QF7+qT5sw==">(function(){window.google.erd={jsr:1,bv:1555,de:true};
var f=this||self;var g,h=null!=(g=f.mei)?g:1,m,n=null!=(m=f.sdo)?m:!0,p=0,q,r=google.erd,u=r.jsr;google.ml=function(a,b,d,k,c){c=void 0===c?2:c;b&&(q=a&&a.message);if(google.dl)return google.dl(a,c,d),null;if(0>u){window.console&&console.error(a,d);if(-2===u)throw a;b=!1}else b=!a||!a.message||"Error loading script"===a.message||p>=h&&!k?!1:!0;if(!b)return null;p++;d=d||{};var e=c;c=encodeURIComponent;b="/gen_204?atyp=i&ei="+c(google.kEI);google.kEXPI&&(b+="&jexpid="+c(google.kEXPI));b+="&srcpg="+c(google.sn)+"&jsr="+c(r.jsr)+"&bver="+c(r.bv)+("&jsel="+e);e=a.lineNumber;void 0!==e&&(b+="&line="+
e);var l=a.fileName;l&&(b+="&script="+c(l),e&&l===window.location.href&&(e=document.documentElement.outerHTML.split("\n")[e],b+="&cad="+c(e?e.substring(0,300):"No script found.")));for(var t in d)b+="&",b+=c(t),b+="=",b+=c(d[t]);b=b+"&emsg="+c(a.name+": "+a.message);b=b+"&jsst="+c(a.stack||"N/A");12288<=b.length&&(b=b.substr(0,12288));a=b;k||google.log(0,"",a);return a};window.onerror=function(a,b,d,k,c){q!==a&&(a=c instanceof Error?c:Error(a),void 0===d||"lineNumber"in a||(a.lineNumber=d),void 0===b||"fileName"in a||(a.fileName=b),google.ml(a,!1,void 0,!1,"SyntaxError"===a.name||"SyntaxError"===a.message.substring(0,11)?2:0));q=null;n&&p>=h&&(window.onerror=null)};})();</script></head><body bgcolor="#fff"><script nonce="ivvK79JV58lk4QF7+qT5sw==">(function(){var src='/images/nav_logo229.png';var iesg=false;document.body.onload = function(){window.n && window.n();if (document.images){new Image().src=src;}
if (!iesg){document.f&&document.f.q.focus();document.gbqf&&document.gbqf.q.focus();}
--- 생략 ---

 

User-agent 변경

경우에 따라 파일을 다운로드 할 때 방문자 장치 및 브라우저에 따라 사용자 에이전트 컬을 차단하거나 다른 내용을 반환하도록 원격 서버를 설정할 수 있다.

이런 경우 브라우저를 에뮬레이트하려면 -A 옵션을 사용한다.

예를 들어 Firefox 60을 에뮬레이트하는 경우 다음을 사용한다. 

curl -A "Mozilla/5.0 (X11; Linux x86_64; rv:60.0) Gecko/20100101 Firefox/60.0" https://getfedora.org/

 

 

 

참고

728x90