Инструкция по настройке SSH для ОС семейства Windows

Для настройки доступа к виртуальной машине на ОС Windows по протоколу SSH нужно выполнить скрипт, приведённый ниже, предварительно вставив в поле sshPubKey ваш публичный ключ.

$sshPubKey = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIEWkysbaLCCx4tNh8q2a6b9OCXkc0SdvRu6yUJlijZld DISTR_TEST"

if ((Get-Service | Where-Object {$_.name -match "sshd"}).Length -eq 0) {
    Add-WindowsCapability -Name OpenSSH.Server~~~~0.0.1.0 -Online
}

Set-Service -Name sshd -StartupType "Automatic"
Start-Service sshd

$rules = Get-NetFirewallRule |
    Where-Object { $_.Direction -eq "Inbound" -and $_.Action -eq "Allow" -and $_.Enabled -eq "True" } |
    Get-NetFirewallPortFilter |
    Where-Object { $_.LocalPort -eq "22" }

if (!$rules) {
    New-NetFirewallRule -Name sshd -DisplayName "OpenSSH Server (sshd)" -Enabled True -Direction Inbound -Protocol TCP -Action Allow -LocalPort 22
} else {
    Write-Host "Port 22 already allowed"
}

$sshdFilePath = "C:\ProgramData\ssh\sshd_config"
$backupPath = $sshdFilePath + "_bak"
try {
    Copy-Item -Path $sshdFilePath -Destination $backupPath
    Write-Host "sshd_config backup saved to $backupPath"
} catch {
    Write-Error "Backup sshd_config error"
}

$sshdFileContent = "StrictModes no
PubkeyAuthentication yes
HostKeyAlgorithms ssh-ed25519-cert-v01@openssh.com,ssh-rsa-cert-v01@openssh.com,ssh-ed25519,ecdsa-sha2-nistp521-cert-v01@openssh.com,ecdsa-sha2-nistp384-cert-v01@openssh.com,ecdsa-sha2-nistp256-cert-v01@openssh.com,ecdsa-sha2-nistp521,ecdsa-sha2-nistp384,ecdsa-sha2-nistp256,rsa-sha2-256,rsa-sha2-512
PasswordAuthentication no
Match Group administrators
       AuthorizedKeysFile __PROGRAMDATA__/ssh/administrators_authorized_keys"

Set-Content -Path $sshdFilePath -Value $sshdFileContent

$authKeysPath = "C:\ProgramData\ssh\administrators_authorized_keys"

if ((Test-Path $authKeysPath) -ne $True) {
    New-Item -Path $authKeysPath -Type File
}

icacls.exe $authKeysPath /inheritance:r /grant "Administrators:F" /grant "SYSTEM:F"
$content = Get-Content $authKeysPath

if ($content -notcontains $sshPubKey) {
    Add-Content -Path $authKeysPath -Value $sshPubKey
}

Restart-Service sshd