curl http header_利用Linux命令cURL实现文件定时上传到ftp服务器的小程序,实用

前言

前段时间群里讨论,想实现某个文件定时上传到服务器要怎么来实现。我记得之前做过 一个项目:为高通的iot模组编写FOTA功能:实现模组可以远程下载升级镜像包,实现版本升级功能。并当时使用的一个超级强大的工具cURL。心血来潮,决定专门写一篇文章,送给需要的朋友。

文章分两部分

  1. 首先介绍cURL的用法;
  2. 实现一个定时上传日志文件的一个简单的程序。

概念

cURL 是常用的命令行工具,用来请求 Web 服务器。它的名字就是客户端(client)的 URL 工具的意思。

cURL 的原作者是 Daniel Stenberg (目前是 cURL 的核心开发者),同时也是 IETF HTTPbis 工作组的资深成员。Daniel 在 1998 年创建了 curl 项目,他编写了最初的 curl 版本,并创建了 libcurl 库。到目前为止,代码仓库包括的 24000 次 commit 有超过一半是 Daniel 本人提交的,他依然是项目的核心开发者。Daniel 表示已将 curl 视为自己的孩子。

作为一款强力工具,支持的协议包括 (DICT, FILE, FTP, FTPS, GOPHER, HTTP, HTTPS, IMAP, IMAPS, LDAP, LDAPS, POP3, POP3S, RTMP, RTSP, SCP, SFTP, SMTP, SMTPS, TELNET and TFTP),还支持POST、cookies、认证、从指定偏移处下载部分文件等功能,具有用户代理字符串、限速、文件大小、进度条、cookie支持、用户认证、断点续传等特征。

一、命令的安装

sudo apt-get install curl

二、cURL命令语法:

curl [options] [URL...]

三、URL格式

URL的格式定义要参考 RFC 1808 。

地址:http://www.w3.org/Addressing/rfc1808.txt《Relative Uniform Resource Locators 》

URL由三部分组成:资源类型、存放资源的主机域名、资源文件名。 也可认为由4部分组成:协议、主机、端口、路径URL的一般语法格式为:

protocol :// hostname[:port] / path / [;parameters][?query]#fragment

(带方括号[]的为可选项)。

指定使用的传输协议,下表列出 protocol 属性的有效方案名称。 最常用的是HTTP协议,它也是WWW中应用最广的协议。

  • file 资源是本地计算机上的文件。格式file:///,注意后边应是三个斜杠。
  • ftp 通过 FTP访问资源。格式 FTP://
  • gopher 通过 Gopher 协议访问该资源。
  • http 通过 HTTP 访问该资源。 格式 HTTP://
  • https 通过安全的 HTTPS 访问该资源。 格式 HTTPS://
  • mailto 资源为电子邮件地址,通过 SMTP 访问。 格式 mailto:
  • MMS 通过 支持MMS(流媒体)协议的播放该资源。(代表软件:Windows Media Player)格式 MMS://
  • ed2k 通过 支持ed2k(专用下载链接)协议的P2P软件访问该资源。(代表软件:电驴) 格式 ed2k://
  • Flashget 通过 支持Flashget:(专用下载链接)协议的P2P软件访问该资源。(代表软件:快车) 格式 Flashget://
  • thunder 通过 支持thunder(专用下载链接)协议的P2P软件访问该资源。(代表软件:迅雷) 格式 thunder://
  • news 通过 NNTP 访问该资源。

是指存放资源的服务器的域名系统(DNS) 主机名或 IP 地址。有时,在主机名前也可以包含连接到服务器所需的用户名和密码(格式:username:password@hostname)。

整数,可选,省略时使用方案的默认端口,各种传输协议都有默认的端口号,如http的默认端口为80。如果输入时省略,则使用默认端口号。有时候出于安全或其他考虑,可以在服务器上对端口进行重定义,即采用非标准端口号,此时,URL中就不能省略端口号这一项。

由零或多个“/”符号隔开的字符串,一般用来表示主机上的一个目录或文件地址。

这是用于指定特殊参数的可选项。

可选,用于给动态网页(如使用CGI、ISAPI、PHP/JSP/ASP/ASP.NET等技术制作的网页)传递参数,可有多个参数,用“&”符号隔开,每个参数的名和值用“=”符号隔开。

字符串,用于指定网络资源中的片断。例如一个网页中有多个名词解释,可使用fragment直接定位到某一名词解释。

四、curl命令参数详解:

由于linux curl功能十分强大,所以命令参数十分多,下表只筛选出来部分常用的参数,更多参数请运行“man curl”命令查看。

