linux命令_curl

curl

curl是一个非常实用的、用来与服务器之间传输数据的工具;支持的协议包括 (DICT, FILE, FTP, FTPS, GOPHER, HTTP, HTTPS, IMAP, IMAPS, LDAP, LDAPS, POP3, POP3S, RTMP, RTSP, SCP, SFTP, SMTP, SMTPS, TELNET and TFTP),curl设计为无用户交互下完成工作;curl提供了一大堆非常有用的功能,包括代理访问、用户认证、ftp上传下载、HTTP POST、SSL连接、cookie支持、断点续传…。

curl,全称CommandLine URL 或 CommandLine Uniform Resource Locator,顾名思义,curl命令是在命令行方式下工作,利用URL的语法进行数据的传输或者文件的传输。

这个命令行工具现在多用于Unix和Linux操作系统,是一个开源的工具,功能十分强大。

下面是crul的官方网站,我们可以该网站获取该工具的最新版本,还有最全面的使用方法。

https://curl.haxx.se/
从官网可以了解到,该工具支持30多种传输类型,包括多种协议。

[En]

We can know from the official website that the tool supports more than 30 types of transmissions, including a variety of protocols.

命令语法

> curl (选项)(参数)

命令选项

参数组 参数 描述 url url 需要抓取的一到多个URLs; 多个下面通配符的方式:

1、http://{www,ftp,mail}.aiezu.com;

2、
http://aiezu.com/images/[001-999].jpg;

3、
http://aiezu.com/images/[1-999].html;

4、

请 求 头 -H “name: value” –header “name: value” (HTTP)添加一个http header(http请求头); -H “name:” –header “name:” (HTTP)移除一个http header(http请求头); -A “string” –user-agent “string”
【参考】

(HTTP)设置Http请求头”User-Agent”,服务器通过”User-Agent”可以判断客户端使用的浏览器名称和操作系统类型,伪造此参数能导致服务器做出错误判断。 也可以使用”-H”, “–header option”设置此选项; -e –referer
【参考】

