在Windows上安裝 OpenSSH Server
當前版本的Windwos10其實已經有內建 OpenSSH 了,不過實際版本可能沒那麼新建議是從 Github 上下載最新的版的安裝。
總共提供三個方法選一個執行就可以了 (別全做了擇一就好)
- 使用Windwos內建的版本
- 從Gihub安裝最新版本的OpenSSH
- 懶人包自動爬蟲安裝最新版本
方式1 使用Windwos內建的版本
如果懶得安裝直接到設定 “選用功能” 中打開OpenSSH功能就會自動裝了
快速打開方法
- 按下 Windows 鍵 + R 打開運行對話框。
- 輸入
ms-settings:optionalfeatures
命令。 - 按下 Enter 鍵或點擊「確定」。
然後打勾按下安裝就會自動裝好了
方式2 從Github安裝最新版本的OpenSSH
目前的Windwos10預設是有自動安裝客戶端的,可以不宜除只要在環境變數追加的時候把想要的版本在前面即可,後面的會被忽略掉。
微軟的安裝說明頁面
開始使用 OpenSSH for Windows | Microsoft Learn
具體來說需要做的事情有
- 安裝檔案
- 追加環境變數
- 通過內付的ps1腳本安裝 OpenSSH Server
- 設置防火牆打開 22 連接埠
安裝檔案
最新版本載點
Releases · PowerShell/Win32-OpenSSH (github.com)
點擊 OpenSSH-Win64.zip 下載檔案
直接解壓縮到C曹
使用管理員打開 PowerShell 執行命令追加環境變數
$env:Path > C:\EnvPath.txt
$newEnvPath = 'C:\OpenSSH-Win64;'+$env:Path
[Environment]::SetEnvironmentVariable('Path', $newEnvPath, 'Machine')
$env:Path = $newEnvPath
[Environment]::GetEnvironmentVariable('Path', 'Machine') -split ';'
要編輯環境變數可以輸入 rundll32 sysdm.cpl,EditEnvironmentVariables 快速打開環境變數編輯的圖形視窗
測試一下 SSH-Client 有沒有裝好,版要跟自己下載的一致
Get-Command ssh,sshd
Win10內建的是8.1版,要是看到這版本檢查一下環境變數,把自己裝的移到最上方就會優先使用了;或是乾脆從方法1中移除內建的也行。
再來執行內付的腳本安裝 SSH-Server
cd 'C:\OpenSSH-Win64'
PowerShell -Exec Bypass -File install-sshd.ps1
再來初始化 OpenSSH Server 的設定
Start-Service sshd
Set-Service -Name sshd -StartupType 'Automatic'
if (!(Get-NetFirewallRule -Name "OpenSSH-Server-In-TCP" -ErrorAction SilentlyContinue | Select-Object Name, Enabled)) {
Write-Output "Firewall Rule 'OpenSSH-Server-In-TCP' does not exist, creating it..."
New-NetFirewallRule -Name 'OpenSSH-Server-In-TCP' -DisplayName 'OpenSSH Server (sshd)' -Enabled True -Direction Inbound -Protocol TCP -Action Allow -LocalPort 22
} else {
Write-Output "Firewall rule 'OpenSSH-Server-In-TCP' has been created and exists."
}
至此就完成了,接下來自己連接自己試試看
ssh localhost
第一次連接會有一個對話出現需要輸入 yes 並按下 enter,再來輸入密碼即可登入
移除的話自行參考底下 [2] 中的指令移除
PowerShell -Exec Bypass -File C:\OpenSSH-Win64\uninstall-sshd.ps1
防火牆的部分到防火牆設定中砍掉 Port 22 的進站規則就好
方式3 懶人包自動爬蟲安裝最新版本
代碼開源在這裡:自動爬蟲抓取最新版本OpenSSH並安裝 · GitHub
使用方法
irm bit.ly/3uosqf4|iex; Install-OpenSSH 'C:\Program Files\OpenSSH' -IncludeServer -OpenFirewall
移除的代碼(不包含防火牆設置)
PowerShell -Exec Bypass -File "$(Split-Path(gcm sshd).Source)\uninstall-sshd.ps1"
參考文獻
- 開始使用 OpenSSH for Windows | Microsoft Learn
- Install Win32 OpenSSH · PowerShell/Win32-OpenSSH Wiki · GitHub