<h1>前言</h1><p>前段時(shí)間群里討論,想實(shí)現(xiàn)某個(gè)文件定時(shí)上傳到服務(wù)器要怎么來(lái)實(shí)現(xiàn)瓶蚂。我記得之前做過(guò)
一個(gè)項(xiàng)目:<strong>為高通的iot模組編寫FOTA功能</strong>:實(shí)現(xiàn)模組可以遠(yuǎn)程下載升級(jí)鏡像包,實(shí)現(xiàn)版本升級(jí)功能宣吱。并當(dāng)時(shí)使用的一個(gè)超級(jí)強(qiáng)大的工具cURL窃这。心血來(lái)潮,決定專門寫一篇文章征候,送給需要的朋友杭攻。</p><p>文章分兩部分</p><ol><li><p>首先介紹cURL的用法;</p></li><li><p class="image-package">實(shí)現(xiàn)一個(gè)定時(shí)上傳日志文件的一個(gè)簡(jiǎn)單的程序疤坝。<img class="uploaded-img" src="https://upload-images.jianshu.io/upload_images/23850874-e40ce603c07bbbfc.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" width="auto" height="auto"/></p></li></ol><h1>概念</h1><p>cURL 是常用的命令行工具兆解,用來(lái)請(qǐng)求 Web 服務(wù)器。它的名字就是客戶端(client)的 URL 工具的意思卒煞。</p><p>cURL 的原作者是 Daniel Stenberg (目前是 cURL 的核心開發(fā)者)痪宰,同時(shí)也是 IETF HTTPbis 工作組的資深成員。Daniel 在 1998 年創(chuàng)建了 curl 項(xiàng)目畔裕,他編寫了最初的 curl 版本衣撬,并創(chuàng)建了 libcurl 庫(kù)。到目前為止扮饶,代碼倉(cāng)庫(kù)包括的 24000 次 commit 有超過(guò)一半是 Daniel 本人提交的具练,他依然是項(xiàng)目的核心開發(fā)者。Daniel 表示已將 curl 視為自己的孩子甜无。</p><p>作為一款強(qiáng)力工具扛点,支持的協(xié)議包括 (DICT, FILE, FTP, FTPS, GOPHER, HTTP, HTTPS, IMAP, IMAPS, LDAP, LDAPS, POP3, POP3S, RTMP, RTSP, SCP, SFTP, SMTP, SMTPS, TELNET and TFTP),還支持POST岂丘、cookies陵究、認(rèn)證、從指定偏移處下載部分文件等功能奥帘,具有用戶代理字符串铜邮、限速、文件大小寨蹋、進(jìn)度條松蒜、cookie支持、用戶認(rèn)證已旧、斷點(diǎn)續(xù)傳等特征秸苗。</p><h1>一、命令的安裝</h1><pre>sudo?apt-get?install?curl</pre><h1>二运褪、cURL命令語(yǔ)法:</h1><pre>curl?[options]?[URL...]</pre><h1>三惊楼、URL格式</h1><p>URL的格式定義要參考 RFC 1808 玖瘸。</p><pre>地址:http://www.w3.org/Addressing/rfc1808.txt《Relative?Uniform?Resource?Locators?》</pre><p>URL由三部分組成:資源類型、存放資源的主機(jī)域名檀咙、資源文件名店读。
也可認(rèn)為由4部分組成:<strong><strong>協(xié)議、主機(jī)攀芯、端口、路徑</strong></strong>URL的一般語(yǔ)法格式為:</p><pre>protocol?://?hostname[:port]?/?path?/?[;parameters][?query]#fragment</pre><p>(帶方括號(hào)[]的為可選項(xiàng))文虏。</p><p/><p>指定使用的傳輸協(xié)議侣诺,下表列出 protocol 屬性的有效方案名稱。 最常用的是HTTP協(xié)議氧秘,它也是WWW中應(yīng)用最廣的協(xié)議年鸳。</p><ul><li><p>file 資源是本地計(jì)算機(jī)上的文件。格式file:///丸相,注意后邊應(yīng)是三個(gè)斜杠搔确。</p></li><li><p>ftp 通過(guò) FTP訪問(wèn)資源。格式 FTP://</p></li><li><p>gopher 通過(guò) Gopher 協(xié)議訪問(wèn)該資源灭忠。</p></li><li><p>http 通過(guò) HTTP 訪問(wèn)該資源膳算。 格式 HTTP://</p></li><li><p>https 通過(guò)安全的 HTTPS 訪問(wèn)該資源。 格式 HTTPS://</p></li><li><p>mailto 資源為電子郵件地址弛作,通過(guò) SMTP 訪問(wèn)涕蜂。 格式 mailto:</p></li><li><p>MMS 通過(guò) 支持MMS(流媒體)協(xié)議的播放該資源。(代表軟件:Windows Media Player)格式 MMS://</p></li><li><p>ed2k 通過(guò) 支持ed2k(專用下載鏈接)協(xié)議的P2P軟件訪問(wèn)該資源映琳。(代表軟件:電驢) 格式 ed2k://</p></li><li><p>Flashget 通過(guò) 支持Flashget:(專用下載鏈接)協(xié)議的P2P軟件訪問(wèn)該資源机隙。(代表軟件:快車) 格式 Flashget://</p></li><li><p class="image-package">thunder 通過(guò) 支持thunder(專用下載鏈接)協(xié)議的P2P軟件訪問(wèn)該資源。(代表軟件:迅雷) 格式 thunder://</p></li><li><p>news 通過(guò) NNTP 訪問(wèn)該資源萨西。</p></li></ul><p/><p class="image-package">是指存放資源的服務(wù)器的域名系統(tǒng)(DNS) 主機(jī)名或 IP 地址有鹿。有時(shí),在主機(jī)名前也可以包含連接到服務(wù)器所需的用戶名和密碼(格式:username:password@hostname)谎脯。</p><p/><p>整數(shù)葱跋,可選,省略時(shí)使用方案的默認(rèn)端口穿肄,各種傳輸協(xié)議都有默認(rèn)的端口號(hào)年局,如http的默認(rèn)端口為80。如果輸入時(shí)省略咸产,則使用默認(rèn)端口號(hào)矢否。有時(shí)候出于安全或其他考慮,可以在服務(wù)器上對(duì)端口進(jìn)行重定義脑溢,即采用非標(biāo)準(zhǔn)端口號(hào)僵朗,此時(shí)赖欣,URL中就不能省略端口號(hào)這一項(xiàng)。</p><p/><p>由零或多個(gè)“/”符號(hào)隔開的字符串验庙,一般用來(lái)表示主機(jī)上的一個(gè)目錄或文件地址顶吮。</p><p/><p>這是用于指定特殊參數(shù)的可選項(xiàng)。</p><p/><p>可選粪薛,用于給動(dòng)態(tài)網(wǎng)頁(yè)(如使用CGI悴了、ISAPI、PHP/JSP/ASP/ASP.NET等技術(shù)制作的網(wǎng)頁(yè))傳遞參數(shù)违寿,可有多個(gè)參數(shù)湃交,用“&”符號(hào)隔開,每個(gè)參數(shù)的名和值用“=”符號(hào)隔開藤巢。</p><p/><p>字符串搞莺,用于指定網(wǎng)絡(luò)資源中的片斷。例如一個(gè)網(wǎng)頁(yè)中有多個(gè)名詞解釋掂咒,可使用fragment直接定位到某一名詞解釋才沧。</p><h1>四、curl命令參數(shù)詳解:</h1><p>由于linux curl功能十分強(qiáng)大绍刮,所以命令參數(shù)十分多温圆,下表只篩選出來(lái)部分常用的參數(shù),更多參數(shù)請(qǐng)運(yùn)行“man curl”命令查看孩革。</p><p>參數(shù)功能-a/--append上傳文件時(shí)捌木,附加到目標(biāo)文件-A/--user-agent設(shè)置用戶代理發(fā)送給服務(wù)器-anyauth可以使用“任何”身份驗(yàn)證方法-b/--cookie <name=string/file>cookie字符串或文件讀取位置--basic使用HTTP基本驗(yàn)證-B/--use-ascii使用ASCII /文本傳輸-c/--cookie-jar操作結(jié)束后把cookie寫入到這個(gè)文件中-C/--continue-at斷點(diǎn)續(xù)轉(zhuǎn)-d/--dataHTTP POST方式傳送數(shù)據(jù)--data-ascii以ascii的方式post數(shù)據(jù)--data-binary以二進(jìn)制的方式post數(shù)據(jù)--negotiate使用HTTP身份驗(yàn)證--digest使用數(shù)字身份驗(yàn)證--disable-eprt禁止使用EPRT或LPRT--disable-epsv禁止使用EPSV-D/--dump-header把header信息寫入到該文件中--egd-file為隨機(jī)數(shù)據(jù)(SSL)設(shè)置EGD socket路徑--tcp-nodelay使用TCP_NODELAY選項(xiàng)-e/--referer來(lái)源網(wǎng)址-E/--cert <cert[:passwd]>客戶端證書文件和密碼 (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要求返回是壓縮的形勢(shì) (using deflate or gzip)--connect-timeout設(shè)置最大請(qǐng)求時(shí)間--create-dirs建立本地目錄的目錄層次結(jié)構(gòu)--crlf上傳是把LF轉(zhuǎn)變成CRLF-f/--fail連接失敗時(shí)不顯示http錯(cuò)誤--ftp-create-dirs如果遠(yuǎn)程目錄不存在,創(chuàng)建遠(yuǎn)程目錄--ftp-method [multicwd/nocwd/singlecwd]控制CWD的使用--ftp-pasv使用 PASV/EPSV 代替端口--ftp-skip-pasv-ip使用PASV的時(shí)候,忽略該IP地址--ftp-ssl嘗試用 SSL/TLS 來(lái)進(jìn)行ftp數(shù)據(jù)傳輸--ftp-ssl-reqd要求用 SSL/TLS 來(lái)進(jìn)行ftp數(shù)據(jù)傳輸-F/--form <name=content>模擬http表單提交數(shù)據(jù)--form-string <name=string>模擬http表單提交數(shù)據(jù)-g/--globoff禁用網(wǎng)址序列和范圍使用{}和[]-G/--get以get的方式來(lái)發(fā)送數(shù)據(jù)-H/--header自定義頭信息傳遞給服務(wù)器--ignore-content-length忽略的HTTP頭信息的長(zhǎng)度-i/--include輸出時(shí)包括protocol頭信息-I/--head只顯示請(qǐng)求頭信息-j/--junk-session-cookies讀取文件進(jìn)忽略session cookie--interface使用指定網(wǎng)絡(luò)接口/地址--krb4使用指定安全級(jí)別的krb4-k/--insecure允許不使用證書到SSL站點(diǎn)-K/--config指定的配置文件讀取-l/--list-only列出ftp目錄下的文件名稱--limit-rate設(shè)置傳輸速度--local-port強(qiáng)制使用本地端口號(hào)-m/--max-time設(shè)置最大傳輸時(shí)間--max-redirs設(shè)置最大讀取的目錄數(shù)--max-filesize設(shè)置最大下載的文件總量-M/--manual顯示全手動(dòng)-n/--netrc從netrc文件中讀取用戶名和密碼--netrc-optional使用 .netrc 或者 URL來(lái)覆蓋-n--ntlm使用 HTTP NTLM 身份驗(yàn)證-N/--no-buffer禁用緩沖輸出-o/--output把輸出寫到該文件中-O/--remote-name把輸出寫到該文件中嫉戚,保留遠(yuǎn)程文件的文件名-p/--proxytunnel使用HTTP代理--proxy-anyauth選擇任一代理身份驗(yàn)證方法--proxy-basic在代理上使用基本身份驗(yàn)證--proxy-digest在代理上使用數(shù)字身份驗(yàn)證--proxy-ntlm在代理上使用ntlm身份驗(yàn)證-P/--ftp-port使用端口地址刨裆,而不是使用PASV-q作為第一個(gè)參數(shù),關(guān)閉 .curlrc-Q/--quote文件傳輸前彬檀,發(fā)送命令到服務(wù)器-r/--range檢索來(lái)自HTTP/1.1或FTP服務(wù)器字節(jié)范圍--range-file讀确小(SSL)的隨機(jī)文件-R/--remote-time在本地生成文件時(shí),保留遠(yuǎn)程文件時(shí)間--retry傳輸出現(xiàn)問(wèn)題時(shí)窍帝,重試的次數(shù)--retry-delay傳輸出現(xiàn)問(wèn)題時(shí)努潘,設(shè)置重試間隔時(shí)間--retry-max-time傳輸出現(xiàn)問(wèn)題時(shí),設(shè)置最大重試時(shí)間-s/--silent靜默模式坤学。不輸出任何東西-S/--show-error顯示錯(cuò)誤--socks4 <host[:port]>用socks4代理給定主機(jī)和端口--socks5 <host[:port]>用socks5代理給定主機(jī)和端口--stderr-t/--telnet-option <OPT=val>Telnet選項(xiàng)設(shè)置--trace對(duì)指定文件進(jìn)行debug--trace-asciiLike --跟蹤但沒(méi)有hex輸出--trace-time跟蹤/詳細(xì)輸出時(shí)疯坤,添加時(shí)間戳-T/--upload-file上傳文件--urlSpet URL to work with-u/--user <user[:password]>設(shè)置服務(wù)器的用戶和密碼-U/--proxy-user <user[:password]>設(shè)置代理用戶名和密碼-w/--write-out [format]什么輸出完成后-x/--proxy <host[:port]>在給定的端口上使用HTTP代理-X/--request指定什么命令-y/--speed-time放棄限速所要的時(shí)間,默認(rèn)為30-Y/--speed-limit停止傳輸速度的限制深浮,速度時(shí)間</p><h1>五压怠、Linux curl命令退出碼:</h1><p class="image-package">下面是linux curl命令的錯(cuò)誤代碼和她們的相應(yīng)的錯(cuò)誤消息,命令執(zhí)行錯(cuò)誤的時(shí)候可以通過(guò)錯(cuò)誤碼來(lái)查看出錯(cuò)原因飞苇,方便開發(fā)調(diào)試菌瘫。</p><p>退 出 碼錯(cuò)誤描述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.</p><h1>六蜗顽、用法演示:</h1><p>為節(jié)省篇幅,部分操作不再貼上執(zhí)行結(jié)果雨让。</p><p/><p>直接在curl命令后加上網(wǎng)址雇盖,就可以看到網(wǎng)頁(yè)源碼。我們以網(wǎng)址www.sina.com為例(選擇該網(wǎng)址栖忠,主要因?yàn)樗木W(wǎng)頁(yè)代碼較短):</p><pre>root@ubuntu:/home/peng#?curl?www.sohu.com<html><head><title>307?Temporary?Redirect</title></head><body?bgcolor="white"><center><h1>307?Temporary?Redirect</h1></center><hr><center>nginx</center></body></html></pre><p>執(zhí)行結(jié)果顯示 <strong>307 Temporary Redirect</strong>崔挖,說(shuō)明該網(wǎng)址需要重定向。</p><p>如果要把這個(gè)網(wǎng)頁(yè)保存下來(lái)庵寞,可以使用<strong>-o</strong>參數(shù)虚汛,這就相當(dāng)于使用wget命令了。</p><pre>curl?-o?[文件名]?www.sohu.com</pre><p/><p>有的網(wǎng)址是自動(dòng)跳轉(zhuǎn)的皇帮。使用<strong>-L</strong>參數(shù),curl就會(huì)跳轉(zhuǎn)到新的網(wǎng)址蛋辈。</p><pre>curl?-L?www.sohu.com</pre><p>鍵入上面的命令属拾,結(jié)果就自動(dòng)跳轉(zhuǎn)為www.sohu.com.cn。</p><p/><p><strong>-i</strong>參數(shù)可以顯示http response的頭信息冷溶,連同網(wǎng)頁(yè)代碼一起渐白。</p><pre>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.3062915<html><head><title>307?Temporary?Redirect</title></head><body?bgcolor="white"><center><h1>307?Temporary?Redirect</h1></center><hr><center>nginx</center></body></html></pre><p><strong>-I</strong>參數(shù)則是只顯示http response的頭信息。</p><p/><p><strong>-v</strong>參數(shù)可以顯示一次http通信的整個(gè)過(guò)程逞频,包括端口連接和http request頭信息纯衍。</p><pre>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:?/>?<?HTTP/1.1?307?Temporary?Redirect<?Content-Type:?text/html<?Content-Length:?180<?Connection:?keep-alive<?Server:?nginx<?Date:?Tue,?25?Aug?2020?10:11:49?GMT<?Location:?https://www.sohu.com/<?FSS-Cache:?from?9855973.18375663.10534247<?FSS-Proxy:?Powered?by?2450292.3564414.3128453<?<html><head><title>307?Temporary?Redirect</title></head><body?bgcolor="white"><center><h1>307?Temporary?Redirect</h1></center><hr><center>nginx</center></body></html>?Connection?#0?to?host?www.sohu.com?left?intact?Closing?connection?#0</pre><p>如果你覺(jué)得上面的信息還不夠,那么下面的命令可以查看更詳細(xì)的通信過(guò)程苗胀。</p><pre>curl?--trace?output.txt?www.sohu.com</pre><p>或者</p><pre>curl?--trace-ascii?output.txt?www.sohu.com</pre><p>運(yùn)行后襟诸,請(qǐng)打開output.txt文件查看。</p><p/><p>發(fā)送表單信息有GET和POST兩種方法基协。GET方法相對(duì)簡(jiǎn)單歌亲,只要把數(shù)據(jù)附在網(wǎng)址后面就行。</p><pre>curl?example.com/form.cgi?data=xxx</pre><p>POST方法必須把數(shù)據(jù)和網(wǎng)址分開澜驮,curl就要用到--data參數(shù)陷揪。</p><pre>curl?-X?POST?--data?"data=xxx"?example.com/form.cgi</pre><p>如果你的數(shù)據(jù)沒(méi)有經(jīng)過(guò)表單編碼,還可以讓curl為你編碼杂穷,參數(shù)是<strong>--data-urlencode</strong>悍缠。</p><pre>curl?-X?POST--data-urlencode?"date=April?1"?example.com/form.cgi</pre><p/><p>curl默認(rèn)的HTTP動(dòng)詞是GET,使用<strong>-X</strong>參數(shù)可以支持其他動(dòng)詞耐量。</p><pre>curl?-X?POST?www.example.comcurl?-X?DELETE?www.example.com</pre><p/><p>假定文件上傳的表單是下面這樣:</p><pre><form?method="POST"?enctype='multipart/form-data'?action="upload.cgi">?<input?type=file?name=upload>?<input?type=submit?name=press?value="OK"></form></pre><p>你可以用curl這樣上傳文件:</p><pre>curl?--form?upload=@localfilename?--form?press=OK?[URL]</pre><p/><p>有時(shí)你需要在http request頭信息中飞蚓,提供一個(gè)referer字段,表示你是從哪里跳轉(zhuǎn)過(guò)來(lái)的廊蜒。</p><pre>curl?--referer?http://www.example.com?http://www.example.com</pre><p/><p>這個(gè)字段是用來(lái)表示客戶端的設(shè)備信息玷坠。服務(wù)器有時(shí)會(huì)根據(jù)這個(gè)字段蜗搔,針對(duì)不同設(shè)備,返回不同格式的網(wǎng)頁(yè)八堡,比如手機(jī)版和桌面版樟凄。</p><p>iPhone4的User Agent是</p><pre>Mozilla/5.0?(iPhone;?U;?CPU?iPhone?OS?4_0?like?Mac?OS?X;?en-us)?AppleWebKit/532.9?(KHTML,?like?Gecko)?Version/4.0.5?Mobile/8A293?Safari/6531.22.7</pre><p>curl可以這樣模擬:</p><pre>curl?--user-agent?"[User?Agent]"?[URL]</pre><p/><p>使用<strong>--cookie</strong>參數(shù),可以讓curl發(fā)送cookie兄渺。</p><pre>curl?--cookie?"name=xxx"?www.example.com</pre><p>至于具體的cookie的值缝龄,可以從http response頭信息的<strong>Set-Cookie</strong>字段中得到。</p><p><strong>-c cookie-file</strong>可以保存服務(wù)器返回的cookie到文件挂谍,<strong>-b cookie-file</strong>可以使用這個(gè)文件作為cookie信息叔壤,進(jìn)行后續(xù)的請(qǐng)求。</p><pre>curl?-c?cookies?http://example.comcurl?-b?cookies?http://example.com</pre><p/><p>有時(shí)需要在http request之中口叙,自行增加一個(gè)頭信息炼绘。<strong>--header</strong>參數(shù)就可以起到這個(gè)作用。</p><pre>$?curl?--header?"Content-Type:application/json"?http://example.com</pre><p/><p>使用curl選項(xiàng) -u 可以完成HTTP或者FTP的認(rèn)證妄田,可以指定密碼俺亮,也可以不指定密碼在后續(xù)操作中輸入密碼:</p><pre>curl?-u?user:pwd?http://man.linuxde.netcurl?-u?user?http://man.linuxde.net</pre><p/><p/><pre>curl?ftp://www.xxx.com/?--user?name:passwdcurl?ftp://www.xxx.com/?–u?name:passwd?#簡(jiǎn)潔寫法curl?ftp://name:passwd@www.xxx.com?#簡(jiǎn)潔寫法2</pre><p>例如:在IP地址192.168.43.117上搭建FTP服務(wù)器,并設(shè)置用戶名為<strong>user</strong>疟呐,密碼為<strong>123456</strong>現(xiàn)在我們要顯示服務(wù)器上根目錄下的所有文件信息脚曾,命令如下:</p><pre>curl?-u?user:123456?ftp://192.168.43.117</pre><p class="image-package">執(zhí)行結(jié)果如下:<img class="uploaded-img" src="https://upload-images.jianshu.io/upload_images/23850874-e289c754aa9f78df.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" width="auto" height="auto"/><strong>簡(jiǎn)潔寫法:</strong></p><pre>curl?ftp://user:123456@192.168.43.117</pre><p class="image-package">執(zhí)行結(jié)果如下:<img class="uploaded-img" src="https://upload-images.jianshu.io/upload_images/23850874-f1ce602bee745b9c.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" width="auto" height="auto"/></p><p/><pre>curl?ftp://www.xxx.com?–u?name:passwd?-s</pre><p/><p><strong>格式</strong></p><pre>curl?ftp://www.xxx.com/size.zip?–u?name:passwd?-o?size.zip</pre><p>示例如下:
從服務(wù)器的根目錄下下載文件test.c,保存到本地启具,本地文件名也為test.c本讥。
【注意】如果沒(méi)有-o選項(xiàng),程序會(huì)吧數(shù)據(jù)流定向到stdout鲁冯,即直接把文件內(nèi)容顯示到終端上拷沸。</p><pre>curl?ftp://user:123456@192.168.43.117/test.c?-o?test.c</pre><p class="image-package">執(zhí)行結(jié)果如下:<img class="uploaded-img" src="https://upload-images.jianshu.io/upload_images/23850874-750cd1d7f5e41272.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" width="auto" height="auto"/><strong>簡(jiǎn)潔模式</strong></p><pre>curl?-u?user:123456?ftp://192.168.43.117/list.h?-o?list.h</pre><p class="image-package">執(zhí)行結(jié)果如下:<img class="uploaded-img" src="https://upload-images.jianshu.io/upload_images/23850874-cc2f1368c24e46e1.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" width="auto" height="auto"/></p><p/><pre>curl?–u?name:passwd?-T?size.mp3?ftp://www.xxx.com/mp3/</pre><p>舉例如下:</p><pre>curl?-u?user:123456?ftp://192.168.43.117/?-T?list.h</pre><p class="image-package"><img class="uploaded-img" src="https://upload-images.jianshu.io/upload_images/23850874-f94639bdf6964f4f.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" width="auto" height="auto"/>可以看到文件并沒(méi)有上傳成功,返回錯(cuò)誤碼是25薯演,參考第五章</p><pre>25?FTP?couldn't?STOR?file.?The?server?denied?the?STOR?operation,?used?for?FTP?uploading.</pre><p>可知堵漱,是因?yàn)榉?wù)器沒(méi)有賦予存儲(chǔ)的權(quán)限,所以設(shè)置服務(wù)器的write權(quán)限即可涣仿。</p><p class="image-package"><img class="uploaded-img" src="https://upload-images.jianshu.io/upload_images/23850874-e0e39b72087c0b7c.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" width="auto" height="auto"/>在這里插入圖片描述</p><p/><pre>curl?–u?name:passwd?ftp://www.xxx.com/?-X?'DELE?mp3/size.mp3'</pre><p/><pre>curl?–u?name:passwd?ftp://www.xxx.com/img/[1-10].gif?–O?#O字母大寫</pre><p/><pre>curl?–u?name:passwd?ftp://www.xxx.com/img/[one,two,three].jpg?–O?#O字母大寫</pre><h1>六勤庐、實(shí)現(xiàn)日志文件定時(shí)上傳</h1><p/><ol><li><p>程序運(yùn)行時(shí)要記錄當(dāng)前日志文件的最后修改時(shí)間;</p></li><li><p>每個(gè)10秒鐘就檢查下log文件是否被修改好港,如果沒(méi)有被修改就休眠10秒鐘愉镰;</p></li><li><p>如果log文件被修改了,就將當(dāng)前的日志文件拷貝成備份文件钧汹,備份文件名字加上當(dāng)前時(shí)間丈探;</p></li><li><p>通過(guò)curl發(fā)送給ftp服務(wù)器;</p></li><li><p>刪除備份文件拔莱,重復(fù)步驟2碗降。</p></li></ol><p/><p class="image-package"><img class="uploaded-img" src="https://upload-images.jianshu.io/upload_images/23850874-f6c389e5bda0f163.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" width="auto" height="auto"/>在這里插入圖片描述</p><p/><p/><p>首先記錄當(dāng)前l(fā)og文件時(shí)間隘竭,并記錄到全局變量<strong>last_mtime</strong>中。</p><p/><p>讀取文件最后修改時(shí)間讼渊,并和<strong>last_mtime</strong>進(jìn)行比較动看,如果相同就返回0,不同就返回1.</p><p/><p>將當(dāng)前的日志文件拷貝成備份文件爪幻,備份文件名字加上當(dāng)前時(shí)間菱皆。</p><p/><p>得到對(duì)應(yīng)文件的屬性信息,存放到struct stat結(jié)構(gòu)體變量中挨稿。</p><p/><p>執(zhí)行參數(shù)中字符串對(duì)應(yīng)的命令</p><p/><pre>/???Copyright?(C)???公眾號(hào):?yikoulinux??/#include?<sys/stat.h>#include?<stdio.h>#include?<stdlib.h>#include?<unistd.h>#include?<time.h>?typedef?struct?stat?ST;unsigned?long?last_mtime;/用戶名密碼暫時(shí)寫死仇轻,實(shí)際應(yīng)該保存在配置文件/char?name[32]="user";char?pass[32]?="123456";char?ip[32]?????="192.168.43.117";char?filename[32]="t.log";char?dstfile[256]??={0};int?init(void){?//準(zhǔn)備結(jié)構(gòu)體?ST?status;??//調(diào)用stat函數(shù)?int?res?=?stat(filename,&status);?if(-1?==?res)?{??perror("error:open?file?fail\n");??return?0;?}?last_mtime?=?status.st_mtime;?printf("init?time:%s?\n",ctime(&last_mtime));?return?1;}?int??check_file_change(void){?//準(zhǔn)備結(jié)構(gòu)體?ST?status;??//調(diào)用stat函數(shù)?int?res?=?stat(filename,&status);?if(-1?==?res)?{??perror("error:open?file?fail\n");??return?0;?}//?printf("old:%s?new:%s",ctime(&last_mtime),ctime(&status.st_mtime));?if(last_mtime?==?status.st_mtime)?{??printf("file?not?change\n");??return?0;?}else{??printf("file?updated\n");???last_mtime?=?status.st_mtime;??return?1;?}}void?file_name_add_time(void){?ST?status;?time_t?t;???struct?tm?*tblock;??char?cmd[1024]={0};???t?=?time(NULL);?tblock?=?localtime(&t);??sprintf(dstfile,"t-%d-%d-%d-%d-%d-%d.log",??tblock->tm_year+1900,??tblock->tm_mon,??tblock->tm_mday,??tblock->tm_hour,??tblock->tm_min,??tblock->tm_sec);?sprintf(cmd,"cp?%s?%s",filename,dstfile);//?printf("cdm=%s\n",cmd);?system(cmd);}int?main(void){?char?cmd[1024]={0};?init();?while(1)?{???if(check_file_change()?==?1)??{???file_name_add_time();???sprintf(cmd,"curl?-u?%s:%s?ftp://%s/?-T?%s",name,pass,ip,dstfile);?//??printf("cdm=%s\n",cmd);???system(cmd);???unlink(dstfile);??}??sleep(10);??}}</pre><p/><p class="image-package"><strong>第一步:</strong><img class="uploaded-img" src="https://upload-images.jianshu.io/upload_images/23850874-bec5b9410e200589.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" width="auto" height="auto"/>因?yàn)閘og文件沒(méi)有被修改過(guò),所以程序不會(huì)上傳奶甘。</p><p class="image-package"><strong>第二步:</strong>手動(dòng)輸入字符串 yikoulinux 到日志文件 t.log中篷店。<img class="uploaded-img" src="https://upload-images.jianshu.io/upload_images/23850874-fcc3e354ffaa1bd8.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" width="auto" height="auto"/>第三步:
因?yàn)槲募l(fā)生了改變,所以打印“file updated”臭家,同時(shí)可以看到curl上傳文件的log信息疲陕。<img class="uploaded-img" src="https://upload-images.jianshu.io/upload_images/23850874-1a4a66870b2ba90e.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" width="auto" height="auto"/>以下是FTP服務(wù)器的根目錄,可以看到侣监,上傳的日志文件:<strong>t-2020-7-26-1-19-45.log</strong>。<img class="uploaded-img" src="https://upload-images.jianshu.io/upload_images/23850874-8ec2785d5c87df3f.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" width="auto" height="auto"/></p><p/><ol><li><p>配置信息臣淤,直接在代碼中寫死橄霉,通常應(yīng)該從配置文件中讀取,為方便讀者閱讀邑蒋,本代碼沒(méi)有增加該功能姓蜂;</p></li><li><p class="image-package">FTP服務(wù)器搭建,本文沒(méi)有說(shuō)明医吊,相關(guān)文件比較多钱慢,大家可以自行搜索,一口君用的是File zilla卿堂;<img class="uploaded-img" src="https://upload-images.jianshu.io/upload_images/23850874-611887dd4bb294cb.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" width="auto" height="auto"/></p></li><li><p>通常這種需要長(zhǎng)時(shí)間運(yùn)行的程序束莫,需要設(shè)置成守護(hù)進(jìn)程,本文沒(méi)有添加相應(yīng)功能草描,讀者可以自行搜索览绿。如果強(qiáng)烈要求可以單開一篇詳細(xì)介紹。</p></li><li><p>代碼中time的管理函數(shù)穗慕,請(qǐng)讀者自行搜索相關(guān)文章饿敲。</p></li><li><p>curl也提供了相關(guān)的函數(shù)庫(kù)curl.lib,如果要實(shí)現(xiàn)更靈活的功能可以使用對(duì)應(yīng)的api逛绵。</p></li><li><p>之所以先把文件拷貝成備份文件怀各,主要是考慮其他模塊隨時(shí)可能修改日志文件倔韭,起到一定保護(hù)作用。</p></li></ol><p>想和博主交流瓢对,請(qǐng)關(guān)注公眾號(hào)「一口Linux」</p><p>
</p>
利用Linux命令cURL實(shí)現(xiàn)文件定時(shí)上傳到ftp服務(wù)器的小程序,實(shí)用
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
- 文/潘曉璐 我一進(jìn)店門桑滩,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人幌氮,你說(shuō)我怎么就攤上這事该互【禄” “怎么了?”我有些...
- 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)太防。 經(jīng)常有香客問(wèn)我,道長(zhǎng)讳嘱,這世上最難降的妖魔是什么沥潭? 我笑而不...
- 正文 為了忘掉前任钝鸽,我火速辦了婚禮拔恰,結(jié)果婚禮上基括,老公的妹妹穿的比我還像新娘风皿。我一直安慰自己桐款,他們只是感情好魔眨,可當(dāng)我...
- 文/花漫 我一把揭開白布冰沙。 她就那樣靜靜地躺著拓挥,像睡著了一般袋励。 火紅的嫁衣襯著肌膚如雪茬故。 梳的紋絲不亂的頭發(fā)上磺芭,一...
- 那天钾腺,我揣著相機(jī)與錄音,去河邊找鬼己英。 笑死吴旋,一個(gè)胖子當(dāng)著我的面吹牛荣瑟,可吹牛的內(nèi)容都是我干的褂傀。 我是一名探鬼主播,決...
- 文/蒼蘭香墨 我猛地睜開眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼未檩!你這毒婦竟也來(lái)了冤狡?” 一聲冷哼從身側(cè)響起项棠,我...
- 序言:老撾萬(wàn)榮一對(duì)情侶失蹤合瓢,失蹤者是張志新(化名)和其女友劉穎晴楔,沒(méi)想到半個(gè)月后税弃,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體凑队,經(jīng)...
- 正文 獨(dú)居荒郊野嶺守林人離奇死亡西壮,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
- 正文 我和宋清朗相戀三年贡定,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了缓待。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片旋炒。...
- 正文 年R本政府宣布,位于F島的核電站铲觉,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜哆窿,卻給世界環(huán)境...
- 文/蒙蒙 一强衡、第九天 我趴在偏房一處隱蔽的房頂上張望漩勤。 院中可真熱鬧,春花似錦究飞、人聲如沸亿傅。這莊子的主人今日做“春日...
- 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至嘴脾,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間蔬墩,已是汗流浹背译打。 一陣腳步聲響...
- 正文 我出身青樓祖能,卻偏偏與公主長(zhǎng)得像与境,于是被迫代替她去往敵國(guó)和親凳寺。 傳聞我的和親對(duì)象是個(gè)殘疾皇子摹菠,可洞房花燭夜當(dāng)晚...