IT备忘录

您现在的位置是:首页 > 教程 > 编程开发

编程开发

curl命令怎么用 curl常用命令及参数详解

2022-08-09 11:03:04编程开发
cURL命令怎么用?初学者往往对cURL命令参数不熟悉,下面IT备忘录小编就给大家收集整理了一份比较齐全的cURL命令参数/选项大全,帮助各位快速熟悉入门。cURL命令是一个利用URL规则

cURL命令怎么用?初学者往往对cURL命令参数不熟悉,下面IT备忘录小编就给大家收集整理了一份比较齐全的cURL命令参数/选项大全,帮助各位快速熟悉入门。

curl命令怎么用 curl常用命令及参数详解

cURL命令是一个利用URL规则在命令行下工作的文件传输工具。它支持文件的上传和下载,所以是综合传输工具。作为一款强力工具,cURL支持包括HTTP、HTTPS、ftp等众多协议,还支持POST、cookies、认证、从指定偏移处下载部分文件、用户代理字符串、限速、文件大小、进度条等特征。做网页处理流程和数据检索自动化,cURL可以祝一臂之力。

cURL命令语法格式:

curl(选项)(参数)

cURL命令选项/参数详解

-a/--append 上传文件时,附加到目标文件
-A/--user-agent <string> 设置用户代理发送给服务器
-anyauth 可以使用“任何”身份验证方法
-b/--cookie <name=string/file> cookie字符串或文件读取位置
     --basic 使用HTTP基本验证
-B/--use-ascii 使用ASCII /文本传输
-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 来源网址
-E/--cert <cert[:passwd]> 客户端证书文件和密码 (SSL)
     --cert-type <type> 证书文件类型 (DER/PEM/ENG) (SSL)
     --key <key> 私钥文件名 (SSL)
     --key-type <type> 私钥文件类型 (DER/PEM/ENG) (SSL)
     --pass <pass> 私钥密码 (SSL)
     --engine <eng> 加密引擎使用 (SSL). "--engine list" for list
     --cacert <file> CA证书 (SSL)
     --capath <directory> CA目录 (made using c_rehash) to verify peer against (SSL)
     --ciphers <list> SSL密码
     --compressed 要求返回是压缩的形势 (using deflate or gzip)
     --connect-timeout <seconds> 设置最大请求时间
     --create-dirs 建立本地目录的目录层次结构
     --crlf 上传是把LF转变成CRLF
-f/--fail 连接失败时不显示http错误
     --ftp-create-dirs 如果远程目录不存在,创建远程目录
     --ftp-method [multicwd/nocwd/singlecwd] 控制CWD的使用
     --ftp-pasv 使用 PASV/EPSV 代替端口
     --ftp-skip-pasv-ip 使用PASV的时候,忽略该IP地址
     --ftp-ssl 尝试用 SSL/TLS 来进行ftp数据传输
     --ftp-ssl-reqd 要求用 SSL/TLS 来进行ftp数据传输
-F/--form <name=content> 模拟http表单提交数据
     --form-string <name=string> 模拟http表单提交数据
-g/--globoff 禁用网址序列和范围使用{}和[]
-G/--get 以get的方式来发送数据
-H/--header <line> 自定义头信息传递给服务器
     --ignore-content-length 忽略的HTTP头信息的长度
-i/--include 输出时包括protocol头信息
-I/--head 只显示请求头信息
-j/--junk-session-cookies 读取文件进忽略session cookie
     --interface <interface> 使用指定网络接口/地址
     --krb4 <level> 使用指定安全级别的krb4
-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> 设置最大下载的文件总量
-M/--manual 显示全手动
-n/--netrc 从netrc文件中读取用户名和密码
     --netrc-optional 使用 .netrc 或者 URL来覆盖-n
     --ntlm 使用 HTTP NTLM 身份验证
-N/--no-buffer 禁用缓冲输出
-o/--output 把输出写到该文件中
-O/--remote-name 把输出写到该文件中,保留远程文件的文件名
-p/--proxytunnel 使用HTTP代理
     --proxy-anyauth 选择任一代理身份验证方法
     --proxy-basic 在代理上使用基本身份验证
     --proxy-digest 在代理上使用数字身份验证
     --proxy-ntlm 在代理上使用ntlm身份验证
-P/--ftp-port <address> 使用端口地址,而不是使用PASV
-q 作为第一个参数,关闭 .curlrc
-Q/--quote <cmd> 文件传输前,发送命令到服务器
-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>  
-t/--telnet-option <OPT=val> Telnet选项设置
     --trace <file> 对指定文件进行debug
     --trace-ascii <file> Like --跟踪但没有hex输出
     --trace-time 跟踪/详细输出时,添加时间戳
-T/--upload-file <file> 上传文件
     --url <URL> Spet URL to work with
-u/--user <user[:password]> 设置服务器的用户和密码
-U/--proxy-user <user[:password]> 设置代理用户名和密码
-w/--write-out [format] 什么输出完成后
-x/--proxy <host[:port]> 在给定的端口上使用HTTP代理
-X/--request <command> 指定什么命令
-y/--speed-time 放弃限速所要的时间,默认为30
-Y/--speed-limit 停止传输速度的限制,速度时间

