一、curl命令作用
curl命令是一个利用URL规则在命令行下工作的文件传输工具。它支持文件的上传和下载,所以是综合传输工具,但按传统,习惯称curl为下载工具。作为一款强力工具,curl支持包括HTTP、HTTPS、ftp等众多协议,还支持POST、cookies、认证、从指定偏移处下载部分文件、用户代理字符串、限速、文件大小、进度条等特征。做网页处理流程和数据检索自动化,curl可以祝一臂之力。
帮助文档:
Usage: curl [options...] <url> 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 FILE CA certificate to verify peer against (SSL) --capath DIR CA 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 LIST SSL ciphers to use (SSL) --compressed Request compressed response (using deflate or gzip) -K, --config FILE Specify which config file to read --connect-timeout SECONDS Maximum time allowed for connection -C, --continue-at OFFSET Resumed transfer offset -b, --cookie STRING/FILE String or file to read cookies from (H) -c, --cookie-jar FILE Write cookies to this file after operation (H) --create-dirs Create necessary local directory hierarchy --crlf Convert LF to CRLF in upload --crlfile FILE Get a CRL list in PEM format from the given file -d, --data DATA HTTP POST data (H) --data-ascii DATA HTTP POST ASCII data (H) --data-binary DATA HTTP POST binary data (H) --data-urlencode DATA 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 FILE Write the headers to this file --egd-file FILE EGD socket path for random data (SSL) --engine ENGINGE Crypto engine (SSL). "--engine list" for list -f, --fail Fail silently (no output at all) on HTTP errors (H) -F, --form CONTENT Specify HTTP multipart POST data (H) --form-string STRING Specify HTTP multipart POST data (H) --ftp-account DATA Account data string (F) --ftp-alternative-to-user COMMAND 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 ADR Use PORT with given address instead of PASV (F) --ftp-skip-pasv-ip Skip the IP address for PASV (F) --ftp-pret Send PRET before PASV (for drftpd) (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) -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, --head Show document info only -h, --help This help text --hostpubmd5 MD5 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 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 SECONDS Interval 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 FILE Dump libcurl equivalent code of this command line --limit-rate RATE Limit transfer speed to this rate -l, --list-only List only names of an FTP directory (F) --local-port RANGE Force use of these local port numbers -L, --location Follow redirects (H) --location-trusted like --location and send auth to other hosts (H) -M, --manual Display the full manual --mail-from FROM Mail from this address --mail-rcpt TO Mail to this receiver(s) --mail-auth AUTH Originator address of the original email --max-filesize BYTES Maximum file size to download (H/F) --max-redirs NUM Maximum number of redirects allowed (H) -m, --max-time SECONDS Maximum time allowed for the transfer --metalink Process 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 FILE Set up the netrc filename to use -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 List of hosts which do not use proxy --ntlm Use 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-bar Display transfer progress as a progress bar --proto PROTOCOLS Enable/disable specified protocols --proto-redir PROTOCOLS Enable/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-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 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 KEY Public key file name (SSH) -Q, --quote CMD Send command(s) to server before transfer (F/SFTP) --random-file FILE File 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 file's time on the local output -X, --request COMMAND Specify request command to use --resolve HOST:PORT:ADDRESS Force 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 SECONDS 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 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-hostname HOST[:PORT] SOCKS5 proxy, pass host name to proxy --socks5-gssapi-service NAME SOCKS5 proxy service name for gssapi --socks5-gssapi-nec Compatibility with NEC SOCKS5 server -Y, --speed-limit RATE Stop transfers below speed-limit for 'speed-time' secs -y, --speed-time SECONDS Time for trig speed-limit abort. Defaults to 30 --ssl Try SSL/TLS (FTP, IMAP, POP3, SMTP) --ssl-reqd Require 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=VAL Set telnet option --tftp-blksize VALUE Set TFTP BLKSIZE option (must be >512) -z, --time-cond TIME 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 FILE Write a debug trace to the given file --trace-ascii FILE Like --trace but without the hex output --trace-time Add time stamps to trace/verbose output --tr-encoding Request compressed transfer encoding (H) -T, --upload-file FILE Transfer 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 USER TLS username --tlspassword STRING TLS password --tlsauthtype STRING TLS authentication type (default SRP) --unix-socket FILE Connect through this UNIX domain socket -A, --user-agent STRING User-Agent to send to server (H) -v, --verbose Make the operation more talkative -V, --version Show version number and quit -w, --write-out FORMAT What to output after completion --xattr Store metadata in extended file attributes -q If used as the first parameter disables .curlrc
常用参数
curl命令参数很多,这里只列出常用、特别是在shell脚本中经常用到过的那些。
-a/--append 上传文件时,附加到目标文件
-A:随意指定自己这次访问所宣称的自己的浏览器信息
-b/--cookie <name=string/file> cookie字符串或文件读取位置,使用option来把上次的cookie信息追加到http request里面去。
-c/--cookie-jar <file> 操作结束后把cookie写入到这个文件中
-C/--continue-at <offset> 断点续转
-d/--data <data> HTTP POST方式传送数据
--data-ascii <data> | 以ascii的方式post数据 |
--data-binary <data> | 以二进制的方式post数据 |
--negotiate | 使用HTTP身份验证 |
--digest | 使用数字身份验证 |
--disable-eprt | 禁止使用EPRT或LPRT |
--disable-epsv | 禁止使用EPSV |
-D/--dump-header <file> 把header信息写入到该文件中
--egd-file <file> 为随机数据(SSL)设置EGD socket路径
--tcp-nodelay 使用TCP_NODELAY选项
-e/--referer <URL> 指定引用地址
-F/--form <name=content> 模拟http表单提交数据
--form-string <name=string> 模拟http表单提交数据
-G/--get 以get的方式来发送数据
-H/--header <header> 指定请求头参数
--ignore-content-length 忽略的HTTP头信息的长度
-i/--include 输出时包括protocol头信息
-I/--head 仅返回头部信息,使用HEAD请求
-k/--insecure 允许不使用证书到SSL站点
-K/--config 指定的配置文件读取
-l/--list-only 列出ftp目录下的文件名称
--limit-rate <rate> 设置传输速度
--local-port<NUM> 强制使用本地端口号
-m/--max-time <seconds> 指定处理的最大时长
--max-redirs <num> 设置最大读取的目录数
--max-filesize <bytes> 设置最大下载的文件总量
-o/--output <file> 指定输出文件名称
-O/--remote-name 把输出写到该文件中,保留远程文件的文件名
-v/--verbose 小写的v参数,用于打印更多信息,包括发送的请求信息,这在调试脚本是特别有用。
-s/--slient 减少输出的信息,比如进度
--connect-timeout <seconds> 指定尝试连接的最大时长
-x/--proxy <proxyhost[:port]> 指定代理服务器地址和端口,端口默认为1080
-u/--user <user[:password]>设置服务器的用户和密码
-r/--range <range>检索来自HTTP/1.1或FTP服务器字节范围
--range-file 读取(SSL)的随机文件
-R/--remote-time 在本地生成文件时,保留远程文件时间
--retry <num> 指定重试次数
--retry-delay <seconds> 传输出现问题时,设置重试间隔时间
--retry-max-time <seconds> 传输出现问题时,设置最大重试时间
-s/--silent 静默模式。不输出任何东西
-S/--show-error 显示错误
--socks4 <host[:port]> 用socks4代理给定主机和端口
--socks5 <host[:port]> 用socks5代理给定主机和端口
--stderr <file>
-x/--proxy <host[:port]> 在给定的端口上使用HTTP代理
-X/--request <command> 指定什么命令。curl默认的HTTP动词是GET,使用-X参数可以支持其他动词。
-T/--upload-file <file> 指定上传文件路径
二、使用实例
1、抓取cokkie信息到一个文件中
curl -c cookie0.txt -d "username=****&password=***" http://www.kuaipan.cn/accounts/login/
2、get方法获取信息
curl -G -I -o xsrf.txt -b cookie1.txt -c cookie2.txt http://web.kuaipan.cn/n/drive/home.tmpl/upload
curl http://www.xxxx.com/show?userId=111
curl -X GET "http://www.xxxx.com/show?userId=111"
POST请求
以application/x-www-url-encoded 方式发送数据(-d/--data):
curl -d "username=sunnyxd&password=12345" URL
curl -X POST -d "module_name=${module_name}" URL --user jenkins:abc
3、文件下载
可以用来执行下载、发送各种HTTP请求,指定HTTP头部等操作。如果系统没有curl可以使用yum install curl安装,也可以下载安装。curl是将下载文件输出到stdout,将进度信息输出到stderr,不显示进度信息使用--silent选项。
curl URL --silent
这条命令是将下载文件输出到终端,所有下载的数据都被写入到stdout。 使用选项-O将下载的数据写入到文件,必须使用文件的绝对地址:
curl http://man.linuxde.net/text.iso --silent -O
$ curl -o Template_App_MySQL-2.2.0.xml https://zabbix.org/mw/images/d/d4/Template_App_MySQL-2.2.0.xml
4、断点续传
5、使用curl设置参照页字符串
6、用curl设置用户代理字符串
7、curl的带宽控制和下载配额
8、用curl进行认证
9、只打印响应头部信息
10、抓取页面
例1:抓取页面保存到test.html:
curl -o test.html URL 或者curl URL > test.html
-O 下载特定文件,url需要指定到一个具体的文件 -C - 断点续传,- 自动推断出正确的续传位置,或者直接指定相应的字节偏移 -f 显示抓取错误信息 -x ip:port 使用代理 -s 不显示进度信息 -e/--referer 伪造来源地址 --limit-rate 50k 限制下载速度 --max-filesize bytes 指定可下载的最大文件大小
例2:获取指定内容
http://127.0.0.1/NginxStatus页面显示如下:
Active connections: 54
server accepts handled requests
60085 60085 175930
Reading: 0 Writing: 1 Waiting: 53
# curl http://127.0.0.1/NginxStatus | grep Active 获取到包含有 Active 字样的内容:
Active connections: 54
# curl http://127.0.0.1/NginxStatus |grep Active |awk '{print $3 }' 这样获取到内容中第三列的内容。
即纯数值 :54
#用于提取status中的active数值也可用:
/usr/bin/curl http://$ip/nginx_status 2>/dev/null | sed -n '1p' | awk '{print $NF}'
#用于提取status中的accepts数值:
/usr/bin/curl http://$ip/nginx_status 2>/dev/null | sed -n '3p' | awk '{print $1}'
#用于提取status中的reading数值:
/usr/bin/curl http://$ip/nginx_status 2>/dev/null | sed -n '4p' | awk '{print $2}'
实例:
1、获取公网ip
curl ip.cn
2、执行指定ip的批处理任务
curl http://127.0.0.1:8151/job/total
curl -H "Content-Type:application/json" -X POST ST https://webapi.ming.com/common/public_info | j | jq -r
3、安装Arthas:
curl -L https://alibaba.github.io/arthas/install.sh | sh
参考资料: