Linux shell编程学习笔记68: curl 命令行网络数据传输工具 选项数量雷人(上)

* 更新日志

* 20240809 补充2.6 和 2.7


0 前言

在网络时代,有经常需要在网络上传输数据,时我们需要通过网络下载文件,为了满足这种时代需要,Linux提供了众多网络命令,我们今天先研究curl命令。例如,我们可以使用 curl 从 URL 下载文件,或将文件上传到服务器。

1 curl命令 的功能、格式和选项说明

我们可以使用 curl --man | more 命令查看curl命令 的帮助信息。

[purpleEndurer @ bash ~]curl --man | more
                                  _   _ ____  _
  Project                     ___| | | |  _ \| |
                             / __| | | | |_) | |
                            | (__| |_| |  _ <| |___
                             \___|\___/|_| \_\_____|

NAME
       curl - transfer a URL

SYNOPSIS
       curl [options] [URL...]

DESCRIPTION
       curl  is  a tool to transfer data from or to a server, using one o
f the
       supported protocols (DICT, FILE, FTP, FTPS, GOPHER, HTTP, HTTPS,  IMAP,
       IMAPS,  LDAP,  LDAPS,  POP3, POP3S, RTMP, RTSP, SCP, SFTP, SMTP, SMTPS,
       TELNET and TFTP).  The command is designed to work without user  inter-
       action.

       curl offers a busload of useful tricks like proxy support, user authen-
       tication, FTP upload, HTTP post, SSL connections, cookies, file  trans-
       fer  resume,  Metalink,  and more. As you will see below, the number of
--More--

1.1 curl命令 的功能

curl 是 client url 或 command line url 的缩写。

curl是一个从命令行通过互联网传输数据的工具,它可以利用HTTP、HTTPS、FTP和SFTP等多种协议,从网络服务器传输数据或将数据传输到网络服务器。

除了进行文件传输,我们还可使用 curl命令 从终端发出 HTTP 请求,如 GET 和 POST。这在测试或与网络服务和 API 交互时非常有用。

利用 curl命令,我们可以在不打开浏览器的情况下检查网页内容,因为它可以获取并显示原始数据。

1.2 curl命令的格式

除了 curl --man命令,我们也可以使用curl --help命令获取curl命令的格式和选项说明。

[purpleEndurer @ bash ~]curl --help
Usage: curl [options...] <url>
Options: (H) means HTTP/HTTPS only, (F) means FTP only
     --anyauth       Pick "any" authentication method (H)
 -a, --append        Append to target file when uploading (F/SFTP)
     --basic         Use HTTP Basic Authentication (H)
     --cacert FILE   CA certificate to verify peer against (SSL)
     --capath DIR    CA directory to verify peer against (SSL)
 -E, --cert CERT[:PASSWD] Client certificate file and password (SSL)
     --cert-type TYPE Certificate file type (DER/PEM/ENG) (SSL)
     --ciphers LIST  SSL ciphers to use (SSL)
     --compressed    Request compressed response (using deflate or gzip)
 -K, --config FILE   Specify which config file to read
     --connect-timeout SECONDS  Maximum time allowed for connection
 -C, --continue-at OFFSET  Resumed transfer offset
 -b, --cookie STRING/FILE  String or file to read cookies from (H)
 -c, --cookie-jar FILE  Write cookies to this file after operation (H)
     --create-dirs   Create necessary local directory hierarchy
     --crlf          Convert LF to CRLF in upload
     --crlfile FILE  Get a CRL list in PEM format from the given file
 -d, --data DATA     HTTP POST data (H)
     --data-ascii DATA  HTTP POST ASCII data (H)
     --data-binary DATA  HTTP POST binary data (H)
     --data-urlencode DATA  HTTP POST data url encoded (H)
     --delegation STRING GSS-API delegation permission
     --digest        Use HTTP Digest Authentication (H)
     --disable-eprt  Inhibit using EPRT or LPRT (F)
     --disable-epsv  Inhibit using EPSV (F)
 -D, --dump-header FILE  Write the headers to this file
     --egd-file FILE  EGD socket path for random data (SSL)
     --engine ENGINGE  Crypto engine (SSL). "--engine list" for list
 -f, --fail          Fail silently (no output at all) on HTTP errors (H)
 -F, --form CONTENT  Specify HTTP multipart POST data (H)
     --form-string STRING  Specify HTTP multipart POST data (H)
     --ftp-account DATA  Account data string (F)
     --ftp-alternative-to-user COMMAND  String to replace "USER [name]" (F)
     --ftp-create-dirs  Create the remote dirs if not present (F)
     --ftp-method [MULTICWD/NOCWD/SINGLECWD] Control CWD usage (F)
     --ftp-pasv      Use PASV/EPSV instead of PORT (F)
 -P, --ftp-port ADR  Use PORT with given address instead of PASV (F)
     --ftp-skip-pasv-ip Skip the IP address for PASV (F)
     --ftp-pret      Send PRET before PASV (for drftpd) (F)
     --ftp-ssl-ccc   Send CCC after authenticating (F)
     --ftp-ssl-ccc-mode ACTIVE/PASSIVE  Set CCC mode (F)
     --ftp-ssl-control Require SSL/TLS for ftp login, clear for transfer (F)
 -G, --get           Send the -d data with a HTTP GET (H)
 -g, --globoff       Disable URL sequences and ranges using {} and []
 -H, --header LINE   Custom header to pass to server (H)
 -I, --head          Show document info only
 -h, --help          This help text
     --hostpubmd5 MD5  Hex encoded MD5 string of the host public key. (SSH)
 -0, --http1.0       Use HTTP 1.0 (H)
     --ignore-content-length  Ignore the HTTP Content-Length header
 -i, --include       Include protocol headers in the output (H/F)
 -k, --insecure      Allow connections to SSL sites without certs (H)
     --interface INTERFACE  Specify network interface/address to use
 -4, --ipv4          Resolve name to IPv4 address
 -6, --ipv6          Resolve name to IPv6 address
 -j, --junk-session-cookies Ignore session cookies read from file (H)
     --keepalive-time SECONDS  Interval between keepalive probes
     --key KEY       Private key file name (SSL/SSH)
     --key-type TYPE Private key file type (DER/PEM/ENG) (SSL)
     --krb LEVEL     Enable Kerberos with specified security level (F)
     --libcurl FILE  Dump libcurl equivalent code of this command line
     --limit-rate RATE  Limit transfer speed to this rate
 -l, --list-only     List only names of an FTP directory (F)
     --local-port RANGE  Force use of these local port numbers
 -L, --location      Follow redirects (H)
     --location-trusted like --location and send auth to other hosts (H)
 -M, --manual        Display the full manual
     --mail-from FROM  Mail from this address
     --mail-rcpt TO  Mail to this receiver(s)
     --mail-auth AUTH  Originator address of the original email
     --max-filesize BYTES  Maximum file size to download (H/F)
     --max-redirs NUM  Maximum number of redirects allowed (H)
 -m, --max-time SECONDS  Maximum time allowed for the transfer
     --metalink      Process given URLs as metalink XML file
     --negotiate     Use HTTP Negotiate Authentication (H)
 -n, --netrc         Must read .netrc for user name and password
     --netrc-optional Use either .netrc or URL; overrides -n
     --netrc-file FILE  Set up the netrc filename to use
 -N, --no-buffer     Disable buffering of the output stream
     --no-keepalive  Disable keepalive use on the connection
     --no-sessionid  Disable SSL session-ID reusing (SSL)
     --noproxy       List of hosts which do not use proxy
     --ntlm          Use HTTP NTLM authentication (H)
 -o, --output FILE   Write output to <file> instead of stdout
     --pass PASS     Pass phrase for the private key (SSL/SSH)
     --post301       Do not switch to GET after following a 301 redirect (H)
     --post302       Do not switch to GET after following a 302 redirect (H)
     --post303       Do not switch to GET after following a 303 redirect (H)
 -#, --progress-bar  Display transfer progress as a progress bar
     --proto PROTOCOLS  Enable/disable specified protocols
     --proto-redir PROTOCOLS  Enable/disable specified protocols on redirect
 -x, --proxy [PROTOCOL://]HOST[:PORT] Use proxy on given port
     --proxy-anyauth Pick "any" proxy authentication method (H)
     --proxy-basic   Use Basic authentication on the proxy (H)
     --proxy-digest  Use Digest authentication on the proxy (H)
     --proxy-negotiate Use Negotiate authentication on the proxy (H)
     --proxy-ntlm    Use NTLM authentication on the proxy (H)
 -U, --proxy-user USER[:PASSWORD]  Proxy user and password
     --proxy1.0 HOST[:PORT]  Use HTTP/1.0 proxy on given port
 -p, --proxytunnel   Operate through a HTTP proxy tunnel (using CONNECT)
     --pubkey KEY    Public key file name (SSH)
 -Q, --quote CMD     Send command(s) to server before transfer (F/SFTP)
     --random-file FILE  File for reading random data from (SSL)
 -r, --range RANGE   Retrieve only the bytes within a range
     --raw           Do HTTP "raw", without any transfer decoding (H)
 -e, --referer       Referer URL (H)
 -J, --remote-header-name Use the header-provided filename (H)
 -O, --remote-name   Write output to a file named as the remote file
     --remote-name-all Use the remote file name for all URLs
 -R, --remote-time   Set the remote file's time on the local output
 -X, --request COMMAND  Specify request command to use
     --resolve HOST:PORT:ADDRESS  Force resolve of HOST:PORT to ADDRESS
     --retry NUM   Retry request NUM times if transient problems occur
     --retry-delay SECONDS When retrying, wait this many seconds between each
     --retry-max-time SECONDS  Retry only within this period
 -S, --show-error    Show error. With -s, make curl show errors when they occur
 -s, --silent        Silent mode. Don't output anything
     --socks4 HOST[:PORT]  SOCKS4 proxy on given host + port
     --socks4a HOST[:PORT]  SOCKS4a proxy on given host + port
     --socks5 HOST[:PORT]  SOCKS5 proxy on given host + port
     --socks5-basic  Enable username/password auth for SOCKS5 proxies
     --socks5-gssapi Enable GSS-API auth for SOCKS5 proxies
     --socks5-hostname HOST[:PORT] SOCKS5 proxy, pass host name to proxy
     --socks5-gssapi-service NAME  SOCKS5 proxy service name for gssapi
     --socks5-gssapi-nec  Compatibility with NEC SOCKS5 server
 -Y, --speed-limit RATE  Stop transfers below speed-limit for 'speed-time' secs
 -y, --speed-time SECONDS  Time for trig speed-limit abort. Defaults to 30
     --ssl           Try SSL/TLS (FTP, IMAP, POP3, SMTP)
     --ssl-reqd      Require SSL/TLS (FTP, IMAP, POP3, SMTP)
 -2, --sslv2         Use SSLv2 (SSL)
 -3, --sslv3         Use SSLv3 (SSL)
     --ssl-allow-beast Allow security flaw to improve interop (SSL)
     --stderr FILE   Where to redirect stderr. - means stdout
     --tcp-nodelay   Use the TCP_NODELAY option
 -t, --telnet-option OPT=VAL  Set telnet option
     --tftp-blksize VALUE  Set TFTP BLKSIZE option (must be >512)
 -z, --time-cond TIME  Transfer based on a time condition
 -1, --tlsv1         Use => TLSv1 (SSL)
     --tlsv1.0       Use TLSv1.0 (SSL)
     --tlsv1.1       Use TLSv1.1 (SSL)
     --tlsv1.2       Use TLSv1.2 (SSL)
     --tlsv1.3       Use TLSv1.3 (SSL)
     --tls-max VERSION  Use TLS up to VERSION (SSL)
     --trace FILE    Write a debug trace to the given file
     --trace-ascii FILE  Like --trace but without the hex output
     --trace-time    Add time stamps to trace/verbose output
     --tr-encoding   Request compressed transfer encoding (H)
 -T, --upload-file FILE  Transfer FILE to destination
     --url URL       URL to work with
 -B, --use-ascii     Use ASCII/text transfer
 -u, --user USER[:PASSWORD]  Server user and password
     --tlsuser USER  TLS username
     --tlspassword STRING TLS password
     --tlsauthtype STRING  TLS authentication type (default SRP)
     --unix-socket FILE    Connect through this UNIX domain socket
 -A, --user-agent STRING  User-Agent to send to server (H)
 -v, --verbose       Make the operation more talkative
 -V, --version       Show version number and quit
 -w, --write-out FORMAT  What to output after completion
     --xattr        Store metadata in extended file attributes
 -q                 If used as the first parameter disables .curlrc
[purpleEndurer @ bash ~]

curl命令的格式:

curl [选项] <统一资源定位符>

1.3  curl选项说明

curl的选项是目前所学的命令中最多的一个。 

说明中的(H) 表示仅 HTTP/HTTPS,(F) 表示仅 FTP

选项说明
--anyauth选择“any”认证方式(H)
-a,--append上传时追加到目标文件 (F/SFTP)
--basic使用 HTTP 基本身份验证 (H)
--cacert FILECA 证书以验证对等方 (SSL)
--capath用于验证对等体的 DIR CA 目录 (SSL)
-E,--cert CERT[:PASSWD]客户端证书文件和密码 (SSL)
--cert-type TYPE证书文件类型 (DER/PEM/ENG) (SSL)
--ciphers列出要使用的 SSL 密码 (SSL)
--compressed请求压缩响应(使用 deflate 或 gzip)
-K,--config FILE指定要读取的配置文件
--connect-timeout SECONDS允许的最大连接时间
-C,--continue-at OFFSET恢复传输偏移
-b,--cookie STRING/FILE从中读取 cookie 的字符串或文件 (H)
-c,--cookie-jar FILE操作后将 cookie 写入指定文件 (H)
--create-dirs创建必要的本地目录层次结构
--crlf在上传中将 LF 转换为 CRLF
--crlfile FILE从给定文件中获取 PEM 格式的 CRL 列表
-d,--data DATAHTTP POST 数据 (H)
--data-ascii DATAHTTP POST ASCII数据(H)
--data-binary DATAHTTP POST 二进制数据 (H)
--data-urlencode DATAHTTP POST 数据 url 编码 (H)
--delegation STRINGGSS-API 委托权限
--digest使用 HTTP 摘要身份验证 (H)
--disable-eprt使用 EPRT 或 LPRT 抑制 (F)
--disable-epsv使用 EPSV 抑制 (F)
-D,--dump-header FILE将头文件写入此文件
--egd-file FILE随机数据  的 EGD 套接字路径(SSL)
--engine ENGINGE加密引擎 。列表为“--engine list”(SSL)
-f,--fail在 HTTP 错误 上静默失败(完全没有输出)(H)
-F,--form CONTENT指定 HTTP 多部分 POST 数据 (H)
--form-string STRING指定 HTTP 多部分 POST 数据 (H)
--ftp-account DATA帐户数据字符串 (F)
--ftp-alternative-to-user COMMAND用于替换“USER [name]”的命令字符串 (F)
--ftp-create-dirs远程目录如果不存在就创建(F)
--ftp-method [MULTICWD/NOCWD/SINGLECWD]控制 CWD 使用 (F)
--ftp-pasv使用 PASV/EPSV 代替 PORT (F)
-P,--ftp-port ADR使用具有给定地址的 PORT 而不是 PASV (F)
--ftp-skip-pasv-ip跳过 PASV 的 IP 地址 (F)
--ftp-pret在 PASV 之前发送 PRET (对于 drftpd) (F)
--ftp-ssl-ccc认证后发送 CCC (F)
--ftp-ssl-ccc-mode ACTIVE/PASSIVE设置 CCC 模式 (F)
--ftp-ssl-controlFTP 登录需要 SSL/TLS,传输需要清除 (F)
-G,--get使用 HTTP GET 发送 -d 数据(H)
-g,--globoff使用 {} 和 [] 禁用 URL 序列和范围
-H,--header LINE自定义头文件传递给服务器 (H)
-I,--head仅显示文档信息
-h,--help此帮助文本
--hostpubmd5 MD5主机公钥的十六进制编码的 MD5 字符串。(SSH)
-0,--http1.0使用 HTTP 1.0 (H)
--ignore-content-length忽略 HTTP Content-Length 头
-i,--include在输出中包含协议头 (H/F)
-k,--insecure允许连接到没有证书的 SSL 站点 (H)
--interface INTERFACE指定要使用的网络接口/地址
-4,--ipv4将名称解析为 IPv4 地址
-6,--ipv6将名称解析为 IPv6 地址
-j,--junk-session-cookies忽略从文件读取的会话 cookie (H) 
--keepalive-time SECONDSkeepalive 探测之间的间隔
--key KEY私钥文件名 (SSL/SSH)
--key-type TYPE私钥文件类型 (DER/PEM/ENG) (SSL)
--krb LEVEL启用具有指定安全级别的 Kerberos (F) 
--libcurl FILEDump libcurl 等效的此命令行代码
--limit-rate RATE将传输速度限制为指定速率
-l,--list-only仅列出 FTP 目录的名称 (F)
--local-port RANGE强制使用这些本地端口号
-L,--location跟随重定向 (H)
--location-trusted类似 --location 并将身份验证发送到其他主机 (H)
-M, --manual显示完整手册
--mail-from FROM来自此地址的邮件
--mail-rcpt TO发送邮件到此收件人
--mail-auth AUTH原始电子邮件的发件人地址
--max-filesize BYTES下载的最大文件大小 (H/F)
--max-redirs NUM允许的最大重定向数 (H)
-m,--max-time SECONDS允许传输的最大时间
--metalink将给定的 URL 处理为元链接 XML 文件
--negotiate使用 HTTP 协商身份验证 (H)
-n,--netrc用户名和密码必须读取 .netrc
--netrc-optional使用 .netrc 或 URL;覆盖 -n
--netrc-file FILE设置要使用的 netrc 文件名
-N,--no-buffer禁用输出流的缓冲
--no-keepalive在连接上禁用 keepalive 使用
--no-sessionid禁用 SSL 会话 ID 重用 (SSL)
--noproxy不使用代理的主机列表
--ntlm使用 HTTP NTLM 身份验证 (H)
-o,--output FILE将输出写入文件而不是标准输出
--pass PASS私钥的密码短语 (SSL/SSH)
--post301遵循 301 重定向后不要切换到 GET (H)
--post302遵循 302 重定向后不要切换到 GET (H)
--post303遵循 303 重定向后不要切换到 GET (H)
-#,--progress-bar将传输进度显示为进度条
--proto PROTOCOLS启用/禁用指定协议
--proto-redir PROTOCOLS在重定向时启用/禁用指定协议
-x,--proxy [PROTOCOL://]HOST[:PORT]在给定端口上使用代理
--proxy-anyauth选择“any”代理认证方式 (H)
--proxy-basic在代理上使用基本身份验证 (H)
--proxy-digest在代理上使用摘要式身份验证 (H)
--proxy-negotiate在代理上使用 Negotiate 身份验证 (H)
--proxy-ntlm在代理上使用 NTLM 身份验证 (H)
-U,--proxy-user USER[:P ASSWORD]代理用户和密码
--proxy1.0 HOST[:P ORT]在给定端口上使用 HTTP/1.0 代理
-p,--proxytunnel通过 HTTP 代理隧道进行操作(使用 CONNECT)
--pubkey KEY公钥文件名 (SSH)
-Q,--quote CMD在传输之前向服务器发送命令 (F/SFTP)
--random-file FILE用于从中读取随机数据的文件 (SSL)
-r,--range RANGE仅检索范围内的字节
--raw做 HTTP “raw”,不带任何传输解码 (H)
-e,--refererReferer URL (H)
-J,--remote-header-name使用头提供的文件名 (H)
-O,--remote-name将输出写入以远程文件方式命名的文件中
--remote-name-all对所有 URL 使用远程文件名
-R,--remote-time在本地输出上设置远程文件的时间
-X,--request COMMAND指定要使用的请求命令
--resolve HOST:PORT:ADDRESS强制将 HOST:PORT 解析为 ADDRESS
--retry NUM如果出现暂时性问题,请重试请求 NUM 次
--retry-delay SECONDS重试时,在每次之间等待这指定秒数
--retry-max-time SECONDS仅在旨定时间段内重试
-S,--show-error显示错误。使用 -s,使 curl 在发生错误时显示错误
-s,--silent静音模式。不输出任何内容
--socks4 HOST[:PORT]给定主机 + 端口上的 SOCKS4 代理
--socks4a HOST[:PORT]给定主机 + 端口上的 SOCKS4a 代理
--socks5 HOST[:PORT]给定主机 + 端口上的 SOCKS5 代理
--socks5-basic为 SOCKS5 代理启用用户名/密码身份验证
--socks5-gssapi为 SOCKS5 代理启用 GSS-API 身份验证
--socks5-hostname HOST[:PORT]SOCKS5代理,将主机名传递给代理
--socks5-gssapi-service NAMEsocks5 gssapi 的代理服务名称
--socks5-gssapi-nec与 NEC SOCKS5 服务器的兼容性
-Y,--speed-limit RATE停止低于速度限制的传输,持续 'speed-time' 秒
-y,--speed-time SECONDS触发限速中止的时间。默认值为 30
--ssl尝试 SSL/TLS (FTP、IMAP、POP3、SMTP)
--ssl-reqd需要 SSL/TLS(FTP、IMAP、POP3、SMTP)
-2,--sslv2使用 SSLv2 (SSL)
-3,--sslv3使用 SSLv3 (SSL)
--ssl-allow-beast允许安全漏洞改进互操作 (SSL)
--stderr FILE将 stderr(标准错误) 重定向到何处。- 表示 stdout(标准输出)
--tcp-nodelay使用 TCP_NODELAY 选项
-t,--telnet-option OPT=VAL设置 telnet 选项
--tftp-blksize VALUE设置 TFTP BLKSIZE 选项(必须为 >512)
-z,--time-cond基于时间条件的 TIME 传输
-1,--tlsv1使用 => TLSv1 (SSL)
--tlsv1.0使用 TLSv1.0 (SSL)
--tlsv1.1使用 TLSv1.1 (SSL)
--tlsv1.2使用 TLSv1.2 (SSL)
--tlsv1.3使用 TLSv1.3 (SSL)
--tls-max VERSION使用TLS最高版本(SSL)
--trace FILE将调试跟踪写入给定文件
--trace-ascii FILE类似于 --trace,但没有十六进制输出
--trace-time为跟踪/详细输出添加时间戳
--tr-encoding请求压缩传输编码 (H) 
-T,--upload-file FILE将 FILE 传输到目标
--url URL要处理的 URL
-B,--use-ascii使用 ASCII/文本传输
-u,--user USER[:PASSWORD]服务器用户和密码
--tlsuser 用户TLS 用户名
--tlspassword STRINGTLS 密码
--tlsauthtype STRINGTLS 身份验证类型(默认 SRP)
--unix-socket FILE通过此 UNIX 域套接字连接
-A,--user-agent STRINGUser-Agent 发送到服务器 (H)
-v,--verbose使操作更详细
-V,--version显示版本号并退出
-w,--write-outFORMAT 完成后输出什么
--xattr在扩展文件属性中存储元数据
-q如果用作第一个参数,则禁用 .curlrc

2 curl命令应用实例

2.1 curl :显示获取本命令的帮助或手册信息的格式

[purpleEndurer @ bash ~] curl
curl: try 'curl --help' or 'curl --manual' for more information
[purpleEndurer @ bash ~] 

 

 我们可以尝试 使用命令 'curl --help' 或 'curl --manual' 来了解更多信息。

2.2 curl 统一资源定位符:显示指定统一资源定位符的内容(源代码)

这里的 统一资源定位符 可以是网站域名或网页地址。

2.2.1 curl g.cn : 显示g.cn的源代码

[purpleEndurer @ bash ~] curl g.cn
<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">
<TITLE>301 Moved</TITLE></HEAD><BODY>
<H1>301 Moved</H1>
The document has moved
<A HREF="https://google.cn/">here</A>.
</BODY></HTML>
[purpleEndurer @ bash ~] 

2.1.2 curl www.google.cn:显示 www.google.cn 的源代码。

[purpleEndurer @ bash ~] curl www.google.cn
<!DOCTYPE html>
<html lang="zh">
  <head>
    <meta charset="utf-8">
    <title>Google</title>
    <style>
      html { background: #fff; margin: 0 1em; }
      body { font: .8125em/1.5 arial, sans-serif; text-align: center; }
      h1 { font-size: 1.5em; font-weight: normal; margin: 1em 0 0; }
      p#footer { color: #767676; font-size: .77em; }
      p#footer a { background: url(//www.google.cn/intl/zh-CN_cn/images/cn_icp.gif) top right no-repeat; padding: 5px 20px 5px 0; }
      ul { margin: 2em; padding: 0; }
      li { display: inline; padding: 0 2em; }
      div { -moz-border-radius: 20px; -webkit-border-radius: 20px; border: 1px solid #ccc; border-radius: 20px; margin: 2em auto 1em; max-width: 650px; min-width: 544px; }
      div:hover, div:hover * { cursor: pointer; }
      div:hover { border-color: #999; }
      div p { margin: .5em 0 1.5em; }
      img { border: 0; }
    </style>
  </head>
  <body>
    <div>
      <a href="https://www.google.com.hk/webhp?hl=zh-CN&amp;sourceid=cnhp">
        <img src="//www.google.cn/intl/zh-CN_cn/landing/cnexp/google-search.png" alt="Google" width="586" height="257">
      </a>
      <h1><a href="https://www.google.com.hk/webhp?hl=zh-CN&amp;sourceid=cnhp"><strong id="target">google.com.hk</strong></a></h1>
      <p>请收藏我们的网址
    </div>
    <p id="footer">
      <span>ICP证合字B2-20070004号</span>
    </p>
  </body>
</html>
[purpleEndurer @ bash ~] 

2.3 将统一定位符资源保存到文件

2.3.1 方法1:curl 统一定位符 > 文件名 

第1种方法是使用输出重定向功能,将curl命令的输出重定向到指定的文件。 

[purpleEndurer @ bash ~] curl g.cn > g.htm
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   215  100   215    0     0   1934      0 --:--:-- --:--:-- --:--:--  1919
[purpleEndurer @ bash ~] cat g.htm
<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">
<TITLE>301 Moved</TITLE></HEAD><BODY>
<H1>301 Moved</H1>
The document has moved
<A HREF="https://google.cn/">here</A>.
</BODY></HTML>
[purpleEndurer @ bash ~] 

在这个实例中,我们先用命令  curl g.cn > g.htm 将g.cn的源代码重定向到g.htm,这时curl命令在标准输出(stdout)显示的就不再像例2.2.1那样显示g.cn的源代码,而是

  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   215  100   215    0     0   1934      0 --:--:-- --:--:-- --:--:--  1919

 然后我们使用 cat g.htm命令查看 g.htm的内容

接着我们可以使用 命令 du -h g.htm 查看g.htm的文件大小

[purpleEndurer @ bash ~] du -h g.htm
4.0K    g.htm
[purpleEndurer @ bash ~] 

2.3.2 方法2 使用-o选项:curl -o 文件名 统一资源定位符

[purpleEndurer @ bash ~] curl -o g.html g.cn
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   215  100   215    0     0   1205      0 --:--:-- --:--:-- --:--:--  1201
[purpleEndurer @ bash ~] du -l g.html
4       g.html
[purpleEndurer @ bash ~] cat g.html
<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">
<TITLE>301 Moved</TITLE></HEAD><BODY>
<H1>301 Moved</H1>
The document has moved
<A HREF="https://google.cn/">here</A>.
</BODY></HTML>
[purpleEndurer @ bash ~] 

我们首先使用 curl -o g.html g.cn命令将g.cn的内容保存到g.html,然后分别使用du命令查看g.html的文件大小,用cat命令查看g.html的文件内容。

2.3.3 方法3 使用-O选项:curl -O 统一资源定位符

[purpleEndurer @ bash ~] curl -O g.cn
curl: Remote file name has no length!
curl: try 'curl --help' or 'curl --manual' for more information
[purpleEndurer @ bash ~] 

 居然没有保存下来,原因是我们在这里只指定了g.cn这个域名,而没有指定具体的文件名,所以curl提示远程文件名没有长度。

当我们使用命令curl -O www.g.cn/index.htm,指定了index.htm这个具体的文件名,资源就可以保存下来了:

[purpleEndurer @ bash ~] curl -O www.g.cn/index.htm
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100  1570  100  1570    0     0  23439      0 --:--:-- --:--:-- --:--:-- 23787
[purpleEndurer @ bash ~] ls
Code  index.htm
[purpleEndurer @ bash ~] cat index.htm
<!DOCTYPE html>
<html lang=en>
  <meta charset=utf-8>
  <meta name=viewport content="initial-scale=1, minimum-scale=1, width=device-width">
  <title>Error 404 (Not Found)!!1</title>
  <style>
    *{margin:0;padding:0}html,code{font:15px/22px arial,sans-serif}html{background:#fff;color:#222;padding:15px}body{margin:7% auto 0;max-width:390px;min-height:180px;padding:30px 0 15px}* > body{background:url(//www.google.com/images/errors/robot.png) 100% 5px no-repeat;padding-right:205px}p{margin:11px 0 22px;overflow:hidden}ins{color:#777;text-decoration:none}a img{border:0}@media screen and (max-width:772px){body{background:none;margin-top:0;max-width:none;padding-right:0}}#logo{background:url(//www.google.com/images/branding/googlelogo/1x/googlelogo_color_150x54dp.png) no-repeat;margin-left:-5px}@media only screen and (min-resolution:192dpi){#logo{background:url(//www.google.com/images/branding/googlelogo/2x/googlelogo_color_150x54dp.png) no-repeat 0% 0%/100% 100%;-moz-border-image:url(//www.google.com/images/branding/googlelogo/2x/googlelogo_color_150x54dp.png) 0}}@media only screen and (-webkit-min-device-pixel-ratio:2){#logo{background:url(//www.google.com/images/branding/googlelogo/2x/googlelogo_color_150x54dp.png) no-repeat;-webkit-background-size:100% 100%}}#logo{display:inline-block;height:54px;width:150px}
  </style>
  <a href=//www.google.com/><span id=logo aria-label=Google></span></a>
  <p><b>404.</b> <ins>That’s an error.</ins>
  <p>The requested URL <code>/index.htm</code> was not found on this server.  <ins>That’s all we know.</ins>
[purpleEndurer @ bash ~] du -l index.htm
4       index.htm
[purpleEndurer @ bash ~] 

然后我们可以使用ls、cat和du等命令查看文件index.htm的内容、长度等信息。

 2.3.4 使用xarg命令下载多个URL资源:xargs -n 1 curl -O < URL资源列表文件

例如,有如下博文资源: 

科学设计程序员面试内容,破解“八股文”之弊 的url是: 
https://blog.csdn.net/Purpleendurer/article/details/140781410?spm=1001.2014.3001.5501

生成式 AI 的发展方向,是 Chat 还是 Agent? 的url是: 
https://blog.csdn.net/Purpleendurer/article/details/140731562?spm=1001.2014.3001.5501

“微软蓝屏”事件的警示:内外双修 加强测试 的url是: 
https://blog.csdn.net/Purpleendurer/article/details/140678899?spm=1001.2014.3001.5501

我们可以把以上3篇博文内容全部保存到本地文件。

2.3.4.1 步骤1:把以上资源的url保存到myurl.txt中。

这里我们使用输出重定向功能创建myurl.txt。
 

[purpleEndurer @ bash ~] echo "https://blog.csdn.net/Purpleendurer/article/details/140781410?spm=1001.2014.3001.5501" > myurl.txt
[purpleEndurer @ bash ~] echo "https://blog.csdn.net/Purpleendurer/article/details/140731562?spm=1001.2014.3001.5501" >> myurl.txt
[purpleEndurer @ bash ~] echo "https://blog.csdn.net/Purpleendurer/article/details/140678899?spm=1001.2014.3001.5501" >> myurl.txt
[purpleEndurer @ bash ~] cat myurl.txt
https://blog.csdn.net/Purpleendurer/article/details/140781410?spm=1001.2014.3001.5501
https://blog.csdn.net/Purpleendurer/article/details/140731562?spm=1001.2014.3001.5501
https://blog.csdn.net/Purpleendurer/article/details/140678899?spm=1001.2014.3001.5501
[purpleEndurer @ bash ~] 

2.3.4.2 步骤2:使用命令 xargs -n 1 curl -O < myurl.txt
[purpleEndurer @ bash ~] xargs -n 1 curl -O < myurl.txt
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100  211k    0  211k    0     0   267k      0 --:--:-- --:--:-- --:--:--  267k
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100  225k    0  225k    0     0   262k      0 --:--:-- --:--:-- --:--:--  262k
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100  207k    0  207k    0     0   190k      0 --:--:--  0:00:01 --:--:--  191k
[purpleEndurer @ bash ~] 

我们用ls命令查看当前目录下的内容,

[purpleEndurer @ bash ~] ls
140678899?spm=1001.2014.3001.5501  140731562?spm=1001.2014.3001.5501  140781410?spm=1001.2014.3001.5501  Code  myurl.txt

可以看到新保存下的来的3个文件:

  1. 140678899?spm=1001.2014.3001.5501
  2. 140731562?spm=1001.2014.3001.5501
  3. 140781410?spm=1001.2014.3001.5501

我们可以用cat <文件名> | more 命令查看文件的内容,例如使用命令 cat 140678899?spm=1001.2014.3001.5501 | more 查看文件 140678899?spm=1001.2014.3001.5501 的内容:

[PurpleEndurer @ bash ~] cat 140678899?spm=1001.2014.3001.5501 | more
    <!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="utf-8">
    <link rel="canonical" href="https://blog.csdn.net/Purpleendurer/article/details/140678899"/>
    <meta http-equiv="content-type" content="text/html; charset=utf-8">
    <meta name="renderer" content="webkit"/>
    <meta name="force-rendering" content="webkit"/>
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <meta name="report" content='{"pid": "blog", "spm":"1001.2101"}'>
    <meta name="referrer" content="always">
    <meta http-equiv="Cache-Control" content="no-siteapp" /><link rel="alternate" media="handheld" href="#" />
    <meta name="shenma-site-verification" content="5a59773ab8077d4a62bf469ab966a63b_1497598848">
    <meta name="applicable-device" content="pc">
    <link  href="https://g.csdnimg.cn/static/logo/favicon32.ico"  rel="shortcut icon" type="image/x-icon" />
    <title>“微软蓝屏”事件的警示:内外双修 加强测试_719蓝屏 反思-CSDN博客</title>
    <script>
      (function(){ 
        var el = document.createElement("script"); 
        el.src = "https://s3a.pstatp.com/toutiao/push.js?1abfa13dfe74d72d41d83c86d240de427e7cac50c51ead53b2e79d40c7952a23ed7716d05b4
a0f683a653eab3e214672511de2457e74e99286eb2c33f4428830"; 
        el.id = "ttzz"; 
--More--

,

 这个文件是博文《“微软蓝屏”事件的警示:内外双修 加强测试》的内容。

 2.3.5 利用序列 下载多个URL资源

例如,假设在http://qzone.qq.com.com/pic 下存在如下5个文件:

  1. qzone1.JPG
  2. qzone2.JPG
  3. qzone3.JPG
  4. qzone4.JPG
  5. qzone5.JPG

那么我们可以使用序列 qzone[1-5].JPG 来表示这5个文件。

也就可以使用命令 curl -O http://qzone.qq.com.com/pic/qzone[1-5].JPG 将它们来保存到本地。

2.4 保存cookie到文件:curl -c 文件名  网站

例如,我们想保存http://qzone.qq.com.com的cookie,那么可以用命令 curl -c qzone-cookie.txt http://qzone.qq.com.com 将cookie保存到文件  qzone-cookie.txt 中

[PurpleEndurer @ bash ~] curl -c qzone-cookie.txt http://qzone.qq.com.com
[PurpleEndurer @ bash ~] cat qzone-cookie.txt
# Netscape HTTP Cookie File
# http://curl.haxx.se/docs/http-cookies.html
# This file was generated by libcurl! Edit at your own risk.

qzone.qq.com.com        FALSE   /       FALSE   0       PHPSESSID       r0jv2c60s8bava08eut7mrg017
qzone.qq.com.com        FALSE   /       FALSE   0       XYZSRV  wtc2-a-2
[PurpleEndurer @ bash ~] 

然后我们使用命令 cat qzone-cookie.txt 查看保存到文件 qzone-cookie.txt 中的cookie。

2.5 保存header信息到文件:curl -D 文件 网址

例如,我们想保存http://qzone.qq.com.com的hearder,那么可以用命令 curl -D header.txt http://qzone.qq.com.com 将hearder 保存到文件  header.txt 中

[PurpleEndurer @ bash ~] curl -D header.txt http://qzone.qq.com.com
[PurpleEndurer @ bash ~] cat header.txt
HTTP/1.1 302 Moved Temporarily
Date: Sun, 04 Aug 2024 13:36:17 GMT
Content-Type: text/html; charset=UTF-8
Transfer-Encoding: chunked
Connection: keep-alive
set-cookie: PHPSESSID=ehhc7f1d5a6d2sush8168b0is4; path=/
set-cookie: XYZSRV=wtc2-a-1; path=/
expires: Thu, 19 Nov 1981 08:52:00 GMT
cache-control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
pragma: no-cache
location: https://gen.xyz/
CF-Cache-Status: DYNAMIC
Report-To: {"endpoints":[{"url":"https:\/\/a.nel.cloudflare.com\/report\/v4?s=4FADjXtpF77uXFkcLQM3%2BA1kVadxIq6E5lzX6mYBbCkZgaNcMGk6HGFQ3fw89mKmzYa3%2Bdu0U9SF3%2BNGRQj%2FR4rAJj8dgCr7PX8R0BkmoVHGCL9TfK7rSXF4Zl2agF%2FSDMY%3D"}],"group":"cf-nel","max_age":604800}
NEL: {"success_fraction":0,"report_to":"cf-nel","max_age":604800}
Server: cloudflare
CF-RAY: 8adeef7a2e432018-IAD

[PurpleEndurer @ bash ~] 

然后我们使用命令 cat header.txt 查看保存到文件 header.txt 中的header信息。

2.6 只显示header信息:curl -I 网址

只显示 http://qzone.qq.com.com 的header信息。

[purpleEndurer @ bash ~] curl -I http://qzone.qq.com.com
HTTP/1.1 302 Moved Temporarily
Date: Fri, 09 Aug 2024 05:36:14 GMT
Content-Type: text/html; charset=UTF-8
Connection: keep-alive
set-cookie: PHPSESSID=1a0u2o0nqus3qsuiq3rgl73ij3; path=/
set-cookie: XYZSRV=wtc2-a-1; path=/
expires: Thu, 19 Nov 1981 08:52:00 GMT
cache-control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
pragma: no-cache
location: https://gen.xyz/
CF-Cache-Status: DYNAMIC
Report-To: {"endpoints":[{"url":"https:\/\/a.nel.cloudflare.com\/report\/v4?s=0SWL7nvsoRSezU%2FEElHecC4NrLTKdipvf2grebaYXAr%2BYy8cBQukoNvO1PxeSJHedyUP1ipYH9xCxmGq0MDKCm5D2a8in53DVdtedzWROuBvFut5jYZUu225tVLjYox9tlw%3D"}],"group":"cf-nel","max_age":604800}
NEL: {"success_fraction":0,"report_to":"cf-nel","max_age":604800}
Server: cloudflare
CF-RAY: 8b05632abc9c241a-IAD

[purpleEndurer @ bash ~] 

2.7 显示header和资源内容: curl -i 网址

[purpleEndurer @ bash ~] curl -i http://g.cn
HTTP/1.1 301 Moved Permanently
Location: https://google.cn/
X-Content-Type-Options: nosniff
Server: sffe
Content-Length: 215
X-XSS-Protection: 0
Date: Fri, 09 Aug 2024 05:41:23 GMT
Expires: Fri, 09 Aug 2024 06:11:23 GMT
Cache-Control: public, max-age=1800
Content-Type: text/html; charset=UTF-8
Age: 459

<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">
<TITLE>301 Moved</TITLE></HEAD><BODY>
<H1>301 Moved</H1>
The document has moved
<A HREF="https://google.cn/">here</A>.
</BODY></HTML>
[purpleEndurer @ bash ~] 

 

与2.1相比,返回信息多了header信息。

  • 34
    点赞
  • 53
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 50
    评论
评论 50
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

紫郢剑侠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值