cURL实例教程举例:

文件下载

curl命令可以用来执行下载、发送各种HTTP请求,指定HTTP头部等操作。如果系统没有curl:

Linux系统可以使用yum install curl安装,也可以自己去官网下载编译安装。

Windows系统cURL安装方法

方法1:curl环境变量配置

方法2:直接将下载的bin目录下的文件解压至:c:\windows\system32目录

curl是将下载文件输出到stdout,将进度信息输出到stderr,不显示进度信息使用--silent选项。

curl URL --silent

这条命令是将下载文件输出到终端,所有下载的数据都被写入到stdout。

使用选项-O将下载的数据写入到文件,必须使用文件的绝对地址:

curl https://www.itmemo.cn/sitemap.txt --silent -O

选项-o将下载数据写入到指定名称的文件中,并使用--progress显示进度条:

curl https://www.itmemo.cn/sitemap.txt -o filename.txt --progress
######################################### 100.0%

温馨提示:在windows系统中若不指定文件下载的绝对路径,默认会下载到用户文件夹下,比如:Administrator文件夹中,貌似加:--progress参数有问题,遇到这种情况请不加该参数。

断点续传

curl能够从特定的文件偏移处继续下载,它可以通过指定一个便宜量来下载部分文件:

curl URL/File -C 偏移量

#偏移量是以字节为单位的整数,如果让curl自动推断出正确的续传位置使用-C -:

curl -C -URL

使用curl设置参照页字符串

参照页是位于HTTP头部中的一个字符串,用来表示用户是从哪个页面到达当前页面的,如果用户点击网页A中的某个连接,那么用户就会跳转到B网页,网页B头部的参照页字符串就包含网页A的URL。

使用--referer选项指定参照页字符串:

curl --referer http://www.google.com https://www.itmemo.cn/

用curl设置cookies

使用--cookie "COKKIES"选项来指定cookie,多个cookie使用分号分隔:

curl https://www.itmemo.cn/ --cookie "user=root;pass=123456"

将cookie另存为一个文件,使用--cookie-jar选项:

curl URL --cookie-jar cookie_file

用curl设置用户代理字符串

有些网站访问会提示只能使用IE浏览器来访问,这是因为这些网站设置了检查用户代理,可以使用curl把用户代理设置为IE,这样就可以访问了。使用--user-agent或者-A选项:

curl URL --user-agent "Mozilla/5.0"
curl URL -A "Mozilla/5.0"

其他HTTP头部信息也可以使用curl来发送,使用-H"头部信息" 传递多个头部信息,例如:

curl -H "Host:www.itmemo.cn" -H "accept-language:zh-cn" URL

curl的带宽控制和下载配额

使用--limit-rate限制curl的下载速度:

curl URL --limit-rate 50k

命令中用k(千字节)和m(兆字节)指定下载速度限制。

使用--max-filesize指定可下载的最大文件大小:

curl URL --max-filesize bytes

如果文件大小超出限制,命令则返回一个非0退出码,如果命令正常则返回0。

用curl进行认证

使用curl选项 -u 可以完成HTTP或者FTP的认证,可以指定密码,也可以不指定密码在后续操作中输入密码:

curl -u user:pwd https://www.itmemo.cn/
curl -u user https://www.itmemo.cn/

只打印响应头部信息

通过-I或者-head可以只打印出HTTP头部信息:

curl -I https://www.itmemo.cn/

HTTP/1.1 200 OK
Server: nginx
Date: Tue, 09 Aug 2022 02:59:38 GMT
Content-Type: text/html
Content-Length: 62774
Last-Modified: Tue, 09 Aug 2022 02:01:21 GMT
Connection: keep-alive
Vary: Accept-Encoding
ETag: "62f1bff1-f536"
Accept-Ranges: bytes

以下是官方翻译过来的cURL简易教程

从网络服务器获取主页:

curl https://www.itmemo.cn/

在 funet 的 ftp-server 上获取用户主目录的 README 文件:

curl ftp://ftp.funet.fi/README

使用端口 8000 从服务器获取网页:

curl http://www.weirdserver.com:8000/

获取 FTP 站点的目录列表:

curl ftp://ftp.funet.fi

从字典中获取 curl 的定义:

curl dict://dict.org/m:curl

一次获取两个文档:

curl ftp://ftp.funet.fi/ http://www.weirdserver.com:8000/

从 FTPS 服务器获取文件:

curl ftps://files.are.secure.com/secrets.txt

或者使用更合适的 FTPS 方式来获取相同的文件:

curl --ftp-ssl ftp://files.are.secure.com/secrets.txt

使用 SFTP 从 SSH 服务器获取文件:

curl -u username sftp://example.com/etc/issue

使用 SCP 使用私钥(不受密码保护)从 SSH 服务器获取文件以进行身份​​验证:

curl -u username: --key ~/.ssh/id_rsa scp://example.com/~/file.txt

使用 SCP 使用私钥(受密码保护)从 SSH 服务器获取文件以进行身份​​验证:

curl -u username: --key ~/.ssh/id_rsa --pass private_key_password
scp://example.com/~/file.txt

从 IPv6 Web 服务器获取主页:

curl "http://[2001:1890:1112:1::20]/"

从 SMB 服务器获取文件:

curl -u "domain\username:passwd" smb://server.example.com/share/file.txt

下载到文件

获取网页并存储在具有特定名称的本地文件中:

curl -o thatpage.html http://www.example.com/

获取网页并存储在本地文件中,使本地文件获取远程文档的名称(如果URL中没有指定文件名部分,则会失败):

curl -O http://www.example.com/index.html

获取两个文件并使用它们的远程名称存储它们:

curl -O www.haxx.se/index.html -O curl.se/download.html

使用密码

FTP

要使用名称+密码 ftp 文件,请将它们包含在 URL 中,例如:

curl ftp://name:passwd@machine.domain:port/full/path/to/file

或使用 -u 标志指定它们,例如

curl -u name:passwd ftp://machine.domain:port/full/path/to/file

FTPS

就像 FTP 一样,但您可能还想为证书等指定和使用特定于 SSL 的选项。

请注意,使用FTPS://as 前缀是标准中描述的“隐式”方式,而推荐的“显式”方式是通过使用 FTP:// 和--ftp-ssl选项来完成的。

SFTP / SCP

这类似于 FTP,但您可以使用该--key选项指定要使用的私钥而不是密码。请注意,私钥本身可能受与远程系统登录密码无关的密码保护;此密码是使用--pass选项指定的。通常,curl 会自动从私钥文件中提取公钥,但如果 curl 没有适当的库支持,则必须使用该--pubkey选项指定匹配的公钥文件。

HTTP

Curl 还支持 HTTP URL 中的用户名和密码,因此您可以选择如下文件:

curl http://name:passwd@machine.domain/full/path/to/file

或单独指定用户和密码,如

curl -u name:passwd http://machine.domain/full/path/to/file

HTTP 提供了许多不同的身份验证方法,curl 支持以下几种:Basic、Digest、NTLM 和 Negotiate (SPNEGO)。在不告诉使用哪种方法的情况下,curl 默认为 Basic。您还可以使用--anyauth.

注意!根据 URL 规范,HTTP URL 不能包含用户和密码,因此当通过代理使用 curl 时,该样式将不起作用,即使 curl 在其他时候允许它。使用代理时,您必须使用-u用户名和密码的样式。

HTTPS

可能最常用于私有证书,如下所述。

代理人

curl 支持 HTTP 和 SOCKS 代理服务器,具有可选的身份验证。它没有对 FTP 代理服务器的特殊支持,因为它们没有标准,但它仍然可以与其中的许多服务器一起工作。您还可以使用 HTTP 和 SOCKS 代理在 FTP 服务器之间传输文件。

使用名为 my-proxy 且使用端口 888 的 HTTP 代理获取 ftp 文件:

curl -x my-proxy:888 ftp://ftp.leachsite.com/README

使用与上述相同的代理从需要用户和密码的 HTTP 服务器获取文件:

curl -u user:passwd -x my-proxy:888 http://www.get.this/

某些代理需要特殊身份验证。如上所述使用 -U 指定:

curl -U user:passwd -x my-proxy:888 http://www.get.this/

可以将不使用代理的主机和域的逗号分隔列表指定为:

curl --noproxy localhost,get.this -x my-proxy:888 http://www.get.this/

--proxy1.0如果使用而不是--proxyor指定代理-x,则 curl 将使用 HTTP/1.0 而不是 HTTP/1.1 进行任何CONNECT尝试。

--socks4curl 还支持带有和的SOCKS4 和 SOCKS5 代理--socks5。

另请参阅 Curl 支持的提供进一步代理控制的环境变量。

大多数 FTP 代理服务器被设置为从客户端的角度来看是一个普通的 FTP 服务器,并带有特殊的命令来选择远程 FTP 服务器。curl 支持-u,-Q和--ftp-account可用于通过许多 FTP 代理设置传输的选项。例如,可以使用带有以下选项的 Blue Coat FTP 代理将文件上传到远程 FTP 服务器:

curl -u "username@ftp.server Proxy-Username:Remote-Pass"
  --ftp-account Proxy-Password --upload-file local-file
  ftp://my-ftp.proxy.server:21/remote/upload/path/

请参阅您的 FTP 代理的手册以确定它期望设置传输的形式,并查看 curl 的-v选项以准确查看 curl 发送的内容。

范围

HTTP 1.1 引入了字节范围。使用它,客户端可以请求仅获取指定文档的一个或多个子部分。Curl 用-r标志支持这一点。

获取文档的前 100 个字节:

curl -r 0-99 http://www.get.this/

获取文档的最后 500 个字节:

curl -r -500 http://www.get.this/

Curl 还支持 FTP 文件的简单范围。然后您只能指定开始和停止位置。

