﻿# 如何讓 OpenSSH for Windows 也能支援 Rsync 遠端加密連線傳輸

傳送大量檔案到遠端 Windows 電腦時，除了使用 SFTP 之外，其實也可以使用 Linux 知名的 `rsync` 命令來快速傳檔，不但傳輸過程可以透過 OpenSSH 加密，傳輸內容甚至於可以壓縮與進行差異比對。不過 Windows 要使用 Rsync 來傳檔真的比我想像中的難很多，我花了大量的時間搜尋解決方案無果，沒有一篇文章能用的，最後嘗試各種組合才被我找出一定能成功使用的方法。這篇文章看起來不長，但還真的花了不少時間研究，就馬上來看看 Windows 如何使用 Rsync 搭配 OpenSSH 來傳檔吧！

### 設定 Windows 伺服器端

基本上你只要設定好 OpenSSH Server 之後，就只要加裝 Rsync 工具即可，這裡我們會以 [cwRsync](https://itefix.net/cwrsync) 為主。

1.  下載與安裝 [cwRsync](https://itefix.net/cwrsync) 最新版
    
    ```powershell
    # 安裝 rsync 工具
    choco install rsync -y
    ```
    
2.  重新啟動 `sshd` 服務
    
    ```powershell
    Restart-Service sshd
    ```
    

### 設定 Windows 用戶端

這次我們因為需要使用到 [cwRsync](https://itefix.net/cwrsync) 內附的 `ssh.exe` 程式，但是 cwRsync 的 Chocolatey 套件只包含 `rsync.exe` 而已，所以我們**用戶端**不能用 Chocolatey 進行安裝。

1.  下載與安裝 [cwRsync](https://itefix.net/cwrsync) 最新版
    
    ```powershell
    # 下載最新版 cwRsync
    Invoke-WebRequest -Uri https://itefix.net/dl/free-software/cwrsync_6.2.4_x64_free.zip -OutFile cwrsync_6.2.4_x64_free.zip
    
    # 先解壓縮到暫存資料夾
    Expand-Archive -LiteralPath "$PWD\cwrsync_6.2.4_x64_free.zip" -DestinationPath "$env:TEMP\cwrsync"
    
    # 將 cwrsync_6.2.4_x64_free 目錄下所有檔案複製到 C:\cwrsync
    mkdir "C:\cwrsync"
    Copy-Item -Path "$env:TEMP\cwrsync\cwrsync_6.2.4_x64_free\*" -Destination "C:\cwrsync" -Recurse
    
    # 刪除壓縮檔
    del "$PWD\cwrsync_6.2.4_x64_free.zip"
    ```
    
2.  設定**系統層級**的 `PATH` 環境變數加入 `C:\cwrsync\bin` 路徑
    
    ```powershell
    # 下載設定環境變數的利器 SetEnv
    Invoke-WebRequest -Uri "https://github.com/doggy8088/SetEnv/releases/download/1.0/SetEnv.exe" -OutFile "SetEnv.exe"
    
    # 增加 PATH 系統環境變數
    .\setenv -a PATH %C:\cwrsync\bin
    
    # 刪除 SetEnv.exe
    del SetEnv.exe
    ```
    
3.  使用 `rsync` 搭配 cwRsync 內附的 `ssh.exe` 來進行加密連線
    
    ```powershell
    rsync -e 'c:\cwrsync\bin\ssh.exe -i mysshkey' -avzr 'myfile' user1@172.29.212.19:.
    ```
    
    > 我目前不太能理解為什麼不能用 Win32-OpenSSH 提供的 `ssh.exe` 來進行連線，但我嘗試了很多種不同的 `ssh.exe`，包含 Cygwin 的 `ssh.exe` 也不行，就只有 cwRsync 的 `ssh.exe` 可以用。我有建立一個 [Issue #1869](https://github.com/PowerShell/Win32-OpenSSH/issues/1869) 來追蹤這個問題。
    

### 相關連結

-   [cwRsync - Rsync for Windows | itefix.net](https://itefix.net/cwrsync)
-   [How to use Rsync on Windows using SSH connection?](https://arunkrsoam.medium.com/how-to-use-rsync-on-windows-using-ssh-connection-835190e72ae0)
-   [rsync: connection unexpectedly closed (0 bytes received so far) \[Receiver\] · Issue #1869 · PowerShell/Win32-OpenSSH](https://github.com/PowerShell/Win32-OpenSSH/issues/1869)
