Linux 機器間傳檔是日常運維核心技能。本文系統比較 scp、rsync、sftp、sshfs 四大主流工具的適用場景、指令範例、效能特性與自動化整合,助你選擇最佳方案。

| 工具 | 核心特性 | 適用場景 | 效能 | 自動化友善度 |
|---|---|---|---|---|
| scp | SSH 管道、單檔/目錄、無斷點續傳 | 臨時單次傳輸、小檔案、腳本簡單複製 | 中 (單流、加密開銷) | 高 (無互動、標準輸出) |
| rsync | 差量傳輸、斷點續傳、保留屬性、壓縮、過濾規則 | **大量資料同步、備份、鏡像、生產部署** | **高 (僅傳差異、可關閉加密)** | 高 (豐富退出碼、統計輸出) |
| sftp | 互動式、類 FTP 指令、支援批次檔 | 互動式探索、需遠端目錄操作 (mkdir/rm/ls) | 中 | 中 (需 expect/lftp 腳本) |
| sshfs | FUSE 掛載遠端目錄為本地檔案系統 | 開發環境遠端編輯、應用程式直接讀寫遠端檔 | 取決於網路/快取 | 低 (掛載後透明,但需 FUSE 權限) |
# 本地 → 遠端
scp file.txt user@host:/remote/path/
scp -r dir/ user@host:/remote/path/
# 遠端 → 本地
scp user@host:/remote/file.txt /local/path/
scp -r user@host:/remote/dir/ /local/path/
# 遠端 → 遠端 (透過本地轉發)
scp user1@host1:/file user2@host2:/path/
# 關鍵參數
scp -P 2222 -C -o StrictHostKeyChecking=no -i ~/.ssh/id_rsa file user@host:/path/
# -P: 指定埠 (小寫 -p 為保留時間戳)
# -C: 壓縮
# -i: 指定私鑰
# -l: 限制頻寬 (Kbit/s)
# -4/-6: 強制 IPv4/IPv6
# 標準備份 (保留權限、時間、符號連結、裝置檔)
rsync -avz --progress /src/ user@host:/dst/
# 鏡像同步 (刪除目的端多餘檔案)
rsync -avz --delete /src/ user@host:/dst/
# 排除規則
rsync -avz --exclude='*.log' --exclude='.git/' /src/ user@host:/dst/
# 限制頻寬 10MB/s
rsync -avz --bwlimit=10000 /src/ user@host:/dst/
# 乾跑模式 (預覽)
rsync -avzn /src/ user@host:/dst/
# SSH 參數透傳
rsync -avz -e 'ssh -p 2222 -i ~/.ssh/id_rsa' /src/ user@host:/dst/
# 互動式
sftp user@host
sftp> put file.txt
sftp> get remote.txt
sftp> mkdir dir
sftp> ls -l
sftp> bye
# 批次檔
sftp -b batch.txt user@host
# batch.txt 內容:
# put file1.txt
# put file2.txt
# get report.pdf
# bye
# 安裝
sudo apt-get install sshfs # 或 yum/dnf/pacman
# 掛載
mkdir ~/remote_mnt
sshfs user@host:/remote/path ~/remote_mnt -o reconnect,ServerAliveInterval=15,allow_other
# 使用 (如本地目錄)
code ~/remote_mnt/project/
vim ~/remote_mnt/config.yaml
# 卸載
fusermount -u ~/remote_mnt
ssh-keygen -t ed25519ssh-copy-id user@hosteval $(ssh-agent) && ssh-addssh -o BatchMode=yes ... (失敗即退出,不提示密碼)tar czf - /src | ssh user@host "tar xzf - -C /dst" (單一 TCP 連線、避開檔案系統元資料開銷)rsync -e 'ssh -c aes128-gcm@openssh.com' --compress-level=1 (較快加密、低壓縮)rsync --daemon + rsync://host/module (無 SSH 加密開銷、近線速)根據「資料量、頻率、互動需求、網路環境」選擇工具:日常臨時用 scp、生產同步備份用 rsync、遠端開發用 sshfs、互動式探索用 sftp。