使用 FTP 获取文档的前 100 个字节:

curl -r 0-99 ftp://www.get.this/README

上传

FTP / FTPS / SFTP / SCP

将 stdin 上的所有数据上传到指定服务器:

curl -T - ftp://ftp.upload.com/myfile

从指定文件上传数据,使用用户名和密码登录:

curl -T uploadfile -u user:passwd ftp://ftp.upload.com/myfile

将本地文件上传到远程站点,并在远程站点也使用本地文件名:

curl -T uploadfile -u user:passwd ftp://ftp.upload.com/

上传本地文件以附加到远程文件:

curl -T localfile -a ftp://ftp.upload.com/remotefile

Curl 还支持通过代理进行 ftp 上传,但前提是代理配置为允许这种隧道。如果是这样,您可以以类似于以下方式运行 curl:

curl --proxytunnel -x proxy:port -T localfile ftp.upload.com

中小企业/中小企业

curl -T file.txt -u "domain\username:passwd"
  smb://server.example.com/share/

HTTP

将 stdin 上的所有数据上传到指定的 HTTP 站点:

curl -T - http://www.upload.com/myfile

请注意,必须先将 HTTP 服务器配置为接受 PUT,然后才能成功完成此操作。

有关进行 HTTP 数据上传的其他方法,请参阅下面的 POST 部分。

详细/调试

如果 curl 在不应该出现的地方失败,如果服务器不让你进入,如果你无法理解响应:使用-v标志来获取详细的获取。Curl 将输出大量信息以及它发送和接收的内容,以便让用户看到所有客户端-服务器交互(但它不会向您显示实际数据)。

curl -v ftp://ftp.upload.com/

要获取有关 curl 功能的更多详细信息和信息,请尝试使用具有给定文件名的--traceor--trace-ascii选项来登录,如下所示:

curl --trace trace.txt www.haxx.se

详细资料

不同的协议提供了不同的方式来获取有关特定文件/文档的详细信息。要让 curl 显示有关单个文件的详细信息,您应该使用-I/--head选项。它显示 HTTP 和 FTP 的单个文件上的所有可用信息。HTTP 信息要广泛得多。

对于 HTTP,您可以使用/获取-I显示在数据之前的标头信息(与将显示的相同) 。当从 FTP 和 HTTP 获取文件时, Curl 理解/选项,然后它将标头存储在指定的文件中。-i--include-D--dump-header

将 HTTP 标头存储在单独的文件中(示例中为 headers.txt):

  curl --dump-header headers.txt curl.se
请注意,如果您希望 curl 使用服务器发送的 cookie,则存储在单独文件中的标头在以后会很有用。更多关于 cookie 部分的信息。

发布 (HTTP)

使用 curl 发布数据很容易。这是使用-d <data>选项完成的。帖子数据必须是 urlencoded。

发布一个简单的“姓名”和“电话”留言簿。

curl -d "name=Rafael%20Sagula&phone=3320780" http://www.where.com/guest.cgi

如何使用 curl 发布表单,第 1 课:

挖掘出<input>您要填写的表单中的所有标签。

如果有一个“正常”的帖子,你-d就用来发帖。-d采用完整的“帖子字符串”,格式为

<variable1>=<data1>&<variable2>=<data2>&...
“变量”名称是标签中设置的名称"name=",<input>数据是您要为输入填写的内容。数据必须经过正确的 URL 编码。这意味着你用 + 替换空格,用 %XX 替换奇怪的字母,其中 XX 是字母 ASCII 代码的十六进制表示。

例子:

(页面位于http://www.formpost.com/getthis/)

<form action="post.cgi" method="post">
<input name=user size=10>
<input name=pass type=password size=10>
<input name=id type=hidden value="blablabla">
<input name=ding value="submit">
</form>
我们想输入用户 'foobar' 和密码 '12345'。

要发布到此,您输入 curl 命令行,如:

curl -d "user=foobar&pass=12345&id=blablabla&ding=submit"
  http://www.formpost.com/getthis/post.cgi
虽然-d使用 application/x-www-form-urlencoded mime-type,通常被 CGI 和类似理解,curl 还支持更强大的 multipart/form-data 类型。后一种类型支持文件上传之类的东西。

-F接受参数,如-F "name=contents". 如果要从文件中读取内容,请使用@filenameas contents。指定文件时,还可以通过附加;type=<mime type>到文件名来指定文件内容类型。您还可以在一个字段中发布多个文件的内容。例如,字段名称 'coolfiles' 用于发送三个具有不同内容类型的文件,使用以下语法:

curl -F "coolfiles=@fil1.gif;type=image/gif,fil2.txt,fil3.html"
  http://www.post.com/postit.cgi
如果没有指定 content-type,curl 将尝试从文件扩展名中猜测(它只知道几个),或者使用先前指定的类型(如果在列表中指定了多个文件,则从较早的文件中),否则它将使用默认类型“application/octet-stream”。

用 模拟填写表格-F。假设您在表单中填写了三个字段。一个字段是要发布的文件名,一个字段是您的姓名,一个字段是文件描述。我们要发布我们编写的名为“cooltext.txt”的文件。要让 curl 代替您喜欢的浏览器发布这些数据,您必须阅读表单页面的 HTML 源代码并找到输入字段的名称。在我们的示例中,输入字段名称是“file”、“yourname”和“filedescription”。

curl -F "file=@cooltext.txt" -F "yourname=Daniel"
  -F "filedescription=Cool text file with cool text inside"
  http://www.post.com/postit.cgi
要在一篇文章中发送两个文件,您可以通过两种方式进行:

使用单个字段名称在单个“字段”中发送多个文件:

curl -F "pictures=@dog.gif,cat.gif" $URL
发送具有两个字段名称的两个字段

curl -F "docpicture=@dog.gif" -F "catpicture=@cat.gif" $URL

@要在不解释前导or<或嵌入的情况下按字面意思发送字段值;type=,请使用--form-string代替-F。当值是从用户或其他不可预测的来源获得时,建议这样做。在这些情况下,使用-F而不是--form-string可能允许用户欺骗 curl 上传文件。

推荐人

HTTP 请求可以选择包含有关哪个地址将其引用到实际页面的信息。curl 允许您指定要在命令行上使用的引荐来源网址。欺骗或欺骗依赖可用信息或包含某些数据的愚蠢服务器或 CGI 脚本特别有用。

curl -e www.coolsite.com http://www.showme.com/

用户代理

An HTTP request has the option to include information about the browser that generated the request. Curl allows it to be specified on the command line. It is especially useful to fool or trick stupid servers or CGI scripts that only accept certain browsers.

Example:

curl -A 'Mozilla/3.0 (Win95; I)' http://www.nationsbank.com/
Other common strings:

Mozilla/3.0 (Win95; I) - Netscape Version 3 for Windows 95
Mozilla/3.04 (Win95; U) - Netscape Version 3 for Windows 95
Mozilla/2.02 (OS/2; U) - Netscape Version 2 for OS/2
Mozilla/4.04 [en] (X11; U; AIX 4.2; Nav) - Netscape for AIX
Mozilla/4.05 [en] (X11; U; Linux 2.0.32 i586) - Netscape for Linux
Note that Internet Explorer tries hard to be compatible in every way:

Mozilla/4.0 (compatible; MSIE 4.01; Windows 95) - MSIE for W95
Mozilla is not the only possible User-Agent name:

Konqueror/1.0 - KDE File Manager desktop client
Lynx/2.7.1 libwww-FM/2.14 - Lynx command line browser
Cookies
Cookies are generally used by web servers to keep state information at the client's side. The server sets cookies by sending a response line in the headers that looks like Set-Cookie: <data> where the data part then typically contains a set of NAME=VALUE pairs (separated by semicolons ; like NAME1=VALUE1; NAME2=VALUE2;). The server can also specify for what path the "cookie" should be used for (by specifying path=value), when the cookie should expire (expire=DATE), for what domain to use it (domain=NAME) and if it should be used on secure connections only (secure).

If you have received a page from a server that contains a header like:

Set-Cookie: sessionid=boo123; path="/foo";
it means the server wants that first pair passed on when we get anything in a path beginning with "/foo".

Example, get a page that wants my name passed in a cookie:

curl -b "name=Daniel" www.sillypage.com

Curl also has the ability to use previously received cookies in following sessions. If you get cookies from a server and store them in a file in a manner similar to:

curl --dump-header headers www.example.com

... you can then in a second connect to that (or another) site, use the cookies from the 'headers' file like:

curl -b headers www.example.com

While saving headers to a file is a working way to store cookies, it is however error-prone and not the preferred way to do this. Instead, make curl save the incoming cookies using the well-known Netscape cookie format like this:

curl -c cookies.txt www.example.com

Note that by specifying -b you enable the "cookie awareness" and with -L you can make curl follow a location: (which often is used in combination with cookies). So that if a site sends cookies and a location, you can use a non-existing file to trigger the cookie awareness like:

curl -L -b empty.txt www.example.com

The file to read cookies from must be formatted using plain HTTP headers OR as Netscape's cookie file. Curl will determine what kind it is based on the file contents. In the above command, curl will parse the header and store the cookies received from www.example.com. curl will send to the server the stored cookies which match the request as it follows the location. The file "empty.txt" may be a nonexistent file.

To read and write cookies from a Netscape cookie file, you can set both -b and -c to use the same file:

curl -b cookies.txt -c cookies.txt www.example.com

Progress Meter
The progress meter exists to show a user that something actually is happening. The different fields in the output have the following meaning:

% Total    % Received % Xferd  Average Speed          Time             Curr.
                               Dload  Upload Total    Current  Left    Speed
0  151M    0 38608    0     0   9406      0  4:41:43  0:00:04  4:41:39  9287
From left-to-right:

% - percentage completed of the whole transfer
Total - total size of the whole expected transfer
% - percentage completed of the download
Received - currently downloaded amount of bytes
% - percentage completed of the upload
Xferd - currently uploaded amount of bytes
Average Speed Dload - the average transfer speed of the download
Average Speed Upload - the average transfer speed of the upload
Time Total - expected time to complete the operation
Time Current - time passed since the invoke
Time Left - expected time left to completion
Curr.Speed - the average transfer speed the last 5 seconds (the first 5 seconds of a transfer is based on less time of course.)
The -# option will display a totally different progress bar that does not need much explanation!

Speed Limit

Curl allows the user to set the transfer speed conditions that must be met to let the transfer keep going. By using the switch -y and -Y you can make curl abort transfers if the transfer speed is below the specified lowest limit for a specified time.

To have curl abort the download if the speed is slower than 3000 bytes per second for 1 minute, run:

curl -Y 3000 -y 60 www.far-away-site.com
This can be used in combination with the overall time limit, so that the above operation must be completed in whole within 30 minutes:

curl -m 1800 -Y 3000 -y 60 www.far-away-site.com
Forcing curl not to transfer data faster than a given rate is also possible, which might be useful if you are using a limited bandwidth connection and you do not want your transfer to use all of it (sometimes referred to as "bandwidth throttle").

Make curl transfer data no faster than 10 kilobytes per second:

curl --limit-rate 10K www.far-away-site.com
or

curl --limit-rate 10240 www.far-away-site.com
Or prevent curl from uploading data faster than 1 megabyte per second:

curl -T upload --limit-rate 1M ftp://uploadshereplease.com
When using the --limit-rate option, the transfer rate is regulated on a per-second basis, which will cause the total transfer speed to become lower than the given number. Sometimes of course substantially lower, if your transfer stalls during periods.

Config File

Curl automatically tries to read the .curlrc file (or _curlrc file on Microsoft Windows systems) from the user's home dir on startup.

The config file could be made up with normal command line switches, but you can also specify the long options without the dashes to make it more readable. You can separate the options and the parameter with spaces, or with = or :. Comments can be used within the file. If the first letter on a line is a #-symbol the rest of the line is treated as a comment.

If you want the parameter to contain spaces, you must enclose the entire parameter within double quotes ("). Within those quotes, you specify a quote as \".

NOTE: You must specify options and their arguments on the same line.

Example, set default time out and proxy in a config file:

# We want a 30 minute timeout:
-m 1800
#. .. and we use a proxy for all accesses:
proxy = proxy.our.domain.com:8080
Whitespaces ARE significant at the end of lines, but all whitespace leading up to the first characters of each line are ignored.

Prevent curl from reading the default file by using -q as the first command line parameter, like:

curl -q www.thatsite.com
Force curl to get and display a local help page in case it is invoked without URL by making a config file similar to:

# default url to get
url = "http://help.with.curl.com/curlhelp.html"
You can specify another config file to be read by using the -K/--config flag. If you set config file name to - it will read the config from stdin, which can be handy if you want to hide options from being visible in process tables etc:

echo "user = user:passwd" | curl -K - http://that.secret.site.com
Extra Headers
When using curl in your own programs, you may end up needing to pass on your own custom headers when getting a web page. You can do this by using the -H flag.

Example, send the header X-you-and-me: yes to the server when getting a page:

curl -H "X-you-and-me: yes" www.love.com

如果您希望 curl 在标题中发送与通常不同的文本,这也很有用。然后,-H您指定的标头将替换 curl 通常会发送的标头。如果将内部标头替换为空标头,则会阻止发送该标头。要防止使用Host:标头:

curl -H "Host:" www.server.com

FTP 和路径名称

请注意,在获取带有ftp://URL 的文件时,给定的路径是相对于您输入的目录的。README要从ftp 站点的主目录中获取文件,请执行以下操作:

curl ftp://user:passwd@my.site.com/README

如果您想要来自同一站点根目录的 README 文件,则需要指定绝对文件名:

curl ftp://user:passwd@my.site.com//README

(即文件名前有一个额外的斜杠。)

SFTP 和 SCP 以及路径名称

对于 sftp: 和 scp: URL,给出的路径名是服务器上的绝对名称。要访问与远程用户的主目录相关的文件,请在文件前面加上/~/,例如:

curl -u $USER sftp://home.example.com/~/.bashrc

FTP 和防火墙

FTP 协议要求相关方之一在数据即将传输时立即打开第二个连接。有两种方法可以做到这一点。

curl 的默认方式是发出 PASV命令,该命令导致服务器打开另一个端口并等待客户端执行的另一个连接。如果客户端位于不允许传入连接的防火墙后面,这很好。

curl ftp.download.com

例如,如果服务器位于防火墙后面,不允许在 21 以外的端口上进行连接(或者如果它只是不支持该PASV命令),则另一种方法是使用该PORT命令并指示服务器进行连接在给定的 IP 号和端口上发送给客户端(作为 PORT 命令的参数)。

curl的-P标志支持几个不同的选项。您的机器可能有多个 IP 地址和/或网络接口,curl 允许您选择使用其中的哪一个。也可以使用默认地址:

curl -P - ftp.download.com
PORT使用但使用我们接口的 IP 地址下载le0(这在 Windows 上不起作用):

curl -P le0 ftp.download.com
下载PORT但使用 192.168.0.10 作为我们使用的 IP 地址:

curl -P 192.168.0.10 ftp.download.com

网络接口

Get a web page from a server using a specified port for the interface:

curl --interface eth0:1 http://www.example.com/
or

curl --interface 192.168.1.10 http://www.example.com/
HTTPS
Secure HTTP requires a TLS library to be installed and used when curl is built. If that is done, curl is capable of retrieving and posting documents using the HTTPS protocol.

Example:

curl https://www.secure-site.com
curl is also capable of using client certificates to get/post files from sites that require valid certificates. The only drawback is that the certificate needs to be in PEM-format. PEM is a standard and open format to store certificates with, but it is not used by the most commonly used browsers. If you want curl to use the certificates you use with your (favourite) browser, you may need to download/compile a converter that can convert your browser's formatted certificates to PEM formatted ones.

Example on how to automatically retrieve a document using a certificate with a personal password:

curl -E /path/to/cert.pem:password https://secure.site.com/
If you neglect to specify the password on the command line, you will be prompted for the correct password before any data can be received.

Many older HTTPS servers have problems with specific SSL or TLS versions, which newer versions of OpenSSL etc use, therefore it is sometimes useful to specify what SSL-version curl should use. Use -3, -2 or -1 to specify that exact SSL version to use (for SSLv3, SSLv2 or TLSv1 respectively):

curl -2 https://secure.site.com/
Otherwise, curl will attempt to use a sensible TLS default version.

Resuming File Transfers
To continue a file transfer where it was previously aborted, curl supports resume on HTTP(S) downloads as well as FTP uploads and downloads.

Continue downloading a document:

curl -C - -o file ftp://ftp.server.com/path/file
Continue uploading a document:

curl -C - -T file ftp://ftp.server.com/path/file
Continue downloading a document from a web server

curl -C - -o file http://www.server.com/
Time Conditions
HTTP allows a client to specify a time condition for the document it requests. It is If-Modified-Since or If-Unmodified-Since. curl allows you to specify them with the -z/--time-cond flag.

For example, you can easily make a download that only gets performed if the remote file is newer than a local copy. It would be made like:

curl -z local.html http://remote.server.com/remote.html
Or you can download a file only if the local file is newer than the remote one. Do this by prepending the date string with a -, as in:

curl -z -local.html http://remote.server.com/remote.html
You can specify a "free text" date as condition. Tell curl to only download the file if it was updated since January 12, 2012:

curl -z "Jan 12 2012" http://remote.server.com/remote.html
Curl will then accept a wide range of date formats. You always make the date check the other way around by prepending it with a dash (-).

DICT
For fun try

curl dict://dict.org/m:curl
curl dict://dict.org/d:heisenbug:jargon
curl dict://dict.org/d:daniel:gcide
Aliases for 'm' are 'match' and 'find', and aliases for 'd' are 'define' and 'lookup'. For example,

curl dict://dict.org/find:curl
Commands that break the URL description of the RFC (but not the DICT protocol) are

curl dict://dict.org/show:db
curl dict://dict.org/show:strat
Authentication support is still missing

LDAP

If you have installed the OpenLDAP library, curl can take advantage of it and offer ldap:// support. On Windows, curl will use WinLDAP from Platform SDK by default.

Default protocol version used by curl is LDAPv3. LDAPv2 will be used as a fallback mechanism in case LDAPv3 fails to connect.

LDAP is a complex thing and writing an LDAP query is not an easy task. I do advise you to dig up the syntax description for that elsewhere. One such place might be: RFC 2255, The LDAP URL Format

To show you an example, this is how I can get all people from my local LDAP server that has a certain sub-domain in their email address:

curl -B "ldap://ldap.frontec.se/o=frontec??sub?mail=*sth.frontec.se"
If I want the same info in HTML format, I can get it by not using the -B (enforce ASCII) flag.

You also can use authentication when accessing LDAP catalog:

curl -u user:passwd "ldap://ldap.frontec.se/o=frontec??sub?mail=*"
curl "ldap://user:passwd@ldap.frontec.se/o=frontec??sub?mail=*"
By default, if user and password are provided, OpenLDAP/WinLDAP will use basic authentication. On Windows you can control this behavior by providing one of --basic, --ntlm or --digest option in curl command line

curl --ntlm "ldap://user:passwd@ldap.frontec.se/o=frontec??sub?mail=*"
On Windows, if no user/password specified, auto-negotiation mechanism will be used with current logon credentials (SSPI/SPNEGO).

Environment Variables
Curl reads and understands the following environment variables:

http_proxy, HTTPS_PROXY, FTP_PROXY
They should be set for protocol-specific proxies. General proxy should be set with

ALL_PROXY

设置了不应通过任何代理的主机名的逗号分隔列表(只有星号,*匹配所有主机)

NO_PROXY

如果主机名与这些字符串之一匹配,或者主机位于这些字符串之一的域内,则不会代理与该节点的事务。使用域时,需要以句点开头。用户可以通过设置为来指定www.example.com和 foo.example.com 都不应使用代理。通过包含全名,您可以排除特定的主机名,因此要不使用代理但仍然可以使用,请设置为.NO_PROXY.example.comwww.example.comfoo.example.comNO_PROXYwww.example.com

-x/标志的使用--proxy会覆盖环境变量。

网路

Unix.netrc很久以前就引入了这个概念。这是用户在文件中为经常访问的 FTP 站点指定名称和密码的一种方式,这样您就不必在每次访问这些站点时都输入它们。您意识到如果其他人掌握了您的密码,这是一个很大的安全风险,因此大多数 Unix 程序不会读取此文件,除非它只能由您自己读取(但 curl 不在乎)。

.netrc如果被告知,Curl 支持文件(使用-n/--netrc和--netrc-optional选项)。这不仅限于 FTP,因此 curl 可以将它用于所有使用身份验证的协议。

一个简单的.netrc文件可能类似于:

machine curl.se login iamdaniel password mysecret

自定义输出

为了更好地让脚本程序员了解 curl 的进度,引入了-w/--write-out选项。使用它,您可以指定要从之前的传输中提取哪些信息。

要显示下载的字节数以及一些文本和结束换行符:

curl -w 'We downloaded %{size_download} bytes\n' www.download.com

Kerberos FTP 传输

Curl 支持 kerberos4 和 kerberos5/GSSAPI 进行 FTP 传输。您需要在 curl 构建时安装和使用 kerberos 包才能使用它。

首先,以正常方式获取 krb-ticket,例如使用 kinit/kauth 工具。然后以类似于以下方式使用 curl:

curl --krb private ftp://krb4site.com -u username:fakepwd

交换机上的密码没有用-u,但是一个空白的密码会让 curl 要求输入密码,并且您已经输入了 kinit/kauth 的真实密码。

远程网络

curl telnet 支持基本且易于使用。Curl 将在标准输入上传递给它的所有数据传递给远程服务器。使用类似于以下内容的命令行连接到远程 telnet 服务器:

curl telnet://remote.server.com

并在标准输入上输入要传递给服务器的数据。结果将被发送到标准输出或您指定的文件-o。

您可能希望-N/--no-buffer选项为慢速连接或类似情况关闭缓冲输出。

通过使用选项将选项传递给 telnet 协议协商-t。要告诉服务器我们使用 vt100 终端,请尝试以下操作:

curl -tTTYPE=vt100 telnet://remote.server.com

其他有趣的选项-t包括:

XDISPLOC=<X display>设置 X 显示位置。
NEW_ENV=<var,val>设置环境变量。

注意: telnet 协议没有指定使用指定用户和密码登录的任何方式,因此 curl 无法自动执行此操作。为此,您需要跟踪何时收到登录提示并相应地发送用户名和密码。

持久连接

在单个命令行上指定多个文件将使 curl 按指定顺序一个接一个地传输所有文件。

libcurl 将尝试使用持久连接进行传输,以便到同一主机的第二次传输可以使用已启动并在上一次传输中保持打开状态的相同连接。这大大减少了除了第一次传输之外的所有连接时间,并且可以更好地利用网络。

请注意,对于在子序列 curl 调用中使用的传输,curl 不能使用持久连接。如果它们使用相同的主机,请尝试在同一命令行上填充尽可能多的 URL,因为这将使传输更快。如果您使用 HTTP 代理进行文件传输,几乎所有传输都将是持久的。

使用单个命令行进行多次传输

如上所述,您可以通过简单地添加更多 URL 来使用一个命令行下载多个文件。如果您希望将它们保存到本地文件而不是仅打印到标准输出,则需要为您指定的每个 URL 添加一个保存选项。请注意,这也适用于-O选项(但不是--remote-name-all)。

例如:获取两个文件并-O用于第一个和自定义文件名用于第二个:

curl -O http://url.com/file.txt ftp://ftp.com/moo.exe -o moo.jpg

您还可以以类似的方式上传多个文件:

curl -T local1 ftp://ftp.com/moo.exe -T local2 ftp://ftp.com/moo2.txt

IPv6

当主机查找返回 IPv6 地址时 curl 将使用 IPv6 连接到服务器,如果连接失败则回退到 IPv4。和选项可以指定当--ipv4两者--ipv6都可用时使用哪个地址。IPv6 地址也可以使用以下语法直接在 URL 中指定:

http://[2001:1890:1112:1::20]/overview.html

使用此样式时,-g必须提供选项以阻止 curl 将方括号解释为特殊的通配符。fe80::1234%1也可以使用包括范围标识符的链接本地和站点本地地址,例如,但范围部分必须是数字或与 Linux 上的现有网络接口匹配,并且百分比字符必须是 URL 转义的。SFTP URL 中的上一个示例可能如下所示:

sftp://[fe80::1234%251]/

除了在 URL 中提供的 IPv6 地址(例如,提供给--proxy、--interface或--ftp-port选项)不应进行 URL 编码。

相关内容标签

文章评论