Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> 關於 Linux

Linux 兩機互傳檔案完全指南:scp/rsync/sftp/sshfs 四大工具實戰比較與最佳實踐

編輯:關於 Linux

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

檔案傳輸工具對比圖

四大工具快速選擇表

工具核心特性適用場景效能自動化友善度
scp SSH 管道、單檔/目錄、無斷點續傳 臨時單次傳輸、小檔案、腳本簡單複製 中 (單流、加密開銷) 高 (無互動、標準輸出)
rsync 差量傳輸、斷點續傳、保留屬性、壓縮、過濾規則 **大量資料同步、備份、鏡像、生產部署** **高 (僅傳差異、可關閉加密)** 高 (豐富退出碼、統計輸出)
sftp 互動式、類 FTP 指令、支援批次檔 互動式探索、需遠端目錄操作 (mkdir/rm/ls) 中 中 (需 expect/lftp 腳本)
sshfs FUSE 掛載遠端目錄為本地檔案系統 開發環境遠端編輯、應用程式直接讀寫遠端檔 取決於網路/快取 低 (掛載後透明,但需 FUSE 權限)

scp 核心指令大全

# 本地 → 遠端
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 生產級同步範例

# 標準備份 (保留權限、時間、符號連結、裝置檔)
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 互動與批次

# 互動式
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

sshfs 掛載遠端目錄

# 安裝
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

進階:免密碼自動化 (所有工具通用)

  1. 產生金鑰:ssh-keygen -t ed25519
  2. 部署公鑰:ssh-copy-id user@host
  3. SSH Agent 快取:eval $(ssh-agent) && ssh-add
  4. 腳本中使用:ssh -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。

Copyright © Windows教程網 All Rights Reserved