(HTTP)设置访问时的来源页面,告诉http服务从哪个页面进入到此页面; -e “aiezu.com”相当于”-H “Referer: www.qq.com””; 响 应 头 -I –head (HTTP)只输出HTTP-header,不获取内容(HTTP/FTP/FILE)。 用于HTTP服务时,获取页面的http头; (如:curl -I
http://aiezu.com

) 用于FTP/FILE时,将会获取文件大小、最后修改时间; (如:curl -I file://test.txt) -i –include (HTTP)输出HTTP头和返回内容; -D –dump-header (HTTP)转储http响应头到指定文件; cookie -b name=data –cookie name=data
【参考】

(HTTP)发送cookie数据到HTTP服务器,数据格式为:”NAME1=VALUE1; NAME2=VALUE2″; 如果行中没有”=”,将把参数值当作cookie文件名; 这个cookie数据可以是由服务器的http响应头”Set-Cookie:”行发送过来的; -c filename –cookie-jar file name
【参考】

(HTTP)完成操作后将服务器返回的cookies保存到指定的文件; 指定参数值为”-“将定向到标准输出”如控制台”; -j –junk-session-cookies (HTTP)告诉curl放弃所有的”session cookies”; 相当于重启浏览器; 代理 -x host:port -x [protocol://[user:pwd@]host[:port] –proxy [protocol://[user:pwd@]host[:port]
【参考】

使用HTTP代理访问;如果未指定端口,默认使用8080端口; protocol默认为http_proxy,其他可能的值包括: http_proxy、HTTPS_PROXY、socks4、socks4a、socks5; 如: –proxy 8.8.8.8:8080; -x “http_proxy://aiezu:123@aiezu.com:80″ -p –proxytunnel 将”-x”参数的代理,作为通道的方式去代理非HTTP协议,如ftp; –socks4
【参考】

使用SOCKS4代理; 使用SOCKS4A代理; 使用SOCKS5代理; 此参数会覆盖”-x”参数; –proxy-anyauth –proxy-basic –proxy-diges –proxy-negotiate –proxy-ntlm http代理认证方式,参考: –anyauth –basic –diges –negotiate –ntlm -U

–proxy-user

设置代理的用户名和密码; 数据 传输 -G –get
【参考】

如果使用了此参数,”-d/”、”–data”、”–data-binary”参数设置的数据,讲附加在url上,以GET的方式请求; -d @file -d “string” –data “string” –data-ascii “string” –data-binary “string” –data-urlencode “string”
【参考】

(HTTP)使用HTTP POST方式发送”key/value对”数据,相当于浏览器表单属性(method=”POST”,enctype=”application/x-www-form-urlencoded”) -d,–data:HTTP方式POST数据; –data-ascii:HTTP方式POST ascii数据; –data-binary:HTTP方式POST二进制数据; –data-urlencode:HTTP方式POST数据(进行urlencode); 如果数据以”@”开头,后紧跟一个文件,将post文件内的内容; -F name=@file -F name=
【参考】

(HTTP)使用HTTP POST方式发送类似”表单字段”的多类型数据,相当于同时设置浏览器表单属性(method=”POST”,enctype=”multipart/form-data”),可以使用此参数上传二进制文件。 如果字段内容以”@”开头,剩下的部分应该是文件名,curl将会上传此文件,如: curl -F “pic=@pic.jpg”
http://aiezu.com

; curl -F “page=@a.html;type=text/html”
http://aiezu.com

curl -F “page=@/tmp/a;filename=a.txt”
http://aiezu.com

如果字段内容以”
http://aiezu.com

; –form-string
http://aiezu.com/a.php

” -T – curl ”
http://aiezu.com/a.php

” -T –
http://aiezu.com

curl -T “img[1-1000].png”
http://aiezu.com

断点 续传 -C –continue-at 断点续转,从文件头的指定位置开始继续下载/上传; offset续传开始的位置,如果offset值为”-“,curl会自动从文件中识别起始位置开始传输; -r –range (HTTP/FTP/SFTP/FILE) 只传输内容的指定部分: 0-499:最前面500字节; -500:最后面500字节; 9500-:最前面9500字节; 0-0,-1:最前面和最后面的1字节; 100-199,500-599:两个100字节; 认证 –basic (HTTP)告诉curl使用HTTP Basic authentication(HTTP协议时),这是默认认证方式; –ntlm (HTTP)使用NTLM身份验证方式,用于HTTP协议; 一般用于IIS使用NTLM的网站; –digest (HTTP)使用HTTP Digest authentication加密,用于HTTP协议; 配合”-u/–user”选项,防止密码使用明文方式发送; –negotiate (HTTP)使用GSS-Negotiate authentication方式,用于HTTP协议; 它主要目的是为它的主要目的是为kerberos5认证提供支持支持; –anyauth (HTTP)告诉curl自动选择合适的身份认证方法,并选用最安全的方式; -u user:password –user user:password 使用用户名、密码认证,此参数会覆盖”-n”、”–netrc”和”–netrc-optional”选项; 如果你只提供用户名,curl将要求你输入密码; 如果你使用”SSPI”开启的curl库做”NTLM”认证,可以使用不含用户名密码的”-u:”选项,强制curl使用当前登录的用户名密码进行认证; 此参数相当于设置http头”Authorization:”; 证书 -E

If a download is slower than speed-limit bytes per second during a speed-time period, the download gets aborted. If speed-time is used, the default speed-limit will be 1 unless set with -Y. This option controls transfers and thus will not affect slow connects etc. If this is a concern for you, try the –connect-timeout option. -Y –speed-limit If a download is slower than this given speed (in bytes per second) for speed-time seconds it gets aborted. speed-time is set with -y and is 30 if not set. 其他 选项 -0/–http1.0 (HTTP) 强制curl使用HTTP 1.0而不是使用默认的HTTP 1.1; –interface 使用指定的网卡接口访问; curl –interface eth0
http://aiezu.com

curl –interface 10.0.0.101
http://aiezu.com

-X –request (HTTP)指定与服务器通信使用的请求方法,如:GET、PUT、POST、DELETE等,默认GET; –keepalive-time 设置keepalive时间 –no-keepalive 关闭keepalive功能; –no-buffer 禁用对输出流缓冲; –buffer 启用输出流缓冲; -L –location (HTTP/HTTPS)追随http响应头”Location:”定向到跳转后的页面; (在http响应码为3XX时使用,如301跳转、302跳转) –location-trusted (HTTP/HTTPS)同”–location”,但跳转后会发送跳转前的用户名和密码; –compressed (HTTP)请求对返回内容使用压缩算法进行压缩;curl支持对gzip压缩进行解压; –connect-timeout 指定最大连接超时,单位”秒”; -m seconds –max-time seconds 限制整个curl操作的最长时间,单位为秒; -s –silent 安静模式。不要显示进度表或错误消息; -# –progress-bar 显示进度条; 错误 选项 -f –fail (HTTP)连接失败时(400以上错误)不返回默认错误页面,而是返回一个curl错误码”22″; –retry –retry-delay –retry-max-time 失败重试次数; 重试间隔时间; 最大重试时间; -S –show-error 安静模式下显示错误信息; –stderr 错误信息保存文件; 输出 -o file –output file 将返回内容输出到文件。 如果是用过通配符获取多个url,可以使用”#”后跟”数字序号”,curl会自动将它替换对应的关键词,如: curl ”
http://aiezu.com/{a,b}.txt

” -o “#1.txt”; 将保存为:”a.txt”,”b.txt”; curl ”
http://aiezu.com/{a,b}_[1-3].txt

” -o “#1#2.txt”; 将保存为:a1.txt、a2.txt、a3.txt、b1.txt、b2.txt、b3.txt 如果要根据规则创建保存目录,参考:”–create-dirs” 指定”-“将定向到标准输出”如控制台”; -O –remote-name 将返回内容输出到当前目录下,和url中文件名相同的文件中(不含目录); –create-dirs 与”-o”参数配合使用,创建必要的本地目录层次结构 -w –write-out format 操作完成后在返回信息尾部追加指定的内容;要追加的内容可以是一个字符串”string”、从文件中获取”@filename”、从标准输入中获取”@-” 格式参数中可以用%{variable_name} 方式使用响应信息的相关变量,如:%{content_type}、%{http_code}、%{local_ip}…,更多变量参考”man curl”获取; 格式参数可以使用”\n”、”\r”、”\t”等转义字符; 调试 –trace 转储所有传入和传出的数据到文件,包括描述信息; 使用”-“作为文件名将输出发送到标准输出。 –trace-ascii file 转储所有传入和传出的数据到文件,包括描述信息,只转储ASCII部分,更容易阅读; 使用”-“作为文件名将输出发送到标准输出。 这个选项会覆盖之前使用的-v、 –verbose、 –trace-ascii选项; –trace-time 转储文件中添加时间信息; -K –config 从配置文件中读取参数,参考:
http://curl.haxx.se/docs/

-v –verbose 显示更详细的信息,调试时使用; 帮助 -M –manual 显示完整的帮助手册; -h –help linux curl用法帮助;

-h 解释

-a/–append 上传文件时,附加到目标文件 –anyauth 可以使用”任何”身份验证方法 –basic 使用HTTP基本验证 -B/–use-ascii 使用ASCII文本传输 -d/–data HTTP POST方式传送数据 –data-ascii 以ascii的方式post数据 –data-binary 以二进制的方式post数据 –negotiate 使用HTTP身份验证 –digest 使用数字身份验证 –disable-eprt 禁止使用EPRT或LPRT –disable-epsv 禁止使用EPSV –egd-file 为随机数据(SSL)设置EGD socket路径 –tcp-nodelay 使用TCP_NODELAY选项 -E/–cert

linux错误代码

退出码 错误描述 1 Unsupported protocol. This build of curl has no support for this protocol. 2 Failed to initialize. 3 URL malformed. The syntax was not correct. 5 Couldn’t resolve proxy. The given proxy host could not be resolved. 6 Couldn’t resolve host. The given remote host was not resolved. 7 Failed to connect to host. 8 FTP weird server reply. The server sent data curl couldn’t parse. 9 FTP access denied. The server denied login or denied access to the particular resource or directory you wanted to reach. Most often you tried to change to a directory that doesn’t exist on the server. 11 FTP weird PASS reply. Curl couldn’t parse the reply sent to the PASS request. 13 FTP weird PASV reply, Curl couldn’t parse the reply sent to the PASV request. 14 FTP weird 227 format. Curl couldn’t parse the 227-line the server sent. 15 FTP can’t get host. Couldn’t resolve the host IP we got in the 227-line. 17 FTP couldn’t set binary. Couldn’t change transfer method to binary. 18 Partial file. Only a part of the file was transferred. 19 FTP couldn’t download/access the given file, the RETR (or similar) command failed. 21 FTP quote error. A quote command returned error from the server. 22 HTTP page not retrieved. The requested url was not found or returned another error with the HTTP error code being 400 or above. This return code only appears if -f/–fail is used. 23 Write error. Curl couldn’t write data to a local filesystem or similar. 25 FTP couldn’t STOR file. The server denied the STOR operation, used for FTP uploading. 26 Read error. Various reading problems. 27 Out of memory. A memory allocation request failed. 28 Operation timeout. The specified time-out period was reached according to the conditions. 30 FTP PORT failed. The PORT command failed. Not all FTP servers support the PORT command, try doing a transfer using PASV instead! 31 FTP couldn’t use REST. The REST command failed. This command is used for resumed FTP transfers. 33 HTTP range error. The range “command” didn’t work. 34 HTTP post error. Internal post-request generation error. 35 SSL connect error. The SSL handshaking failed. 36 FTP bad download resume. Couldn’t continue an earlier aborted download. 37 FILE couldn’t read file. Failed to open the file. Permissions? 38 LDAP cannot bind. LDAP bind operation failed. 39 LDAP search failed. 41 Function not found. A required LDAP function was not found. 42 Aborted by callback. An application told curl to abort the operation. 43 Internal error. A function was called with a bad parameter. 45 Interface error. A specified outgoing interface could not be used. 47 Too many redirects. When following redirects, curl hit the maximum amount. 48 Unknown TELNET option specified. 49 Malformed telnet option. 51 The peer’s SSL certificate or SSH MD5 fingerprint was not ok. 52 The server didn’t reply anything, which here is considered an error. 53 SSL crypto engine not found. 54 Cannot set SSL crypto engine as default. 55 Failed sending network data. 56 Failure in receiving network data. 58 Problem with the local certificate. 59 Couldn’t use specified SSL cipher. 60 Peer certificate cannot be authenticated with known CA certificates. 61 Unrecognized transfer encoding. 62 Invalid LDAP URL. 63 Maximum file size exceeded. 64 Requested FTP SSL level failed. 65 Sending the data requires a rewind that failed. 66 Failed to initialize SSL Engine. 67 The user name, password, or similar was not accepted and curl failed to log in. 68 File not found on TFTP server. 69 Permission problem on TFTP server. 70 Out of disk space on TFTP server. 71 Illegal TFTP operation. 72 Unknown TFTP transfer ID. 73 File already exists (TFTP). 74 No such user (TFTP). 75 Character conversion failed. 76 Character conversion functions required. 77 Problem with reading the SSL CA cert (path? access rights?). 78 The resource referenced in the URL does not exist. 79 An unspecified error occurred during the SSH session. 80 Failed to shut down the SSL connection. 82 Could not load CRL file, missing or wrong format (added in 7.19.0). 83 Issuer check failed (added in 7.19.0). XX More error codes will appear here in future releases. The existing ones are meant to never change.

示例

下载文件

curl命令可以用来执行下载、发送各种HTTP请求,指定HTTP头部等操作。如果系统没有curl可以使用 yum install curl安装,也可以下载安装。curl是将下载文件输出到stdout,将进度信息输出到stderr,不显示进度信息使用 --silent选项。

curl URL --silent

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

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

linux命令_curl

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

linux命令_curl

断点续传

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

curl URL/File -C 偏移量

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

使用curl设置参照页字符串

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

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

curl --referer https://www.baidu.com https://www.coonote.com

用curl设置cookies

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

curl http://www.baidu.com --cookie "user=ivanlee;pass=123456"

linux命令_curl

将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"

linux命令_curl

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

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

linux命令_curl

curl的带宽控制和下载配额

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

curl URL --limit-rate 50k

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

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

curl URL --max-filesize bytes

如果文件大小超过限制,该命令将返回非零退出代码,如果该命令正常,则返回0。

[En]

If the file size exceeds the limit, the command returns a non-zero exit code, or 0 if the command is normal.

只打印响应头部信息

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

linux命令_curl

增加头部信息

有时需要在 http request 之中,自行增加一个头信息。 --header 参数就可以起到这个作用。

$ curl --header "Content-Type:application/json" http://example.com

显示通信过程

-v 参数可以显示一次 http 通信的整个过程,包括端口连接和 http request 头信息。

ivanlee@ivanleedeMacBook-Pro ~ % curl -v http://www.jd.com
*   Trying 116.207.187.3:80...

* Connected to www.jd.com (116.207.187.3) port 80 (#0)
> GET / HTTP/1.1
> Host: www.jd.com
> User-Agent: curl/7.79.1
> Accept: */*
>
* Mark bundle as not supporting multiuse
< HTTP/1.1 302 Moved Temporarily
< Server: nginx
< Date: Fri, 27 May 2022 06:13:44 GMT
< Content-Type: text/html
< Content-Length: 138
< Connection: keep-alive
< Location: https://www.jd.com/
< Timing-Allow-Origin: *
< X-Trace: 302-1653632024641-0-0-0-0-0
< Strict-Transport-Security: max-age=3600
<

302 Found

302 Found
nginx

* Connection #0 to host www.jd.com left intact

http动词

curl 默认的 HTTP 动词是 GET,使用 -X 参数可以支持其他动词。

$ curl -X POST www.example.com
$ curl -X DELETE www.example.com

下载资源

-O 大写字母O参数, 直接八寸资源到本地,有原文件名

ivanlee@ivanleedeMacBook-Pro ~ % curl -O http://hcdn1.luffycity.com/static/frontend/public_class/PY1@2x_1566529821.1110113.png
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   253  100   253    0     0     42      0  0:00:06  0:00:05  0:00:01    61
ivanlee@ivanleedeMacBook-Pro ~ % ls
Applications (Parallels)    GolandProjects          PY1@2x_1566529821.1110113.png   PycharmProjects         configfile          java_error_in_pycharm_13464.log

使用curl模拟post请求

> curl -d "param1=value1¶m2=value2" https://json.im/login
> curl -d'login=rumenz&password=123' -X POST https://json.im/login
> curl -d 'login=rumenz' -d 'password=123' -X POST  https://json.im/login

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

> curl --data-urlencode 'comment=hello world' https://json.im/login

上传文本文件

> curl -d '@data.txt' https://json.im/upload

post json格式的数据

> curl -l -H 'Content-type: application/json' -X POST -d '{"rumenz":"123"}' https://json.im/123.json

向服务器发送 Cookie

> curl https://json.im --cookie "user=rumenz&pass=123456"

Cookie写入到一个文件

> curl -c cookies.txt https://json.im

上传二进制文件

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

> curl -F "file=@123.png" https://json.im/uploadfile

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

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

> curl -F 'file=@123.png;type=image/png'  https://json.im/uploadfile

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

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

> curl -F 'file=@123.png;filename=rumenz.png' https://json.im/uploadfile

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

请求跟随服务器的重定向

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

> curl -L -d 'rumenz=123' https://json.im/

curl接口测试

curl 可以很方便地完成对 REST API 的调用场景,比如:设置 Header,指定 HTTP 请求方法,指定 HTTP 消息体,指定权限认证信息等。通过 -v 选项也能输出 REST 请求的所有返回信息。curl 功能很强大,有很多参数,这里列出 REST 测试常用的参数:

-X/--request [GET|POST|PUT|DELETE|...]  指定请求的 HTTP 方法
-H/--header                           指定请求的 HTTP Header
-d/--data                             指定请求的 HTTP 消息体(Body)
-v/--verbose                          输出详细的返回信息
-u/--user                             指定账号、密码
-b/--cookie                           读取 cookie

典型的测试命令为:
curl -v -X POST -H "Content-Type: application/json" http://127.0.0.1:8080/user -d'{"username":"admin","password":"admin1234"}'...

测试get请求
curl http://www.linuxidc.com/login.cgi?user=test001&password=123456

测试post请求
curl -d "user=nickwolfe&password=12345" http://www.linuxidc.com/login.cgi

请求主体用json格式
curl -X POST -H 'content-type: application/json' -d @json文件绝对路径 URL
curl -X POST -H 'content-type: application/json' -d 'json内容' URL

请求主体用xml格式
curl -X POST -H 'content-type: application/xml' -d @xml文件绝对路径 URL
curl -X POST -H 'content-type: application/xml' -d 'xml内容' URL

发送post请求时需要使用-X选项,除了使用POST外,还可以使用http规范定义的其它请求谓词,如PUT,DELETE等
curl -XPOST url

#发送post请求时,通常需要指定请求体数据。可以使用-d或--data来指定发送的请求体。
curl -XPOST -d "name=leo&age=12" url

如果需要对请求数据进行urlencode,可以使用下面的方式:
curl -XPOST --data-urlencode "name=leo&age=12" url

此外发送post请求还可以有如下几种子选项:
–data-raw
–data-ascii
–data-binary

linux命令_curl

Original: https://www.cnblogs.com/ivanlee717/p/16317538.html
Author: ivanlee717
Title: linux命令_curl

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/523489/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球