参数功能-a/--append上传文件时,附加到目标文件-A/--user-agent设置用户代理发送给服务器-anyauth可以使用“任何”身份验证方法-b/--cookie cookie字符串或文件读取位置--basic使用HTTP基本验证-B/--use-ascii使用ASCII /文本传输-c/--cookie-jar操作结束后把cookie写入到这个文件中-C/--continue-at断点续转-d/--dataHTTP POST方式传送数据--data-ascii以ascii的方式post数据--data-binary以二进制的方式post数据--negotiate使用HTTP身份验证--digest使用数字身份验证--disable-eprt禁止使用EPRT或LPRT--disable-epsv禁止使用EPSV-D/--dump-header把header信息写入到该文件中--egd-file为随机数据(SSL)设置EGD socket路径--tcp-nodelay使用TCP_NODELAY选项-e/--referer来源网址-E/--cert 客户端证书文件和密码 (SSL)--cert-type证书文件类型 (DER/PEM/ENG) (SSL)--key私钥文件名 (SSL)--key-type私钥文件类型 (DER/PEM/ENG) (SSL)--pass私钥密码 (SSL)--engine加密引擎使用 (SSL). "--engine list" for list--cacertCA证书 (SSL)--capathCA目录 (made using c_rehash) to verify peer against (SSL)--ciphersSSL密码--compressed要求返回是压缩的形势 (using deflate or gzip)--connect-timeout设置最大请求时间--create-dirs建立本地目录的目录层次结构--crlf上传是把LF转变成CRLF-f/--fail连接失败时不显示http错误--ftp-create-dirs如果远程目录不存在,创建远程目录--ftp-method [multicwd/nocwd/singlecwd]控制CWD的使用--ftp-pasv使用 PASV/EPSV 代替端口--ftp-skip-pasv-ip使用PASV的时候,忽略该IP地址--ftp-ssl尝试用 SSL/TLS 来进行ftp数据传输--ftp-ssl-reqd要求用 SSL/TLS 来进行ftp数据传输-F/--form 模拟http表单提交数据--form-string 模拟http表单提交数据-g/--globoff禁用网址序列和范围使用{}和[]-G/--get以get的方式来发送数据-H/--header自定义头信息传递给服务器--ignore-content-length忽略的HTTP头信息的长度-i/--include输出时包括protocol头信息-I/--head只显示请求头信息-j/--junk-session-cookies读取文件进忽略session cookie--interface使用指定网络接口/地址--krb4使用指定安全级别的krb4-k/--insecure允许不使用证书到SSL站点-K/--config指定的配置文件读取-l/--list-only列出ftp目录下的文件名称--limit-rate设置传输速度--local-port强制使用本地端口号-m/--max-time设置最大传输时间--max-redirs设置最大读取的目录数--max-filesize设置最大下载的文件总量-M/--manual显示全手动-n/--netrc从netrc文件中读取用户名和密码--netrc-optional使用 .netrc 或者 URL来覆盖-n--ntlm使用 HTTP NTLM 身份验证-N/--no-buffer禁用缓冲输出-o/--output把输出写到该文件中-O/--remote-name把输出写到该文件中,保留远程文件的文件名-p/--proxytunnel使用HTTP代理--proxy-anyauth选择任一代理身份验证方法--proxy-basic在代理上使用基本身份验证--proxy-digest在代理上使用数字身份验证--proxy-ntlm在代理上使用ntlm身份验证-P/--ftp-port使用端口地址,而不是使用PASV-q作为第一个参数,关闭 .curlrc-Q/--quote文件传输前,发送命令到服务器-r/--range检索来自HTTP/1.1或FTP服务器字节范围--range-file读取(SSL)的随机文件-R/--remote-time在本地生成文件时,保留远程文件时间--retry传输出现问题时,重试的次数--retry-delay传输出现问题时,设置重试间隔时间--retry-max-time传输出现问题时,设置最大重试时间-s/--silent静默模式。不输出任何东西-S/--show-error显示错误--socks4 用socks4代理给定主机和端口--socks5 用socks5代理给定主机和端口--stderr-t/--telnet-option Telnet选项设置--trace对指定文件进行debug--trace-asciiLike --跟踪但没有hex输出--trace-time跟踪/详细输出时,添加时间戳-T/--upload-file上传文件--urlSpet URL to work with-u/--user 设置服务器的用户和密码-U/--proxy-user 设置代理用户名和密码-w/--write-out [format]什么输出完成后-x/--proxy 在给定的端口上使用HTTP代理-X/--request指定什么命令-y/--speed-time放弃限速所要的时间,默认为30-Y/--speed-limit停止传输速度的限制,速度时间

五、Linux curl命令退出码:

下面是linux curl命令的错误代码和她们的相应的错误消息,命令执行错误的时候可以通过错误码来查看出错原因,方便开发调试。

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

六、用法演示:

为节省篇幅,部分操作不再贴上执行结果。

直接在curl命令后加上网址,就可以看到网页源码。我们以网址www.sina.com为例(选择该网址,主要因为它的网页代码较短):

root@ubuntu:/home/peng# curl www.sohu.com307 Temporary Redirect

307 Temporary Redirect

nginx

执行结果显示 307 Temporary Redirect,说明该网址需要重定向。

如果要把这个网页保存下来,可以使用-o参数,这就相当于使用wget命令了。

curl -o [文件名] www.sohu.com

有的网址是自动跳转的。使用-L参数,curl就会跳转到新的网址。

curl -L www.sohu.com

键入上面的命令,结果就自动跳转为www.sohu.com.cn。

-i参数可以显示http response的头信息,连同网页代码一起。

root@ubuntu:/home/peng/driver/test#  curl -i www.sohu.comHTTP/1.1 307 Temporary RedirectContent-Type: text/htmlContent-Length: 180Connection: keep-aliveServer: nginxDate: Tue, 25 Aug 2020 10:10:54 GMTLocation: https://www.sohu.com/FSS-Cache: from 9790436.18244590.10468709FSS-Proxy: Powered by 2384755.3433341.3062915307 Temporary Redirect

307 Temporary Redirect

nginx

-I参数则是只显示http response的头信息。

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

root@ubuntu:/home/peng/driver/test#  curl -v www.sohu.com* About to connect() to www.sohu.com port 80 (#0)*   Trying 240e:83:201:3700::5... connected> GET / HTTP/1.1> User-Agent: curl/7.22.0 (i686-pc-linux-gnu) libcurl/7.22.0 OpenSSL/1.0.1 zlib/1.2.3.4 libidn/1.23 librtmp/2.3> Host: www.sohu.com> Accept: */*> 307 Temporary Redirect

307 Temporary Redirect

nginx
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值