curl命令详解 (1)、curl介绍
作为一款强力工具,curl支持包括HTTP、HTTPS、FTP在内的众多协议。它还支持POST、cookie、认证、从指定偏移处下载部分文件、参照页(referer)、用户代理字符串、扩展头部、限速、文件大小限制、进度条等特性。如果要和网页访问序列(web page usagesequence)以及数据检索自动化打交道,那么curl定能助你一臂之力。 (2)、curl的help
curl --helpUsage: curl [options...] Options: (H) means HTTP/HTTPS only, (F) means FTP only --anyauth Pick "any" authentication method (H) -a/--append Append to target file when uploading (F/SFTP) --basic Use HTTP Basic Authentication (H) --cacert CA certificate to verify peer against (SSL) --capath CA directory to verify peer against (SSL) -E/--cert Client certificate file and password (SSL) --cert-type Certificate file type (DER/PEM/ENG) (SSL) --ciphers SSL ciphers to use (SSL) --compressed Request compressed response (using deflate or gzip) -K/--config Specify which config file to read --connect-timeout Maximum time allowed for connection -C/--continue-at Resumed transfer offset -b/--cookie Cookie string or file to read cookies from (H) -c/--cookie-jar Write cookies to this file after operation (H) --create-dirs Create necessary local directory hierarchy --crlf Convert LF to CRLF in upload --crlfile Get a CRL list in PEM format from the given file -d/--data HTTP POST data (H) --data-ascii HTTP POST ASCII data (H) --data-binary HTTP POST binary data (H) --data-urlencode HTTP POST data url encoded (H) --delegation STRING GSS-API delegation permission --digest Use HTTP Digest Authentication (H) --disable-eprt Inhibit using EPRT or LPRT (F) --disable-epsv Inhibit using EPSV (F) -D/--dump-header Write the headers to this file --egd-file EGD socket path for random data (SSL) --engine Crypto engine to use (SSL). "--engine list" for list -f/--fail Fail silently (no output at all) on HTTP errors (H) -F/--form Specify HTTP multipart POST data (H) --form-string Specify HTTP multipart POST data (H) --ftp-account Account data to send when requested by server (F) --ftp-alternative-to-user String to replace "USER [name]" (F) --ftp-create-dirs Create the remote dirs if not present (F) --ftp-method [multicwd/nocwd/singlecwd] Control CWD usage (F) --ftp-pasv Use PASV/EPSV instead of PORT (F) -P/--ftp-port Use PORT with address instead of PASV (F) --ftp-skip-pasv-ip Skip the IP address for PASV (F) --ftp-ssl Try SSL/TLS for ftp transfer (F) --ftp-ssl-ccc Send CCC after authenticating (F) --ftp-ssl-ccc-mode [active/passive] Set CCC mode (F) --ftp-ssl-control Require SSL/TLS for ftp login, clear for transfer (F) --ftp-ssl-reqd Require SSL/TLS for ftp transfer (F) -G/--get Send the -d data with a HTTP GET (H) -g/--globoff Disable URL sequences and ranges using {} and [] -H/--header Custom header to pass to server (H) -I/--head Show document info only -h/--help This help text --hostpubmd5 Hex encoded MD5 string of the host public key. (SSH) -0/--http1.0 Use HTTP 1.0 (H) --ignore-content-length Ignore the HTTP Content-Length header -i/--include Include protocol headers in the output (H/F) -k/--insecure Allow connections to SSL sites without certs (H) --interface Specify network interface/address to use -4/--ipv4 Resolve name to IPv4 address -6/--ipv6 Resolve name to IPv6 address -j/--junk-session-cookies Ignore session cookies read from file (H) --keepalive-time Interval between keepalive probes --key Private key file name (SSL/SSH) --key-type Private key file type (DER/PEM/ENG) (SSL) --krb Enable Kerberos with specified security level (F) --libcurl Dump libcurl equivalent code of this command line --limit-rate Limit transfer speed to this rate -l/--list-only List only names of an FTP directory (F) --local-port [-num] Force use of these local port numbers -L/--location Follow Location: hints (H) --location-trusted Follow Location: and send auth to other hosts (H) -M/--manual Display the full manual --max-filesize Maximum file size to download (H/F) --max-redirs Maximum number of redirects allowed (H) -m/--max-time Maximum time allowed for the transfer --negotiate Use HTTP Negotiate Authentication (H) -n/--netrc Must read .netrc for user name and password --netrc-optional Use either .netrc or URL; overrides -n -N/--no-buffer Disable buffering of the output stream --no-keepalive Disable keepalive use on the connection --no-sessionid Disable SSL session-ID reusing (SSL) --noproxy Comma-separated list of hosts which do not use proxy --ntlm Use HTTP NTLM authentication (H) -o/--output Write output to instead of stdout --pass Pass phrase for the private key (SSL/SSH) --post301 Do not switch to GET after following a 301 redirect (H) --post302 Do not switch to GET after following a 302 redirect (H) -#/--progress-bar Display transfer progress as a progress bar -x/--proxy Use HTTP proxy on given port --proxy-anyauth Pick "any" proxy authentication method (H) --proxy-basic Use Basic authentication on the proxy (H) --proxy-digest Use Digest authentication on the proxy (H) --proxy-negotiate Use Negotiate authentication on the proxy (H) --proxy-ntlm Use NTLM authentication on the proxy (H) -U/--proxy-user Set proxy user and password --proxy1.0 Use HTTP/1.0 proxy on given port -p/--proxytunnel Operate through a HTTP proxy tunnel (using CONNECT) --pubkey Public key file name (SSH) -Q/--quote Send command(s) to server before file transfer (F/SFTP) --random-file File for reading random data from (SSL) -r/--range Retrieve only the bytes within a range --raw Pass HTTP "raw", without any transfer decoding (H) -e/--referer Referer URL (H) -O/--remote-name Write output to a file named as the remote file --remote-name-all Use the remote file name for all URLs -R/--remote-time Set the remote file's time on the local output -X/--request Specify request command to use --retry Retry request times if transient problems occur --retry-delay When retrying, wait this many seconds between each --retry-max-time Retry only within this period -S/--show-error Show error. With -s, make curl show errors when they occur -s/--silent Silent mode. Don't output anything --socks4 SOCKS4 proxy on given host + port --socks4a SOCKS4a proxy on given host + port --socks5 SOCKS5 proxy on given host + port --socks5-hostname SOCKS5 proxy, pass host name to proxy --socks5-gssapi-service SOCKS5 proxy service name for gssapi --socks5-gssapi-nec Compatibility with NEC SOCKS5 server -Y/--speed-limit Stop transfer if below speed-limit for 'speed-time' secs -y/--speed-time Time needed to trig speed-limit abort. Defaults to 30 -2/--sslv2 Use SSLv2 (SSL) -3/--sslv3 Use SSLv3 (SSL) --stderr Where to redirect stderr. - means stdout --tcp-nodelay Use the TCP_NODELAY option -t/--telnet-option Set telnet option -z/--time-cond Transfer based on a time condition -1/--tlsv1 Use => TLSv1 (SSL) --tlsv1.0 Use TLSv1.0 (SSL) --tlsv1.1 Use TLSv1.1 (SSL) --tlsv1.2 Use TLSv1.2 (SSL) --trace Write a debug trace to the given file --trace-ascii Like --trace but without the hex output --trace-time Add time stamps to trace/verbose output -T/--upload-file Transfer to remote site --url Set URL to work with -B/--use-ascii Use ASCII/text transfer -u/--user Set server user and password -A/--user-agent User-Agent to send to server (H) -v/--verbose Make the operation more talkative -V/--version Show version number and quit -w/--write-out What to output after completion -q If used as the first parameter disables .curlrc (3)、curl实战 示例1:不带参数的curl
$ curl URL 不带任何参数,curl会将下载文件输出到stdout,将进度信息输出到stderr
示例11:用curl进行认证
可以用curl的选项 -u完成HTTP或FTP认证。
-uusername:password可用来指定用户名和密码。它也可以不指定密码,而在后续的执行过程中按照提示输入密码。例如:
$ curl -u user:pass http://test_auth.com 如果你喜欢经提示后输入密码,只需要使用 -u username即可。例如:
$ curl -u user http://test_auth.com 示例12:只打印响应头部信息(不包括数据部分)
-I/--head Show document info only
只打印响应头部(response header)有助于进行各种检查或统计。例如,如果要检查某个页面是否能够打开,并不需要下载整个页面内容。只用读取HTTP响应头部就能够知道这个页面是否可用。
检查HTTP头部的一个用法就是在下载之前先获知文件大小。我们可以在下载之前,通过检查HTTP头部中的 Content-Length 参数来得知文件的长度。同样还可以从头部检索出其他一些有用的参数。Last-Modified参数能告诉我们远程文件最后的改动时间。
通过 -I或--head 就可以只打印HTTP头部信息,而无须下载远程文件。例如:
[root@MuBanJi_01 curl]# curl -I http://10.72.10.5:10010/index.htmlHTTP/1.1 200 OKServer: nginxDate: Sun, 10 Sep 2017 12:25:22 GMTContent-Type: text/htmlContent-Length: 5346Connection: keep-aliveVary: Accept-EncodingLast-Modified: Fri, 18 Aug 2017 09:41:43 GMTVary: Accept-EncodingETag: "5996b657-14e2"Accept-Ranges: bytes 示例13:-w选项,输出指定格式的内容到标准输出
-w/--write-out What to output after completion
顾名思义,write-out的作用就是输出点什么。curl的-w参数用于在一次完整且成功的操作后输出指定格式的内容到标准输出。
输出格式由普通字符串和任意数量的变量组成,输出变量需要按照%{variable_name}的格式,如果需要输出%,double一下即可,即%%,同时,\n是换行,\r是回车,\t是TAB。curl会用合适的值来替代输出格式中的变量,所有可用变量如下:
url_effective
最终获取的url地址,尤其是当你指定给curl的地址存在301跳转,且通过-L继续追踪的情形。
http_code
http状态码,如200成功,301转向,404未找到,500服务器错误等。(The numerical response code that was found in the lastretrieved HTTP(S) or FTP(s) transfer. In 7.18.2 the alias response_code wasadded to show the same info.)
$ curl -I -s -o /dev/null -w %{http_code}"\n" http://10.72.10.5:10010/index.html200
http_connect
The numericalcode that was found in the last response (from a proxy) to a curl CONNECTrequest. (Added in 7.12.4)
time_total
总时间,按秒计。精确到小数点后三位。(The total time,in seconds, that the full operation lasted. The time will be displayed withmillisecond resolution.)
time_namelookup
DNS解析时间,从请求开始到DNS解析完毕所用时间。(The time, in seconds, it took from the start until thename resolving was completed.)
time_connect
连接时间,从开始到建立TCP连接完成所用时间,包括前边DNS解析时间,如果需要单纯的得到连接时间,用这个time_connect时间减去前边time_namelookup时间。以下同理,不再赘述。(The time, inseconds, it took from the start until the TCP connect to the remote host (orproxy) was completed.)
time_appconnect
连接建立完成时间,如SSL/SSH等建立连接或者完成三次握手时间。(The time, inseconds, it took from the start until the SSL/SSH/etc connect/handshake to theremote host was completed. (Added in 7.19.0))
time_pretransfer
开始到准备传输的时间。(The time, in seconds, it took from the start until thefile transfer was just about to begin. This includes all pre-transfer commandsand negotiations that are specific to the particular protocol(s) involved.)
time_redirect
重定向时间,包括到最后一次传输前的几次重定向的DNS解析,连接,预传输,传输时间。(The time, inseconds, it took for all redirection steps include name lookup, connect,pretransfer and transfer before the final transaction was started.time_redirect shows the complete execution time for multiple redirections.(Added in 7.12.3))
time_starttransfer
开始传输时间。在发出请求之后,Web 服务器返回数据的第一个字节所用的时间(The time, inseconds, it took from the start until the first byte was just about to betransferred. This includes time_pretransfer and also the time the server neededto calculate the result.)
size_download
下载大小。(The total amount of bytes that were downloaded.)
size_upload
上传大小。(The total amount of bytes that were uploaded.)
size_header
下载的header的大小(The totalamount of bytes of the downloaded headers.)
size_request
请求的大小。(The total amount of bytes that were sent in the HTTPrequest.)
speed_download
下载速度,单位-字节每秒。(The averagedownload speed that curl measured for the complete download. Bytes per second.)
speed_upload
上传速度,单位-字节每秒。(The average upload speed that curl measured for thecomplete upload. Bytes per second.)
content_type
就是content-Type, (text/html;);(TheContent-Type of the requested document, if there was any.)
num_connects
Number of newconnects made in the recent transfer. (Added in 7.12.3)
num_redirects
Number ofredirects that were followed in the request. (Added in 7.12.3)
redirect_url
When a HTTPrequest was made without -L to follow redirects, this variable will show theactual URL a redirect would take you to. (Added in 7.18.2)
ftp_entry_path
The initial pathlibcurl ended up in when logging on to the remote FTP server. (Added in 7.15.4)
ssl_verify_result
ssl认证结果,返回0表示认证成功。( The result ofthe SSL peer certificate verification that was requested. 0 means theverification was successful. (Added in 7.19.0))