Linux命令cURL詳解+定時上傳檔案到FTP伺服器(送原始碼)

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格式

在WWW上,每一資訊資源都有統一的且在網上唯一的地址,該地址就叫URL(Uniform Resource Locator,統一資源定位器),它是WWW的統一資源定位標誌,就是指網路地址。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(協議)

指定使用的傳輸協議,下表列出 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 訪問該資源。hostname(主機名)

是指存放資源的伺服器的域名系統(DNS) 主機名或 IP 地址。有時,在主機名前也可以包含連線到伺服器所需的使用者名稱和密碼(格式:username:password@hostname)。

port(埠號)

整數,可選,省略時使用方案的預設埠,各種傳輸協議都有預設的埠號,如http的預設埠為80。如果輸入時省略,則使用預設埠號。有時候出於安全或其他考慮,可以在伺服器上對埠進行重定義,即採用非標準埠號,此時,URL中就不能省略埠號這一項。

path(路徑)

由零或多個“/”符號隔開的字串,一般用來表示主機上的一個目錄或檔案地址。

parameters(引數)

這是用於指定特殊引數的可選項。

query(查詢)

可選,用於給動態網頁(如使用CGI、ISAPI、PHP/JSP/ASP/ASP。NET等技術製作的網頁)傳遞引數,可有多個引數,用“&”符號隔開,每個引數的名和值用“=”符號隔開。

fragment(資訊片斷)

字串,用於指定網路資源中的片斷。例如一個網頁中有多個名詞解釋,可使用fragment直接定位到某一名詞解釋。

四、curl命令引數詳解:

由於linux curl功能十分強大,所以命令引數十分多,下表只篩選出來部分常用的引數,更多引數請執行“man curl”命令檢視。

在以下選項中,(H) 表示僅適用 HTTP/HTTPS ,(F) 表示僅適用於 FTP

引數1引數2說明

——anyauth選擇 “any” 認證方法 (H)-a,——append新增要上傳的檔案 (F/SFTP)

——basic使用HTTP基礎認證(Basic Authentication)(H)

——cacert FILECA 證書,用於每次請求認證 (SSL)

——capath DIRCA 證書目錄 (SSL)-E,——cert CERT[:PASSWD]客戶端證書檔案及密碼 (SSL)

——cert-type TYPE證書檔案型別 (DER/PEM/ENG) (SSL)

——ciphers LISTSSL 秘鑰 (SSL)

——compressed請求壓縮 (使用 deflate 或 gzip)-K,——config FILE指定配置檔案

——connect-timeout SECONDS連線超時設定-C,——continue-at OFFSET斷點續轉-b,——cookie STRING/FILECookies字串或讀取Cookies的檔案位置 (H)-c,——cookie-jar FILE操作結束後,要寫入 Cookies 的檔案位置 (H)

——create-dirs建立必要的本地目錄層次結構

——crlf在上傳時將 LF 轉寫為 CRLF

——crlfile FILE從指定的檔案獲得PEM格式CRL列表-d,——data DATAHTTP POST 資料 (H)

——data-ascii DATA ASCII編碼 HTTP POST 資料 (H)

——data-binary DATA binary編碼 HTTP POST 資料 (H)

——data-urlencode DATA url編碼 HTTP POST 資料 (H)

——delegation STRING GSS-API委託許可權

——digest使用數字身份驗證 (H)

——disable-eprt禁止使用 EPRT 或 LPRT (F)

——disable-epsv禁止使用 EPSV (F)-D,——dump-header FILE將頭資訊寫入指定的檔案

——egd-file FILE為隨機資料設定EGD socket路徑(SSL)

——engine ENGINGE加密引擎 (SSL)。 “——engine list” 指定列表-f,——fail連線失敗時不顯示HTTP錯誤資訊 (H)-F,——form CONTENT模擬 HTTP 表單資料提交(multipart POST) (H)

