萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 作業系統 >  >> Linux 教學

Linux curl 指令完整實戰範例:下載、上傳、斷點續傳、代理、Cookie、偽裝瀏覽器等 11 大場景

curl 是功能最完整的命令列傳輸工具,支援 HTTP/HTTPS/FTP/SFTP 等協議,廣泛用於 API 測試、自動化腳本、檔案下載上傳。本文整理 11 大實戰場景與常用參數速查表,助你掌握 curl 核心用法。

一、常用參數速查

參數長參數說明
-O--remote-name以遠端檔名儲存
-o--output指定輸出檔名
-C ---continue-at -斷點續傳
-L--location追蹤重導向
-H--header自訂請求標頭
-d--dataPOST 資料
-b--cookie送出 Cookie
-c--cookie-jar儲存 Cookie 到檔案
-A--user-agent偽裝 User-Agent
-e--referer偽裝 Referer
-x--proxy指定 HTTP 代理
-u--user基本認證 user:pass
-s--silent靜默模式
-#--progress-bar進度條顯示
-I--head只取得 HEAD 回應
-v--verbose詳細輸出

二、11 大實戰場景

1. 基本抓取網頁原始碼

$ curl https://www.example.com

無桌面環境的伺服器常用此法測試網站可達性。

2. 儲存網頁內容

# 重導向
$ curl https://www.example.com > page.html

# -o 指定檔名(顯示進度)
$ curl -o page.html https://www.example.com

# -O 使用遠端檔名(需具體檔案 URL)
$ curl -O https://www.example.com/file.zip

3. 測試 HTTP 狀態碼(腳本常用)

$ curl -o /dev/null -s -w "%{http_code}" https://www.example.com
# 輸出如:200

4. 指定代理伺服器

$ curl -x 192.168.1.100:8080 https://www.example.com

5. Cookie 處理

# 儲存回應 Cookie
$ curl -c cookies.txt https://www.example.com

# 儲存回應 Header(含 Set-Cookie)
$ curl -D headers.txt https://www.example.com

# 送出 Cookie
$ curl -b cookies.txt https://www.example.com

6. 偽裝瀏覽器 User-Agent

$ curl -A "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36" https://www.example.com

7. 偽裝 Referer(防盜鏈繞過)

$ curl -e "https://www.example.com/" https://www.example.com/protected.jpg

8. 下載檔案進階技巧

# 循環下載多檔案
$ curl -O https://example.com/img[1-10].jpg

# 多目錄下載並重命名避免覆蓋
$ curl -o "#1_#2.jpg" https://example.com/{dir1,dir2}/img[1-5].jpg
# 輸出:dir1_img1.jpg, dir1_img2.jpg, ..., dir2_img5.jpg

# 分段下載大檔案
$ curl -r 0-1023999 -o part1.bin https://example.com/large.bin
$ curl -r 1024000-2047999 -o part2.bin https://example.com/large.bin
$ curl -r 2048000- -o part3.bin https://example.com/large.bin
$ cat part*.bin > large.bin

# FTP 下載(兩種語法)
$ curl -O -u user:pass ftp://example.com/file.zip
$ curl -O ftp://user:pass@example.com/file.zip

# 進度條 / 靜默
$ curl -# -O https://example.com/large.iso
$ curl -s -O https://example.com/large.iso

9. 斷點續傳

$ curl -C - -O https://example.com/large.iso

10. 上傳檔案

$ curl -T localfile.txt -u user:pass ftp://example.com/upload/
# HTTP POST 上傳
$ curl -F "file=@localfile.txt" https://example.com/upload

11. 錯誤處理

# 失敗時不輸出 HTTP 錯誤頁面,只回傳錯誤碼
$ curl -f https://example.com/notfound
# 結合腳本判斷
$ if curl -f -o /dev/null -s https://example.com; then echo "OK"; else echo "FAIL"; fi

三、其他實用參數

--limit-rate 100k    # 限速
--max-time 30        # 最大執行秒數
--connect-timeout 10 # 連線逾時
--retry 3            # 重試次數
--retry-delay 5      # 重試間隔
--compressed         # 請求 gzip/deflate 壓縮
-k / --insecure      # 忽略 SSL 憑證驗證(測試用)
copyright © 萬盛學電腦網 all rights reserved