curl 命令简介

219 阅读2分钟

curl 是一个强大的命令行工具,用于从服务器传输数据。它支持多种协议,包括 HTTP、HTTPS、FTP、FTPS、SFTP、SCP、SMTP、POP3、IMAP 等。curl 非常灵活,可以用于各种网络请求和数据传输任务。

基本语法

curl [选项] [URL...]

常用选项

以下是一些常用的 curl 选项及其解释:

  • -o [file]
    将输出保存到指定的文件中。
    示例:curl -o example.html http://example.com

  • -O
    使用 URL 中的文件名将输出保存到文件中。
    示例:curl -O http://example.com/example.html

  • -L
    跟随重定向。
    示例:curl -L http://example.com

  • -s
    静默模式,不显示进度条或错误信息。
    示例:curl -s http://example.com

  • -v
    详细模式,显示请求和响应的详细信息。
    示例:curl -v http://example.com

  • -u [user:password]
    使用指定的用户名和密码进行身份验证。
    示例:curl -u username:password http://example.com

  • -d [data]
    发送 POST 请求并附带数据。
    示例:curl -d "param1=value1&param2=value2" http://example.com

  • -X [command]
    指定 HTTP 请求方法。
    示例:curl -X PUT http://example.com

  • -H [header]
    添加 HTTP 头。
    示例:curl -H "Content-Type: application/json" http://example.com

  • -I
    仅显示响应头。
    示例:curl -I http://example.com

  • -k
    忽略 SSL 证书验证。
    示例:curl -k https://example.com

  • -F [name=content]
    模拟表单提交。
    示例:curl -F "file=@/path/to/file" http://example.com

  • -b [cookie]
    发送指定的 Cookie。
    示例:curl -b "name=value" http://example.com

  • -c [file]
    将 Cookie 保存到文件中。
    示例:curl -c cookies.txt http://example.com

示例

  1. 下载文件

    curl -o example.html http://example.com
    
  2. 静默模式下载

    curl -s -o example.html http://example.com
    
  3. 下载文件到指定路径(忽略错误),执行文件如果保存 执行空操作(:)

curl -s "http://wwww.baidu.com/hotUpdate.sh" -o /export/data/hotUpdate.sh; source /export/data/hotUpdate.sh || :
  1. 跟随重定向

    curl -L http://example.com
    
  2. 发送 POST 请求

    curl -d "param1=value1&param2=value2" http://example.com
    
  3. 发送 JSON 数据的 POST 请求

    curl -H "Content-Type: application/json" -d '{"key1":"value1", "key2":"value2"}' http://example.com
    
  4. 添加 HTTP 头

    curl -H "Authorization: Bearer YOUR_TOKEN" http://example.com
    
  5. 上传文件

    curl -F "file=@/path/to/file" http://example.com/upload
    
  6. 使用用户名和密码进行身份验证

    curl -u username:password http://example.com
    
  7. 忽略 SSL 证书验证

    curl -k https://example.com
    
  8. 保存和发送 Cookie

    # 保存 Cookie
    curl -c cookies.txt http://example.com
    # 发送 Cookie
    curl -b cookies.txt http://example.com
    

实际应用场景

  • 自动化任务:通过脚本自动下载文件、上传文件、提交表单数据等。
  • API 调用:与 RESTful API 交互,发送 GET、POST、PUT、DELETE 请求。
  • 调试网络请求:查看 HTTP 请求和响应的详细信息,调试和分析网络请求。
  • 数据抓取:从网页抓取数据,进行数据分析和处理。

curl 是一个功能强大的工具,适用于各种网络请求和数据传输任务。如果你有具体的使用场景或问题,欢迎继续提问!