Skip to content

Instantly share code, notes, and snippets.

@u8sand
Last active June 27, 2023 19:44
Show Gist options
  • Save u8sand/f94069a31c1ac17d4d7e6908b5fc0f22 to your computer and use it in GitHub Desktop.
Save u8sand/f94069a31c1ac17d4d7e6908b5fc0f22 to your computer and use it in GitHub Desktop.
Powershell script for hassle-free Windows 10 OpenSSH Setup
# To get around "scripts not allowed on this system," you can run this with:
# powershell -ExecutionPolicy Bypass -File Windows10-OpenSSH.ps1
if (-Not (New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
Write-Host "Must run as administrator!"
Sleep 5
Exit
}
Write-Host "Current service status..."
Get-WindowsCapability -Online | Where-Object Name -like 'OpenSSH*' | Write-Host
Write-Host "Enabling OpenSSH Client/Server..."
Add-WindowsCapability -Online -Name OpenSSH.Client~~~~0.0.1.0
Add-WindowsCapability -Online -Name OpenSSH.Server~~~~0.0.1.0
Write-Host "Enabling Pubkey Authentication..."
(Get-Content -Path 'C:\ProgramData\ssh\sshd_config') -replace '#PubkeyAuthentication yes', 'PubkeyAuthentication yes' | Set-Content 'C:\ProgramData\ssh\sshd_config' -Encoding UTF8
Write-Host "Starting OpenSSH Server..."
Start-Service sshd
Write-Host "Ensuring OpenSSH Server starts on Startup..."
Set-Service -Name sshd -StartupType 'Automatic'
Write-Host "Veryifying OpenSSH Firewall"
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."
}
Write-Host "Creating administrators_authorized_keys..."
New-Item C:\ProgramData\ssh\administrators_authorized_keys
Write-Host "Updating permissions..."
$acl = Get-Acl C:\ProgramData\ssh\administrators_authorized_keys
$acl.SetAccessRuleProtection($true, $false)
$administratorsRule = New-Object system.security.accesscontrol.filesystemaccessrule("Administrators","FullControl","Allow")
$systemRule = New-Object system.security.accesscontrol.filesystemaccessrule("SYSTEM","FullControl","Allow")
$acl.SetAccessRule($administratorsRule)
$acl.SetAccessRule($systemRule)
$acl | Set-Acl
Write-Host "Add your public keys to C:\ProgramData\ssh\administrators_authorized_keys using with UTF8 encoding"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment