curl用法详解

curl用法详解

Curl(CommandLine Uniform Resource Locator),即在命令行中利用URL进行数据或者文件传输,它是Linux下强大的http命令行工具,其功能十分强大,我们来看下帮助页面,参数非常丰富。

[root@mx ~]# curl -h Usage: curl [options...] <url> Options: (H) means HTTP/HTTPS only, (F) means FTP only --anyauth Pick "any" authentication method (H) -a, --appendAppend to target file when uploading (F/SFTP) --basic Use HTTP Basic Authentication (H) --cacert FILE CA certificate to verify peer against (SSL) --capath DIRCA directory to verify peer against (SSL) -E, --cert CERT[:PASSWD] Client certificate file and password (SSL) --cert-type TYPE Certificate file type (DER/PEM/ENG) (SSL) --ciphers LISTSSL ciphers to use (SSL) --compressedRequest compressed response (using deflate or gzip) -K, --config FILE Specify which config file to read --connect-timeout SECONDSMaximum time allowed for connection -C, --continue-at OFFSETResumed transfer offset -b, --cookie STRING/FILEString or file to read cookies from (H) -c, --cookie-jar FILEWrite cookies to this file after operation (H) --create-dirs Create necessary local directory hierarchy --crlfConvert LF to CRLF in upload --crlfile FILEGet a CRL list in PEM format from the given file -d, --data DATA HTTP POST data (H) --data-ascii DATAHTTP POST ASCII data (H) --data-binary DATAHTTP POST binary data (H) --data-urlencode DATAHTTP POST data url encoded (H) --delegation STRING GSS-API delegation permission --digestUse HTTP Digest Authentication (H) --disable-eprtInhibit using EPRT or LPRT (F) --disable-epsvInhibit using EPSV (F) -D, --dump-header FILEWrite the headers to this file --egd-file FILEEGD socket path for random data (SSL) --engine ENGINGECrypto engine (SSL). "--engine list" for list -f, --failFail silently (no output at all) on HTTP errors (H) -F, --form CONTENTSpecify HTTP multipart POST data (H) --form-string STRINGSpecify HTTP multipart POST data (H) --ftp-account DATAAccount data string (F) --ftp-alternative-to-user COMMANDString to replace "USER [name]" (F) --ftp-create-dirsCreate the remote dirs if not present (F) --ftp-method [MULTICWD/NOCWD/SINGLECWD] Control CWD usage (F) --ftp-pasvUse PASV/EPSV instead of PORT (F) -P, --ftp-port ADRUse PORT with given address instead of PASV (F) --ftp-skip-pasv-ip Skip the IP address for PASV (F) --ftp-pretSend PRET before PASV (for drftpd) (F) --ftp-ssl-ccc Send CCC after authenticating (F) --ftp-ssl-ccc-mode ACTIVE/PASSIVESet CCC mode (F) --ftp-ssl-control Require SSL/TLS for ftp login, clear for transfer (F) -G, --get Send the -d data with a HTTP GET (H) -g, --globoff Disable URL sequences and ranges using {} and [] -H, --header LINE Custom header to pass to server (H) -I, --headShow document info only -h, --helpThis help text --hostpubmd5 MD5Hex encoded MD5 string of the host public key. (SSH) -0, --http1.0 Use HTTP 1.0 (H) --ignore-content-lengthIgnore the HTTP Content-Length header -i, --include Include protocol headers in the output (H/F) -k, --insecureAllow connections to SSL sites without certs (H) --interface INTERFACESpecify network interface/address to use -4, --ipv4Resolve name to IPv4 address -6, --ipv6Resolve name to IPv6 address -j, --junk-session-cookies Ignore session cookies read from file (H) --keepalive-time SECONDSInterval between keepalive probes --key KEY Private key file name (SSL/SSH) --key-type TYPE Private key file type (DER/PEM/ENG) (SSL) --krb LEVEL Enable Kerberos with specified security level (F) --libcurl FILEDump libcurl equivalent code of this command line --limit-rate RATELimit transfer speed to this rate -l, --list-only List only names of an FTP directory (F) --local-port RANGEForce use of these local port numbers -L, --locationFollow redirects (H) --location-trusted like --location and send auth to other hosts (H) -M, --manualDisplay the full manual --mail-from FROMMail from this address --mail-rcpt TOMail to this receiver(s) --mail-auth AUTHOriginator address of the original email --max-filesize BYTESMaximum file size to download (H/F) --max-redirs NUMMaximum number of redirects allowed (H) -m, --max-time SECONDSMaximum time allowed for the transfer --metalinkProcess given URLs as metalink XML file --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 --netrc-file FILESet up the netrc filename to use -N, --no-buffer Disable buffering of the output stream --no-keepaliveDisable keepalive use on the connection --no-sessionidDisable SSL session-ID reusing (SSL) --noproxy List of hosts which do not use proxy --ntlmUse HTTP NTLM authentication (H) -o, --output FILE Write output to <file> instead of stdout --pass 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) --post303 Do not switch to GET after following a 303 redirect (H) -#, --progress-barDisplay transfer progress as a progress bar --proto PROTOCOLSEnable/disable specified protocols --proto-redir PROTOCOLSEnable/disable specified protocols on redirect -x, --proxy [PROTOCOL://]HOST[:PORT] Use proxy on given port --proxy-anyauth Pick "any" proxy authentication method (H) --proxy-basic Use Basic authentication on the proxy (H) --proxy-digestUse Digest authentication on the proxy (H) --proxy-negotiate Use Negotiate authentication on the proxy (H) --proxy-ntlmUse NTLM authentication on the proxy (H) -U, --proxy-user USER[:PASSWORD]Proxy user and password --proxy1.0 HOST[:PORT]Use HTTP/1.0 proxy on given port -p, --proxytunnel Operate through a HTTP proxy tunnel (using CONNECT) --pubkey KEYPublic key file name (SSH) -Q, --quote CMD Send command(s) to server before transfer (F/SFTP) --random-file FILEFile for reading random data from (SSL) -r, --range RANGE Retrieve only the bytes within a range --raw Do HTTP "raw", without any transfer decoding (H) -e, --referer Referer URL (H) -J, --remote-header-name Use the header-provided filename (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 files time on the local output -X, --request COMMANDSpecify request command to use --resolve HOST:PORT:ADDRESSForce resolve of HOST:PORT to ADDRESS --retry NUM Retry request NUM times if transient problems occur --retry-delay SECONDS When retrying, wait this many seconds between each --retry-max-time SECONDSRetry only within this period -S, --show-errorShow error. With -s, make curl show errors when they occur -s, --silentSilent mode. Dont output anything --socks4 HOST[:PORT]SOCKS4 proxy on given host + port --socks4a HOST[:PORT]SOCKS4a proxy on given host + port --socks5 HOST[:PORT]SOCKS5 proxy on given host + port --socks5-basicEnable username/password auth for SOCKS5 proxies --socks5-gssapi Enable GSS-API auth for SOCKS5 proxies --socks5-hostname HOST[:PORT] SOCKS5 proxy, pass host name to proxy --socks5-gssapi-service NAMESOCKS5 proxy service name for gssapi --socks5-gssapi-necCompatibility with NEC SOCKS5 server -Y, --speed-limit RATEStop transfers below speed-limit for speed-time secs -y, --speed-time SECONDSTime for trig speed-limit abort. Defaults to 30 --ssl Try SSL/TLS (FTP, IMAP, POP3, SMTP) --ssl-reqdRequire SSL/TLS (FTP, IMAP, POP3, SMTP) -2, --sslv2 Use SSLv2 (SSL) -3, --sslv3 Use SSLv3 (SSL) --ssl-allow-beast Allow security flaw to improve interop (SSL) --stderr FILE Where to redirect stderr. - means stdout --tcp-nodelay Use the TCP_NODELAY option -t, --telnet-option OPT=VALSet telnet option --tftp-blksize VALUESet TFTP BLKSIZE option (must be >512) -z, --time-cond TIMETransfer 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) --tlsv1.3 Use TLSv1.3 (SSL) --tls-max VERSIONUse TLS up to VERSION (SSL) --trace FILEWrite a debug trace to the given file --trace-ascii FILELike --trace but without the hex output --trace-timeAdd time stamps to trace/verbose output --tr-encoding Request compressed transfer encoding (H) -T, --upload-file FILETransfer FILE to destination --url URL URL to work with -B, --use-ascii Use ASCII/text transfer -u, --user USER[:PASSWORD]Server user and password --tlsuser USERTLS username --tlspassword STRING TLS password --tlsauthtype STRINGTLS authentication type (default SRP) --unix-socket FILEConnect through this UNIX domain socket -A, --user-agent STRINGUser-Agent to send to server (H) -v, --verbose Make the operation more talkative -V, --version Show version number and quit -w, --write-out FORMATWhat to output after completion --xattrStore metadata in extended file attributes -q If used as the first parameter disables .curlrc [root@mx ~]#

curl在Mac和Linux下是自带的命令行工具,如果你也想在Windows上使用,这里推荐使用"git for windows"这个工具,你可以使用此关键字在网络上检索下载。

安装完成后,点击桌面的"Git Bash"后,就可以在Windows下使用curl命令行工具了。

基本用法

curl是http工具,最简单的使用方法就是直接搭配网址使用,比如请求百度的内容:

[root@mx ~]# curl www.baidu.com

-s 选项:加上此选项,不显示请求内容的进度信息。

-o 选项:将获取内容存储到本地文件,-o后接文件名,如把请求的内容存储到1.txt中

# 搭配-s选项一起使用 [root@mx ~]# curl -s-o 1.txt # 不使用-s时,显示进度信息 [root@mx ~]# curl -o 2.txt % Total% Received % XferdAverage Speed TimeTime TimeCurrent DloadUpload Total SpentLeftSpeed 100244310024430 0141830 --:--:-- --:--:-- --:--:-- 14203 [root@mx ~]# cat 1.txt <!DOCTYPE html> <!--STATUS OK--><html> <head><meta http-equiv=content-type content=text/html;charset=utf-8><meta http-equiv=X-UA-Compatible content=IE=Edge><meta content=always name=referrer><link rel=stylesheet type=text/css href=https://ss1.bdstatic.com/5eN1bjq8AAUYm2zgoY3K/r/www/cache/bdorz/baidu.min.css><title>百度一下,你就知道</title></head …… [root@mx ~]#

详细用法

-A 选项:

-A参数指定客户端的用户代理标头,即User-Agent。curl 的默认用户代理字符串是curl/[version]。 下面命令将User-Agent改成 Chrome 浏览器。

$ curl -A Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36 https://google.com

下面命令会移除User-Agent标头。

$ curl -A https://google.com

也可以通过-H参数直接指定标头,更改User-Agent。

$ curl -H User-Agent: php/1.0 https://google.com

-b 选项:

-b参数用来向服务器发送 Cookie。

$ curl -b foo=bar https://google.com

上面命令会生成一个标头Cookie: foo=bar,向服务器发送一个名为foo、值为bar的 Cookie。

$ curl -b foo1=bar;foo2=bar2 https://google.com

上面命令发送两个 Cookie。

$ curl -b cookies.txt https://www.google.com

上面命令读取本地文件cookies.txt,里面是服务器设置的 Cookie(参见-c参数),将其发送到服务器。

-c 选项:

-c参数将服务器设置的 Cookie 写入一个文件。

$ curl -c cookies.txt https://www.google.com

上面命令将服务器的 HTTP 回应所设置 Cookie 写入文本文件cookies.txt。

-d 选项:

-d参数用于发送 POST 请求的数据体。

$ curl -dlogin=emma&password=123-X POST https://google.com/login #或者 $ curl -d login=emma -d password=123 -X POSThttps://google.com/login

使用-d参数以后,HTTP 请求会自动加上标头Content-Type : application/x-www-form-urlencoded。并且会自动将请求转为 POST 方法,因此可以省略-X POST。

-d参数可以读取本地文本文件的数据,向服务器发送。

$ curl -d @data.txt https://google.com/login

上面命令读取data.txt文件的内容,作为数据体向服务器发送。

--data-urlencode --data-urlencode参数等同于-d,发送 POST 请求的数据体,区别在于会自动将发送的数据进行 URL 编码。

$ curl --data-urlencode comment=hello world https://google.com/login

上面代码中,发送的数据hello world之间有一个空格,需要进行 URL 编码。

-e 选项:

-e参数用来设置 HTTP 的标头Referer,表示请求的来源。

curl -e ?q=example

上面命令将Referer标头设为?q=example。

-H参数可以通过直接添加标头Referer,达到同样效果。

curl -H Referer: ?q=example

-F 参数:

-F参数用来向服务器上传二进制文件。

$ curl -F [email protected] https://google.com/profile

上面命令会给 HTTP 请求加上标头Content-Type: multipart/form-data,然后将文件photo.png作为file字段上传。

-F参数可以指定 MIME 类型。

$ curl -F [email protected];type=image/png https://google.com/profile

上面命令指定 MIME 类型为image/png,否则 curl 会把 MIME 类型设为application/octet-stream。

-F参数也可以指定文件名。

