Linux Snippets - curl

curl 是一个命令行工具,它的主要功能是基于网络协议,对指定 URL 进行网络数据传输。简单来说就是在命令行做各种网络请求操作。

关于 curl 命令的基本用法,可以参考阮一峰老师的博客 curl 的用法指南

这里再分享几个 curl 的实战场景。

curl 测试 URL 响应时间

1
curl -o /dev/null -s -w "time_connect: %{time_connect}\ntime_starttransfer: %{time_starttransfer}\ntime_total: %{time_total}\n" <URL>

-w 可以使用 %{变量名} 的方式展示请求的各种信息,其中关于请求时间的变量有以下几种:

1
2
3
4
5
6
7
8
# format.txt
time_namelookup: %{time_namelookup}\n
time_connect: %{time_connect}\n
time_appconnect: %{time_appconnect}\n
time_pretransfer: %{time_pretransfer}\n
time_redirect: %{time_redirect}\n
time_starttransfer: %{time_starttransfer}\n
time_total: %{time_total}\n

当然这里也可以使用封装好的工具,例如:httpstat

curl 下载 Github Release

1
curl -SL https://github.com/prometheus/node_exporter/releases/download/v1.8.2/node_exporter-1.8.2.linux-amd64.tar.gz -o /tmp/node_exporter.tar.gz

这里使用到的三个选项作用分别如下:

  • -L--show-error,即使使用-s静默模式也显示错误信息;
  • -S--location,自动跟随URL重定向;
  • -o--ouput FILE,指定输出文件名。

curl 带证书请求 HTTPS

以 K8S 集群的健康检查接口为例。

curl --cacert ca.crt --cert cert.crt --key cert.key https://192.168.229.128:6443/healthz 

注意:

  • 低版本的 curl 有个缺陷(7.29.0确认存在),--cert 参数后面需要带完整路径,否则证书无法识别,正确的命令如下:
curl --cacert ca.crt --cert ./cert.crt --key cert.key https://192.168.229.128:6443/healthz 

当直接使用文件名作为参数时,在 curl 命令后面加上 --trace <debug file> 参数,可以看到会有一条警告:== Info: warning: certificate file name “cerrt.crt” handled as nickname; please use “./cert.crt” to force file name

作者

ParTrove

发布于

2025-09-04

更新于

2025-09-04

许可协议