——form-string STRING模擬 HTTP 表單資料提交 (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-control ftp登入時需要 SSL/TLS (F)-G,——get使用 HTTP GET 方法傳送 -d 資料 (H)-g,——globoff禁用的 URL 佇列 及範圍使用 {} 和 []-H,——header LINE要傳送到服務端的自定義請求頭 (H)-I,——head僅顯示響應文件頭-h,——help顯示幫助-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 FILE命令的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傳送郵件到這個接收人(s)

——mail-auth AUTH原始電子郵件的起始地址

——max-filesize BYTES下載的最大檔案大小 (H/F)

——max-redirs NUM最大重定向數 (H)-m,——max-time SECONDS允許的最多傳輸時間

——metalink處理指定的URL上的XML檔案

——negotiate使用 HTTP Negotiate 認證 (H)-n,——netrc必須從 。netrc 檔案讀取使用者名稱和密碼

——netrc-optional使用 。netrc 或 URL; 將重寫 -n 引數

——netrc-file FILE設定要使用的 netrc 檔名-N,——no-buffer禁用輸出流的快取

——no-keepalive禁用 connection 的 keepalive

——no-sessionid禁止重複使用 SSL session-ID (SSL)

——noproxy不使用代理的主機列表

——ntlm使用 HTTP NTLM 認證 (H)-o,——output FILE將輸出寫入檔案,而非 stdout

——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在代理上使用 Basic 認證 (H)

——proxy-digest在代理上使用 Digest 認證 (H)

——proxy-negotiate在代理上使用 Negotiate 認證 (H)

——proxy-ntlm在代理上使用 NTLM 認證 (H)-U,——proxy-user USER[:PASSWORD]代理使用者名稱及密碼

——proxy1。0 HOST[:PORT]在指定的埠上使用 HTTP/1。0 代理-p,——proxytunnel使用HTTP代理 (用於 CONNECT)

——pubkey KEY公鑰檔名 (SSH)-Q,——quote CMD在傳輸開始前向伺服器傳送命令 (F/SFTP)

——random-file FILE讀取隨機資料的檔案 (SSL)-r,——range RANGE僅檢索範圍內的位元組

——raw使用原始HTTP傳輸,而不使用編碼 (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出現問題時的重試次數

——retry-delay SECONDS重試時的延時時長

——retry-max-time SECONDS僅在指定時間段內重試-S,——show-error顯示錯誤。 在選項 -s 中,當 curl 出現錯誤時將顯示-s,——silentSilent模式。不輸出任務內容

——socks4 HOST[:PORT]在指定的 host + port 上使用 SOCKS4 代理

——socks4a HOST[:PORT]在指定的 host + port 上使用 SOCKSa 代理

——socks5 HOST[:PORT]在指定的 host + port 上使用 SOCKS5 代理

——socks5-hostname HOST[:PORT] SOCKS5代理,指定使用者名稱、密碼

——socks5-gssapi-service NAME為gssapi使用SOCKS5代理服務名稱

——socks5-gssapi-nec與NEC Socks5伺服器相容-Y,——speed-limit RATE在指定限速時間之後停止傳輸-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 的檔案位置。 - means 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)

——trace FILE將 debug 資訊寫入指定的檔案

——trace-ascii FILE類似 ——trace 但使用16進度輸出

——trace-time向 trace/verbose 輸出新增時間戳

——tr-encoding請求壓縮傳輸編碼 (H)-T,——upload-file FILE將檔案傳輸(上傳)到指定位置

——url URL指定所使用的 URL-B,——use-ascii使用 ASCII/text 傳輸-u,——user USER[:PASSWORD]指定伺服器認證使用者名稱、密碼

——tlsuser USERTLS 使用者名稱

——tlspassword STRINGTLS 密碼

——tlsauthtype STRINGTLS 認證型別 (預設 SRP)

——unix-socket FILE透過這個 UNIX socket 域連線-A,——user-agent STRING要傳送到伺服器的 User-Agent (H)-v,——verbose顯示詳細操作資訊-V,——version顯示版本號並退出-w,——write-out FORMAT完成後輸出什麼

——xattr將元資料儲存在擴充套件檔案屬性中-q

。curlrc 如果作為第一個引數無效

五、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。六、用法演示:

為節省篇幅,部分操作不再貼上執行結果。

1、檢視網頁原始碼

直接在curl命令後加上網址,就可以看到網頁原始碼。我們以網址www。sina。com為例(選擇該網址,主要因為它的網頁程式碼較短):

root@ubuntu:/home/peng# curl www。sohu。com

執行結果顯示 307 Temporary Redirect,說明該網址需要重定向。

如果要把這個網頁儲存下來,可以使用-o引數,這就相當於使用wget命令了。

curl -o [檔名] www。sohu。com

2、自動跳轉

有的網址是自動跳轉的。使用-L引數,curl就會跳轉到新的網址。

curl -L www。sohu。com

鍵入上面的命令,結果就自動跳轉為www。sohu。com。cn。

3、顯示頭資訊

-i引數可以顯示http response的頭資訊,連同網頁程式碼一起。

root@ubuntu:/home/peng/driver/test# curl -i www。sohu。com

HTTP/1。1 307 Temporary Redirect

Content-Type: text/html

Content-Length: 180

Connection: keep-alive

Server: nginx

Date: Tue, 25 Aug 2020 10:10:54 GMT

Location: https://www。sohu。com/

FSS-Cache: from 9790436。18244590。10468709

FSS-Proxy: Powered by 2384755。3433341。3062915

-I引數則是隻顯示http response的頭資訊。

4、顯示通訊過程

-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: */*

>

* Connection #0 to host www。sohu。com left intact

* Closing connection #0

如果你覺得上面的資訊還不夠,那麼下面的命令可以檢視更詳細的通訊過程。

curl ——trace output。txt www。sohu。com

或者

curl ——trace-ascii output。txt www。sohu。com

執行後,請開啟output。txt檔案檢視。

5、傳送表單資訊

傳送表單資訊有GET和POST兩種方法。GET方法相對簡單,只要把資料附在網址後面就行。

curl example。com/form。cgi?data=xxx

POST方法必須把資料和網址分開,curl就要用到——data引數。

curl -X POST ——data “data=xxx” example。com/form。cgi

如果你的資料沒有經過表單編碼,還可以讓curl為你編碼,引數是——data-urlencode。

curl -X POST——data-urlencode “date=April 1” example。com/form。cgi

6、HTTP動詞

curl預設的HTTP動詞是GET,使用-X引數可以支援其他動詞。

curl -X POST www。example。com

curl -X DELETE www。example。com

7、檔案上傳

假定檔案上傳的表單是下面這樣:

你可以用curl這樣上傳檔案:

curl ——form upload=@localfilename ——form press=OK [URL]

8、Referer欄位

有時你需要在http request頭資訊中,提供一個referer欄位,表示你是從哪裡跳轉過來的。

curl ——referer http://www。example。com http://www。example。com

9、User Agent欄位

這個欄位是用來表示客戶端的裝置資訊。伺服器有時會根據這個欄位,針對不同裝置,返回不同格式的網頁,比如手機版和桌面版。

iPhone4的User Agent是

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

curl可以這樣模擬:

curl ——user-agent “[User Agent]” [URL]

10、cookie

使用——cookie引數,可以讓curl傳送cookie。

curl ——cookie “name=xxx” www。example。com

至於具體的cookie的值,可以從http response頭資訊的Set-Cookie欄位中得到。

-c cookie-file可以儲存伺服器返回的cookie到檔案,-b cookie-file可以使用這個檔案作為cookie資訊,進行後續的請求。

curl -c cookies http://example。com

curl -b cookies http://example。com

11、增加頭資訊

有時需要在http request之中,自行增加一個頭資訊。——header引數就可以起到這個作用。

$ curl ——header “Content-Type:application/json” http://example。com

12、認證

使用curl選項 -u 可以完成HTTP或者FTP的認證,可以指定密碼,也可以不指定密碼在後續操作中輸入密碼:

curl -u user:pwd http://man。linuxde。net

curl -u user http://man。linuxde。net

13、FTP1)、列出ftp伺服器上的目錄列表curl ftp://www。xxx。com/ ——user name:passwd

curl ftp://www。xxx。com/ –u name:passwd #簡潔寫法

curl ftp://name:passwd@www。xxx。com #簡潔寫法2

例如:在IP地址192。168。43。117上搭建FTP伺服器,並設定使用者名稱為user,密碼為123456。

現在我們要顯示伺服器上根目錄下的所有檔案資訊,命令如下:

curl -u user:123456 ftp://192。168。43。117

執行結果如下:

簡潔寫法:

curl ftp://user:123456@192。168。43。117

執行結果如下:

2)、只列出目錄,不顯示進度條curl ftp://www。xxx。com –u name:passwd -s

3)、下載一個檔案:

命令如下:

curl ftp://www。xxx。com/size。zip –u name:passwd -o size。zip

示例如下:從伺服器的根目錄下下載檔案test。c,儲存到本地,本地檔名也為test。c。【注意】如果沒有-o選項,程式會吧資料流定向到stdout,即直接把檔案內容顯示到終端上。

curl ftp://user:123456@192。168。43。117/test。c -o test。c

執行結果如下:

簡潔模式

curl -u user:123456 ftp://192。168。43。117/list。h -o list。h

執行結果如下:

4)、上載一個檔案:curl –u name:passwd -T size。mp3 ftp://www。xxx。com/mp3/

舉例如下:

curl -u user:123456 ftp://192。168。43。117/ -T list。h

Linux命令cURL詳解+定時上傳檔案到FTP伺服器(送原始碼)

可以看到檔案並沒有上傳成功,返回錯誤碼是25,參考第五章

25 FTP couldn’t STOR file。 The server denied the STOR operation, used for FTP uploading。

可知,是因為伺服器沒有賦予儲存的許可權,所以設定伺服器的write許可權即可。

5)、從伺服器上刪除檔案(使用curl傳遞ftp協議的DELE命令):curl –u name:passwd ftp://www。xxx。com/ -X ‘DELE mp3/size。mp3’

6)、另外curl不支援遞迴下載,不過可以用陣列方式下載檔案,比如我們要下載1-10。gif連續命名的檔案:**curl –u name:passwd ftp://www。xxx。com/img/[1-10]。gif –O #O字母大寫

7)、要連續下載多個檔案:curl –u name:passwd ftp://www。xxx。com/img/[one,two,three]。jpg –O #O字母大寫

六、實現日誌檔案定時上傳功能程式執行時要記錄當前日誌檔案的最後修改時間;每個10秒鐘就檢查下log檔案是否被修改,如果沒有被修改就休眠10秒鐘;如果log檔案被修改了,就將當前的日誌檔案複製成備份檔案,備份檔名字加上當前時間;透過curl傳送備份檔案給ftp伺服器;刪除備份檔案,重複步驟2。程式流程圖如下:

Linux命令cURL詳解+定時上傳檔案到FTP伺服器(送原始碼)

函式功能介紹init()

首先記錄當前log檔案時間,並記錄到全域性變數last_mtime中。

check_file_change()

讀取檔案最後修改時間,並和last_mtime進行比較,如果相同就返回0,不同就返回1。

file_name_add_time()

將當前的日誌檔案複製成備份檔案,備份檔名字加上當前時間。

stat()

得到對應檔案的屬性資訊,存放到struct stat結構體變數中。

system()

執行引數中字串對應的命令。

程式碼如下:/* Copyright (C) 公眾號: yikoulinux */

#include

#include

#include

#include

#include

typedef struct stat ST;

unsigned long last_mtime;

/*使用者名稱密碼暫時寫死,實際應該儲存在配置檔案*/

char name[32]=“user”;

char pass[32] =“123456”;

char ip[32] =“192。168。43。117”;

char filename[32]=“t。log”;

char dstfile[256] =;

int init(void)

{

//準備結構體

ST status;

//呼叫stat函式

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)

{

//準備結構體

ST status;

//呼叫stat函式

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]=;

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]=;

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);

}

}

執行截圖:

第一步:

Linux命令cURL詳解+定時上傳檔案到FTP伺服器(送原始碼)

因為log檔案沒有被修改過,所以程式不會上傳。

第二步:

手動輸入字串 yikoulinux 到日誌檔案 t。log中。

第三步:因為檔案發生了改變,所以列印“file updated”,同時可以看到curl上傳檔案的log資訊。

Linux命令cURL詳解+定時上傳檔案到FTP伺服器(送原始碼)

以下是FTP伺服器的根目錄,可以看到,上傳的日誌檔案:t-2020-7-26-1-19-45。log。

Linux命令cURL詳解+定時上傳檔案到FTP伺服器(送原始碼)

【補充】配置資訊,直接在程式碼中寫死,通常應該從配置檔案中讀取,為方便讀者閱讀,本程式碼沒有增加該功能;FTP伺服器搭建,本文沒有說明,相關檔案比較多,大家可以自行搜尋,一口君用的是File zilla;

Linux命令cURL詳解+定時上傳檔案到FTP伺服器(送原始碼)

通常這種需要長時間執行的程式,需要設定成守護程序,本文沒有新增相應功能,讀者可以自行搜尋。如果強烈要求可以單開一篇詳細介紹。

4。 程式碼中time的管理函式,請讀者自行搜尋相關文章。

5。 curl也提供了相關的函式庫curl。lib,如果要實現更靈活的功能可以使用對應的api。

6。 之所以先把檔案複製成備份檔案,主要是考慮其他模組隨時可能修改日誌檔案,起到一定保護作用。

TAG: curlSSLftpwwwfile