$ curl -F [email protected];filename=me.png https://google.com/profile

上面命令中,原始文件名为photo.png,但是服务器接收到的文件名为me.png。

-G 选项:

-G参数用来构造 URL 的查询字符串。

$ curl -G -d q=kitties -d count=20 https://google.com/search

上面命令会发出一个 GET 请求,实际请求的 URL 为/search?q=kitties&count=20。如果省略--G,会发出一个 POST 请求。

如果数据需要 URL 编码,可以结合--data--urlencode参数。

$ curl -G --data-urlencode comment=hello world https://www.example.com

-H 选项:

-H参数添加 HTTP 请求的标头。

$ curl -H Accept-Language: en-US https://google.com

上面命令添加 HTTP 标头Accept-Language: en-US。

$ curl -H Accept-Language: en-US -H Secret-Message: xyzzy https://google.com

上面命令添加两个 HTTP 标头。

$ curl -d {"login": "emma", "pass": "123"} -H Content-Type: application/json https://google.com/login

上面命令添加 HTTP 请求的标头是Content-Type: application/json,然后用-d参数发送 JSON 数据。

-i 选项:

-i参数打印出服务器回应的 HTTP 标头。

$ curl -i https://www.example.com

上面命令收到服务器回应后,先输出服务器回应的标头,然后空一行,再输出网页的源码。

-I 选项:

-I参数向服务器发出 HEAD 请求,然会将服务器返回的 HTTP 标头打印出来。

$ curl -I https://www.example.com

上面命令输出服务器对 HEAD 请求的回应。

--head参数等同于-I。

$ curl --head https://www.example.com

-k 参数:

-k参数指定跳过 SSL 检测。

$ curl -k https://www.example.com

上面命令不会检查服务器的 SSL 证书是否正确。

-L 参数:

-L参数会让 HTTP 请求跟随服务器的重定向。curl 默认不跟随重定向。

$ curl -L -d tweet=hi https://api.twitter.com/tweet

--limit-rate 选项:

--limit-rate用来限制 HTTP 请求和回应的带宽,模拟慢网速的环境。

$ curl --limit-rate 200k

上面命令将带宽限制在每秒 200K 字节。

-o 选项:

-o参数将服务器的回应保存成文件,等同于wget命令。

$ curl -o example.html https://www.example.com

上面命令将www.example.com保存成example.html。

-O 选项:

-O参数将服务器回应保存成文件,并将 URL 的最后部分当作文件名。

$ curl -O https://www.example.com/foo/bar.html

上面命令将服务器回应保存成文件,文件名为bar.html。

-s 选项:

-s参数将不输出错误和进度信息。

$ curl -s https://www.example.com

上面命令一旦发生错误,不会显示错误信息。不发生错误的话,会正常显示运行结果。

如果想让 curl 不产生任何输出,可以使用下面的命令。

$ curl -s -o /dev/null https://google.com

-S 选项:

-S参数指定只输出错误信息,通常与-s一起使用。

$ curl -s -o /dev/null https://google.com

上面命令没有任何输出,除非发生错误。

-u 选项:

-u参数用来设置服务器认证的用户名和密码。

$ curl -u bob:12345 https://google.com/login

上面命令设置用户名为bob,密码为12345,然后将其转为 HTTP 标头Authorization: Basic Ym9iOjEyMzQ1。

curl 能够识别 URL 里面的用户名和密码。

$ curl https://bob:[email protected]/login

上面命令能够识别 URL 里面的用户名和密码,将其转为上个例子里面的 HTTP 标头。

$ curl -u bob https://google.com/login

上面命令只设置了用户名,执行后,curl 会提示用户输入密码。

-v 选项:

-v参数输出通信的整个过程,用于调试。

$ curl -v https://www.example.com

--trace参数也可以用于调试,还会输出原始的二进制数据。

$ curl --trace - https://www.example.com

-x 选项:

-x参数指定 HTTP 请求的代理。

$ curl -x socks5://james:[email protected]:8080 https://www.example.com

上面命令指定 HTTP 请求通过myproxy.com:8080的 socks5 代理发出。

如果没有指定代理协议,默认为 HTTP。

$ curl -x james:[email protected]:8080 https://www.example.com

上面命令中,请求的代理使用 HTTP 协议。

-X 选项:

-X参数指定 HTTP 请求的方法。

$ curl -X POST https://www.example.com

上面命令对发出 POST 请求。

参考作者:阮一峰的日志

地址链接: