curl命令详解
(1)、curl介绍
作为一款强力工具,curl支持包括HTTP、HTTPS、FTP在内的众多协议。它还支持POST、cookie、认证、从指定偏移处下载部分文件、参照页(referer)、用户代理字符串、扩展头部、限速、文件大小限制、进度条等特性。如果要和网页访问序列(web page usagesequence)以及数据检索自动化打交道,那么curl定能助你一臂之力。
(2)、curl的help
curl--help
Usage:curl[options...]<url>
Options:(H)meansHTTP/HTTPSonly,(F)meansFTPonly
--anyauthPick"any"authenticationmethod(H)
-a/--appendAppendtotargetfilewhenuploading(F/SFTP)
--basicUseHTTPBasicAuthentication(H)
--cacert<file>CAcertificatetoverifypeeragainst(SSL)
--capath<directory>CAdirectorytoverifypeeragainst(SSL)
-E/--cert<cert[:passwd]>Clientcertificatefileandpassword(SSL)
--cert-type<type>Certificatefiletype(DER/PEM/ENG)(SSL)
--ciphers<list>SSLcipherstouse(SSL)
--compressedRequestcompressedresponse(usingdeflateorgzip)
-K/--config<file>Specifywhichconfigfiletoread
--connect-timeout<seconds>Maximumtimeallowedforconnection
-C/--continue-at<offset>Resumedtransferoffset
-b/--cookie<name=string/file>Cookiestringorfiletoreadcookiesfrom(H)
-c/--cookie-jar<file>Writecookiestothisfileafteroperation(H)
--create-dirsCreatenecessarylocaldirectoryhierarchy
--crlfConvertLFtoCRLFinupload
--crlfile<file>GetaCRLlistinPEMformatfromthegivenfile
-d/--data<data>HTTPPOSTdata(H)
--data-ascii<data>HTTPPOSTASCIIdata(H)
--data-binary<data>HTTPPOSTbinarydata(H)
--data-urlencode<name=data/name@filename>HTTPPOSTdataurlencoded(H)
--delegationSTRINGGSS-APIdelegationpermission
--digestUseHTTPDigestAuthentication(H)
--disable-eprtInhibitusingEPRTorLPRT(F)
--disable-epsvInhibitusingEPSV(F)
-D/--dump-header<file>Writetheheaderstothisfile
--egd-file<file>EGDsocketpathforrandomdata(SSL)
--engine<eng>Cryptoenginetouse(SSL)."--enginelist"forlist
-f/--failFailsilently(nooutputatall)onHTTPerrors(H)
-F/--form<name=content>SpecifyHTTPmultipartPOSTdata(H)
--form-string<name=string>SpecifyHTTPmultipartPOSTdata(H)
--ftp-account<data>Accountdatatosendwhenrequestedbyserver(F)
--ftp-alternative-to-user<cmd>Stringtoreplace"USER[name]"(F)
--ftp-create-dirsCreatetheremotedirsifnotpresent(F)
--ftp-method[multicwd/nocwd/singlecwd]ControlCWDusage(F)
--ftp-pasvUsePASV/EPSVinsteadofPORT(F)
-P/--ftp-port<address>UsePORTwithaddressinsteadofPASV(F)
--ftp-skip-pasv-ipSkiptheIPaddressforPASV(F)
--ftp-sslTrySSL/TLSforftptransfer(F)
--ftp-ssl-cccSendCCCafterauthenticating(F)
--ftp-ssl-ccc-mode[active/passive]SetCCCmode(F)
--ftp-ssl-controlRequireSSL/TLSforftplogin,clearfortransfer(F)
--ftp-ssl-reqdRequireSSL/TLSforftptransfer(F)
-G/--getSendthe-ddatawithaHTTPGET(H)
-g/--globoffDisableURLsequencesandrangesusing{}and[]
-H/--header<line>Customheadertopasstoserver(H)
-I/--headShowdocumentinfoonly
-h/--helpThishelptext
--hostpubmd5<md5>HexencodedMD5stringofthehostpublickey.(SSH)
-0/--http1.0UseHTTP1.0(H)
--ignore-content-lengthIgnoretheHTTPContent-Lengthheader
-i/--includeIncludeprotocolheadersintheoutput(H/F)
-k/--insecureAllowconnectionstoSSLsiteswithoutcerts(H)
--interface<interface>Specifynetworkinterface/addresstouse
-4/--ipv4ResolvenametoIPv4address
-6/--ipv6ResolvenametoIPv6address
-j/--junk-session-cookiesIgnoresessioncookiesreadfromfile(H)
--keepalive-time<seconds>Intervalbetweenkeepaliveprobes
--key<key>Privatekeyfilename(SSL/SSH)
--key-type<type>Privatekeyfiletype(DER/PEM/ENG)(SSL)
--krb<level>EnableKerberoswithspecifiedsecuritylevel(F)
--libcurl<file>Dumplibcurlequivalentcodeofthiscommandline
--limit-rate<rate>Limittransferspeedtothisrate
-l/--list-onlyListonlynamesofanFTPdirectory(F)
--local-port<num>[-num]Forceuseoftheselocalportnumbers
-L/--locationFollowLocation:hints(H)
--location-trustedFollowLocation:andsendauthtootherhosts(H)
-M/--manualDisplaythefullmanual
--max-filesize<bytes>Maximumfilesizetodownload(H/F)
--max-redirs<num>Maximumnumberofredirectsallowed(H)
-m/--max-time<seconds>Maximumtimeallowedforthetransfer
--negotiateUseHTTPNegotiateAuthentication(H)
-n/--netrcMustread.netrcforusernameandpassword
--netrc-optionalUseeither.netrcorURL;overrides-n
-N/--no-bufferDisablebufferingoftheoutputstream
--no-keepaliveDisablekeepaliveuseontheconnection
--no-sessionidDisableSSLsession-IDreusing(SSL)
--noproxyComma-separatedlistofhostswhichdonotuseproxy
--ntlmUseHTTPNTLMauthentication(H)
-o/--output<file>Writeoutputto<file>insteadofstdout
--pass<pass>Passphrasefortheprivatekey(SSL/SSH)
--post301DonotswitchtoGETafterfollowinga301redirect(H)
--post302DonotswitchtoGETafterfollowinga302redirect(H)
-#/--progress-barDisplaytransferprogressasaprogressbar
-x/--proxy<host[:port]>UseHTTPproxyongivenport
--proxy-anyauthPick"any"proxyauthenticationmethod(H)
--proxy-basicUseBasicauthenticationontheproxy(H)
--proxy-digestUseDigestauthenticationontheproxy(H)
--proxy-negotiateUseNegotiateauthenticationontheproxy(H)
--proxy-ntlmUseNTLMauthenticationontheproxy(H)
-U/--proxy-user<user[:password]>Setproxyuserandpassword
--proxy1.0<host[:port]>UseHTTP/1.0proxyongivenport
-p/--proxytunnelOperatethroughaHTTPproxytunnel(usingCONNECT)
--pubkey<key>Publickeyfilename(SSH)
-Q/--quote<cmd>Sendcommand(s)toserverbeforefiletransfer(F/SFTP)
--random-file<file>Fileforreadingrandomdatafrom(SSL)
-r/--range<range>Retrieveonlythebyteswithinarange
--rawPassHTTP"raw",withoutanytransferdecoding(H)
-e/--refererRefererURL(H)
-O/--remote-nameWriteoutputtoafilenamedastheremotefile
--remote-name-allUsetheremotefilenameforallURLs
-R/--remote-timeSettheremotefile‘stimeonthelocaloutput
-X/--request<command>Specifyrequestcommandtouse
--retry<num>Retryrequest<num>timesiftransientproblemsoccur
--retry-delay<seconds>Whenretrying,waitthismanysecondsbetweeneach
--retry-max-time<seconds>Retryonlywithinthisperiod
-S/--show-errorShowerror.With-s,makecurlshowerrorswhentheyoccur
-s/--silentSilentmode.Don‘toutputanything
--socks4<host[:port]>SOCKS4proxyongivenhost+port
--socks4a<host[:port]>SOCKS4aproxyongivenhost+port
--socks5<host[:port]>SOCKS5proxyongivenhost+port
--socks5-hostname<host[:port]>SOCKS5proxy,passhostnametoproxy
--socks5-gssapi-service<name>SOCKS5proxyservicenameforgssapi
--socks5-gssapi-necCompatibilitywithNECSOCKS5server
-Y/--speed-limitStoptransferifbelowspeed-limitfor‘speed-time‘secs
-y/--speed-timeTimeneededtotrigspeed-limitabort.Defaultsto30
-2/--sslv2UseSSLv2(SSL)
-3/--sslv3UseSSLv3(SSL)
--stderr<file>Wheretoredirectstderr.-meansstdout
--tcp-nodelayUsetheTCP_NODELAYoption
-t/--telnet-option<OPT=val>Settelnetoption
-z/--time-cond<time>Transferbasedonatimecondition
-1/--tlsv1Use=>TLSv1(SSL)
--tlsv1.0UseTLSv1.0(SSL)
--tlsv1.1UseTLSv1.1(SSL)
--tlsv1.2UseTLSv1.2(SSL)
--trace<file>Writeadebugtracetothegivenfile
--trace-ascii<file>Like--tracebutwithoutthehexoutput
--trace-timeAddtimestampstotrace/verboseoutput
-T/--upload-file<file>Transfer<file>toremotesite
--url<URL>SetURLtoworkwith
-B/--use-asciiUseASCII/texttransfer
-u/--user<user[:password]>Setserveruserandpassword
-A/--user-agent<string>User-Agenttosendtoserver(H)
-v/--verboseMaketheoperationmoretalkative
-V/--versionShowversionnumberandquit
-w/--write-out<format>Whattooutputaftercompletion
-qIfusedasthefirstparameterdisables.curlrc
(3)、curl实战
示例1:不带参数的curl
$curlURL
不带任何参数,curl会将下载文件输出到stdout,将进度信息输出到stderr
示例2:避免curl命令显示进度信息
可以使用--silent选项。
$curl--silentURL
[root@MuBanJi_01curl]#curlhttp://10.72.10.5:10010>a.html
%Total%Received%XferdAverageSpeedTimeTimeTimeCurrent
DloadUploadTotalSpentLeftSpeed
10053461005346002931k0--:--:----:--:----:--:--5220k
[root@MuBanJi_01curl]#
[root@MuBanJi_01curl]#
[root@MuBanJi_01curl]#
[root@MuBanJi_01curl]#curlhttp://10.72.10.5:10010--silent>a.html
[root@MuBanJi_01curl]#ll
总用量8
-rw-r--r--.1rootroot53469月1019:36a.html
[root@MuBanJi_01curl]#
示例3:-O和-o选项
-o/--output<file> Write output to <file> instead of stdout
-O/--remote-name Write output to a file named as the remotefile
选项–o表明将下载数据写入文件,而非标准输出中。文件名由自己手工指定,是必要参数。
选项-O表示将下载数据写入文件,不过不需要指定文件名,该文件采用的是从URL中解析出的文件名
如果在URL中找不到文件名,则会产生错误。因此要确保URL指向的是远程文件。Curl http://10.72.10.5:10010/-O --silent就会显示错误信息,这是因为无法从URL中解析出文件名。
$curlURL--silent–ofilename
$curlURL--silent-O
[root@MuBanJi_01curl]#ll
总用量0
[root@MuBanJi_01curl]#curl--silent-Ohttp://10.72.10.5:10010/index.html
[root@MuBanJi_01curl]#ll
总用量8
-rw-r--r--.1rootroot53469月1019:45index.html
[root@MuBanJi_01curl]#curl--silent-oa.htmlhttp://10.72.10.5:10010/index.html
[root@MuBanJi_01curl]#ll
总用量1