在Linux中curl是一个利用URL规则在命令行下工作的文件传输工具,可以说是一款很强大的http命令行工具。它支持文件的上传和下载,是综合传输工具,但按传统,习惯称url为下载工具。

语法:# curl [option] [url]

常见参数:

-A/–user-agent <string> 设置用户代理发送给服务器
-b/–cookie <name=string/file> cookie字符串或文件读取位置
-c/–cookie-jar <file> 操作结束后把cookie写入到这个文件中
-C/–continue-at <offset> 断点续转
-D/–dump-header <file> 把header信息写入到该文件中
-e/–referer 来源网址
-f/–fail 连接失败时不显示http错误
-o/–output 把输出写到该文件中
-O/–remote-name 把输出写到该文件中,保留远程文件的文件名
-r/–range <range> 检索来自HTTP/1.1或FTP服务器字节范围
-s/–silent 静音模式。不输出任何东西
-T/–upload-file <file> 上传文件
-u/–user <user[:password]> 设置服务器的用户和密码
-w/–write-out [format] 什么输出完成后
-x/–proxy <host[:port]> 在给定的端口上使用HTTP代理
-#/–progress-bar 进度条显示当前的传送状态

一些示例:

1、基本用法

[linuxmi@localhost ~/www.linuxmi.com]$curl https://www.linuxmi.com

执行后,www.linuxmi.com 的html就会显示在屏幕上了

Ps:由于安装linux的时候很多时候是没有安装桌面的,也意味着没有浏览器,因此这个方法也经常用于测试一台服务器是否可以到达一个网站

2、保存访问的网页

2.1:使用Linux的重定向功能保存

[linuxmi@localhost ~/www.linuxmi.com]$curl http://www.linuxmi.com>> linuxmi.html
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 147 100 147 0 0 538 0 –:–:– –:–:– –:–:– 538

2.2:可以使用curl的内置option:-o(小写)保存网页

[linuxmi@localhost ~/www.linuxmi.com]$curl -o linuxmi.html https://www.linuxmi.com

执行完成后会显示如下界面,显示100%则表示保存成功

% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 61572 100 61572 0 0 72352 0 –:–:– –:–:– –:–:– 72267

2.3:可以使用curl的内置option:-O(大写)保存网页中的文件

要注意这里后面的url要具体到某个文件,不然抓不下来

[linuxmi@localhost ~/www.linuxmi.com]$curl -O https://www.linuxmi.com/wp-content/uploads/2020/02/linuxmi.png
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 29158 100 29158 0 0 47029 0 –:–:– –:–:– –:–:– 46953

3、测试网页返回值

[linuxmi@localhost ~/www.linuxmi.com]$curl -o /dev/null -s -w %{http_code} www.linuxmi.com
302

Ps:在脚本中,这是很常见的测试网站是否正常的用法

4、查询HTTP标头

HTTP标头允许远程Web服务器发送有关自身的其他信息以及实际请求。 这为客户提供了有关如何处理请求的详细信息。

要从网站查询HTTP标头,请执行以下操作:

[linuxmi@localhost ~/www.linuxmi.com]$curl -I https://www.linuxmi.com

5、限制下载率

为防止curl占用带宽,您可以将下载速率限制为90KB/s,如下所示。

[linuxmi@localhost ~/www.linuxmi.com]$curl –limit-rate 8K https://www.linuxmi.com/linuxmi.com.gz -O

6、显示下载进度条

[linuxmi@localhost ~/www.linuxmi.com]$curl -# -O https://www.linuxmi.com/wp-content/uploads/2020/02/linuxmi.png

7、断点续传

参数:

-C <offset>
–continue-at <offset>

断点续转,从文件头的指定位置开始继续下载/上传;
offset续传开始的位置,如果offset值为“-”,curl会自动从文件中识别起始位置开始传输

[linuxmi@localhost ~/www.linuxmi.com]$curl -# -O http://mirrors.163.com/debian-cd/current-live/amd64/iso-hybrid/debian-live-10.3.0-amd64-cinnamon.iso
####### 10.1%^C
[linuxmi@localhost ~/www.linuxmi.com]$curl -# -C- -O http://mirrors.163.com/debian-cd/current-live/amd64/iso-hybrid/debian-live-10.3.0-amd64-cinnamon.iso
########

OK,本文暂时就这样,如果有补充再更新。

发表回复