В современных версиях Windows уже есть встроенный SSH сервер на базе пакета OpenSSH. В этой статье мы покажем, как установить и настроить OpenSSH сервер в Windows 10/11 и Windows Server 2022/2019 и подключиться к нему удаленно по защищенному SSH протоколу (как к Linux).
Содержание:
- Установка сервера OpenSSH в Windows
- Настройка SSH сервера в Windows
- Sshd_config: Конфигурационный файл сервера OpenSSH
- Подключение по SSH к Windows компьютеру
- Логи SSH подключений в Windows
Установка сервера OpenSSH в Windows
Пакет OpenSSH Server включен в современные версии Windows 10 (начиная с 1803), Windows 11 и Windows Server 2022/2019 в виде Feature on Demand (FoD). Для установки сервера OpenSSH достаточно выполнить PowerShell команду:
Get-WindowsCapability -Online | Where-Object Name -like ‘OpenSSH.Server*’ | Add-WindowsCapability –Online
Или при помощи команды DISM:
dism /Online /Add-Capability /CapabilityName:OpenSSH.Server~~~~0.0.1.0
Если ваш компьютер подключен к интернету, пакет OpenSSH.Server будет скачан и установлен в Windows.
Также вы можете установить сервер OpenSSH в Windows через современную панель Параметры (Settings -> Apps and features -> Optional features -> Add a feature, Приложения -> Управление дополнительными компонентами -> Добавить компонент. Найдите в списке OpenSSH Server и нажмите кнопку Install).
На изолированных от интернета компьютерах вы можете установить компонент с ISO образа Features On Demand (доступен в личном кабинете на сайте Microsoft: MSDN или my.visualstudio.com). Скачайте диск, извлеките его содержимое в папку c:\FOD (достаточно распаковать извлечь файл
OpenSSH-Server-Package~31bf3856ad364e35~amd64~~.cab
), выполните установку из локального репозитория:
Add-WindowsCapability -Name OpenSSH.Server~~~~0.0.1.0 -Online -Source c:\FOD
Также доступен MSI установщик OpenSSH для Windows в официальном репозитории Microsoft на GitHub (https://github.com/PowerShell/Win32-OpenSSH/releases/). Например, для Windows 10 x64 нужно скачать и установить пакет OpenSSH-Win64-v8.9.1.0.msi. Следующая PowerShell команда скачает MSI файл и установит клиент и сервер OpenSSH:
Invoke-WebRequest https://github.com/PowerShell/Win32-OpenSSH/releases/download/v8.9.1.0p1-Beta/OpenSSH-Win64-v8.9.1.0.msi -OutFile $HOME\Downloads\OpenSSH-Win64-v8.9.1.0.msi -UseBasicParsing
msiexec /i c:\users\root\downloads\OpenSSH-Win64-v8.9.1.0.msi
Также вы можете вручную установить OpenSSH сервер в предыдущих версиях Windows (Windows 8.1, Windows Server 2016/2012R2). Пример установки Win32-OpenSSH есть в статье “Настройка SFTP сервера (SSH FTP) в Windows”.
Чтобы проверить, что OpenSSH сервер установлен, выполните:
Get-WindowsCapability -Online | ? Name -like 'OpenSSH.Ser*'
State : Installed
Настройка SSH сервера в Windows
После установки сервера OpenSSH в Windows добавляются две службы:
- ssh-agent (OpenSSH Authentication Agent) – можно использовать для управления закрытыми ключами если вы настроили SSH аутентификацию по ключам;
- sshd (OpenSSH SSH Server) – собственно сам SSH сервер.
Вам нужно изменить тип запуска службы sshd на автоматический и запустить службу с помощью PowerShell:
Set-Service -Name sshd -StartupType 'Automatic'
Start-Service sshd
С помощью nestat убедитесь, что теперь в системе запущен SSH сервер и ждет подключений на порту TCP:22 :
netstat -na| find ":22"
Проверьте, что включено правило брандмауэра (Windows Defender Firewall), разрешающее входящие подключения к Windows по порту TCP/22.
Get-NetFirewallRule -Name *OpenSSH-Server* |select Name, DisplayName, Description, Enabled
Name DisplayName Description Enabled ---- ----------- ----------- ------- OpenSSH-Server-In-TCP OpenSSH SSH Server (sshd) Inbound rule for OpenSSH SSH Server (sshd) True
Если правило отключено (состоянии Enabled=False) или отсутствует, вы можете создать новое входящее правило командой New-NetFirewallRule:
New-NetFirewallRule -Name sshd -DisplayName 'OpenSSH Server (sshd)' -Enabled True -Direction Inbound -Protocol TCP -Action Allow -LocalPort 22
Рассмотрим, где храниться основные компоненты OpenSSH:
- Исполняемые файлы OpenSSH Server находятся в каталоге
C:\Windows\System32\OpenSSH\
(sshd.exe, ssh.exe, ssh-keygen.exe, sftp.exe и т.д.) - Конфигурационный файл sshd_config (создается после первого запуска службы):
C:\ProgramData\ssh - Файлы authorized_keys и ssh ключи можно хранить в профиле пользователей:
%USERPROFILE%\.ssh\
Sshd_config: Конфигурационный файл сервера OpenSSH
Настройки сервере OpenSSH хранятся в конфигурационном файле %programdata%\ssh\sshd_config. Это обычный текстовый файл с набором директив. Для редактирования можно использовать любой текстовый редактор (я предпочитаю notepad++). Можно открыть с помощью обычного блокнота:
start-process notepad C:\Programdata\ssh\sshd_config
Например, чтобы запретить SSH подключение для определенного доменного пользователя (и всех пользователей указанного домена), добавьте в конце файле директивы:
DenyUsers winitpro\[email protected] DenyUsers corp\*
Чтобы разрешить подключение только для определенной доменной группы:
AllowGroups winitpro\sshadmins
Либо можете разрешить доступ для локальной группы:
AllowGroups sshadmins
По умолчанию могут к openssh могут подключаться все пользователи Windows. Директивы обрабатываются в следующем порядке: DenyUsers, AllowUsers, DenyGroups,AllowGroups.
Можно запретить вход под учетными записями с правами администратора, в этом случае для выполнения привилегированных действий в SSH сессии нужно делать runas.
DenyGroups Administrators
Следующие директивы разрешают SSH доступ по ключам (SSH аутентификации в Windows с помощью ключей описана в отдельной статье) и по паролю:
PubkeyAuthentication yes PasswordAuthentication yes
Вы можете изменить стандартный SSH порт TCP/22, на котором принимает подключения OpenSSH в конфигурационном файле sshd_config в директиве Port.
После любых изменений в конфигурационном файле sshd_config нужно перезапускать службу sshd:
restart-service sshd
Подключение по SSH к Windows компьютеру
Теперь вы можете попробовать подключиться к своей Windows 10 через SSH клиент (в этом примере я использую putty).
Вы можете использовать встроенный SSH клиентом Windows для подключения к удаленному хосту. Для этого нужно в командной строке выполнить команду:
ssh [email protected]
В этом примере
alexbel
– имя пользователя на удаленном Windows компьютере, и 192.168.31.102 – IP адрес или DNS имя компьютера.
Обратите внимание что можно использовать следующие форматы имен пользователей Windows при подключении через SSH:
-
alex@server1
– локальный пользователь Windows -
[email protected]@server1
–пользователь Active Directory (в виде UPN) или аккаунт Microsoft/ Azure(Microsoft 365) -
winitpro\alex@server1
– NetBIOS формат имени
В домене Active Directory можно использовать Kerberos аутентификацию в SSH. Для этого в sshd_config нужно включить параметр:
GSSAPIAuthentication yes
После этого можно прозрачно подключать к SSH сервер с Windows компьютера в домене из сессии доменного подключается. В этом случае пароль пользователя не указывается и выполняется SSO аутентификация через Kerberos:
ssh -K server1
При первом подключении появится стандартный запрос на добавление узла в список известных SSH хостов.
Нажимаем Да, и в открывшееся окне авторизуемся под пользователем Windows.
При успешном подключении запускается командная оболочка cmd.exe со строкой-приглашением.
admin@win10tst C:\Users\admin>
В командной строке вы можете выполнять различные команды, запускать скрипты и программы.
Я предпочитаю работать в командной строке PowerShell. Чтобы запустить интерпретатор PowerShell, выполните:
powershell.exe
Чтобы изменить командную оболочку (Shell) по умолчанию в OpenSSH с cmd.exe на PowerShell, внесите изменение в реестр такой командой:
New-ItemProperty -Path "HKLM:\SOFTWARE\OpenSSH" -Name DefaultShell -Value "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -PropertyType String –Force
Осталось перезапустить SSH подключение и убедиться, что при подключении используется командный интерпретатор PowerShell (об этом свидетельствует приглашение
PS C:\Users\admin>
).
В SSH сессии запустилась командная строка PowerShell, в которой работают привычные функции: авто дополнение, раскраска модулем PSReadLine, история команд и т.д. Если текущий пользователь входит в группу локальных администраторов, то все команды в его сессии выполняются с повышенными правами даже при включенном UAC.
Логи SSH подключений в Windows
В Windows логи подключений к SSH серверу по-умолчанию пишутся не в текстовые файлы, а в отдельный журнал событий через Event Tracing for Windows (ETW). Откройте консоль Event Viewer (
eventvwr.msc
>) и перейдите в раздел Application and services logs -> OpenSSH -> Operational.
При успешном подключении с помощью к SSH серверу с помощью пароля в журнале появится событие:
EventID: 4 sshd: Accepted password for root from 192.168.31.53 port 65479 ssh2
Если была выполнена аутентификация с помощью SSH ключа, событие будет выглядеть так:
sshd: Accepted publickey for locadm from 192.168.31.53 port 55772 ssh2: ED25519 SHA256:FEHDEC/J72Fb2zC2oJNb45678967kghH43h3bBl31ldPs
Если вы хотите, чтобы логи писались в локальный текстовый файл, нужно в файле sshd_config включить параметры:
SyslogFacility LOCAL0 LogLevel INFO
Перезапустите службу sshd и провеьте, что теперь логи SSH сервера пишутся в файл C:\ProgramData\ssh\logs\sshd.log
The latest builds of Windows 10 and Windows 11 include a build-in SSH server and client that are based on OpenSSH.
This means now you can remotely connect to Windows 10/11 or Windows Server 2019 using any SSH client, like Linux distros.
Let’s see how to configure OpenSSH on Windows 10 and Windows 11, and connect to it using Putty or any other SSH client.
OpenSSH is an open-source, cross-platform version of Secure Shell (SSH) that is used by Linux users for a long time.
This project is currently ported to Windows and can be used as an SSH server on almost any version of Windows.
In the latest versions of Windows Server 2022/2019 and Windows 11, OpenSSH is built-in to the operating system image.
How to install SSH Server on Windows 10?
Make sure our build of Windows 10 is 1809 or newer. The easiest way to do this is by running the command:
Note. If you have an older Windows 10 build installed, you can update it through Windows Update or using an ISO image with a newer version of Windows 10 (you can create an image using the Media Creation Tool). If you don’t want to update your Windows 10 build, you can manually install the Win32-OpenSSH port for Windows with GitHub.
Enable feature
We can enable OpenSSH server in Windows 10 through the graphical Settings panel:
-
Go to the
Settings>Apps>Apps and features>Optional features(or run thecommand ms-settings:appsfeatures) -
Click Add a feature, select
OpenSSH Server(OpenSSH-based secure shell (SSH) server, for secure key management and access from remote machines), and clickInstall
Install using PowerShell
We can also install sshd server using PowerShell:
Add-WindowsCapability -Online -Name OpenSSH.Server*
Install using DISM
Or we can also install sshd server using DISM:
dism /Online /Add-Capability /CapabilityName:OpenSSH.Server~~~~0.0.1.0
If you want to make sure the OpenSSH server is installed, run the following PS command:
Get-WindowsCapability -Online | ? Name -like 'OpenSSH.Server*'
How to uninstall SSH Server?
Use the following PowerShell command to uninstall the SSH server:
Remove-WindowsCapability -Online -Name OpenSSH.Server~~~~0.0.1.0
How to Install SSH Server on Windows 11?
Also, you can add the OpenSSH Server on Windows 11.
- Go to Settings > Apps > Optional features;
- Click View Features;
Select OpenSSH Server from the list and click Next > Install;
Wait for the installation to complete.
The OpenSSH binaries are located in the C:\Windows\System32\OpenSSH\ folder.
Configuring SSH Service on Windows 10 and 11
Check the status of ssh-agent and sshd services using the PowerShell command Get-Service:
As we can see, both services are in a Stopped state and not added to the automatic startup list. To start services and configure autostart for them, run the following commands:
Start-Service sshd Set-Service -Name sshd -StartupType 'Automatic' Start-Service 'ssh-agent' Set-Service -Name 'ssh-agent' -StartupType 'Automatic'
We also need to allow incoming connections to TCP port 22 in the Windows Defender Firewall. We can open the port using netsh:
netsh advfirewall firewall add rule name=”SSHD service” dir=in action=allow protocol=TCP localport=22
Or we can add a firewall rule to allow SSH traffic using PowerShell:
New-NetFirewallRule -Name sshd -DisplayName 'OpenSSH Server (sshd)' -Enabled True -Direction Inbound -Protocol TCP -Action Allow -LocalPort 22
Now we can connect to Windows 10 using any SSH client. To connect from Linux, use the command:
ssh -p 22 admin@192.168.1.90
Here, the admin is a local Windows user under which we want to connect. 192.168.1.90 is an IP address of your Windows 10 computer.
After that, a new Windows command prompt window will open in SSH session.
Hint. To run the PowerShell.exe cli instead of cmd.exe shell when logging in via SSH on Windows 10, we need to run the following command in Windows 10 (under admin account):
New-ItemProperty -Path "HKLM:\SOFTWARE\OpenSSH" -Name DefaultShell -Value "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -PropertyType String -Force
Now, we change the default OpenSSH shell. From here, when connecting to Windows via SSH, you will immediately see PowerShell prompt instead of cmd.exe.
If you want to use key-based ssh authentication instead of password authentication, you need to generate a key using ssh-keygen on your client.
Then, the contents of the id_rsa.pub file must be copied to the c:\users\admin\.ssh\authorized_keys file in Windows 10.
After that, you can connect from your Linux client to Windows 10 without a password. Use the command:
ssh -l admin@192.168.1.90
Configuration
We can configure various OpenSSH server settings in Windows using the %programdata%\ssh\sshd_config configuration file.
For example, we can disable password authentication and leave only key-based auth with:
PubkeyAuthentication yes PasswordAuthentication no
Here we can also specify a new TCP port (instead of the default TCP 22 port) on which the SSHD will accept connections. For example:
Using the directives AllowGroups, AllowUsers, DenyGroups, DenyUsers, you can specify users and groups who are allowed or denied to connect to Windows via SSH:
DenyUsers theitbros\jbrown@192.168.1.15— blocks connections to username jbrown from 192.168.1.15 hostsжDenyUsers theitbros\*— prevent all users from theitbros domain to connect host using sshжAllowGroups theitbros\ssh_allow— only allow users from theitbtos\ssh_allow connect hostю- The allow and deny rules of sshd are processed in the following order:
DenyUsers,AllowUsers,DenyGroups, andAllowGroups.
After making changes to the sshd_config file, you need to restart the sshd service:
Get-Service sshd | Restart-Service –force
In previous versions of OpenSSH on Windows, all sshd service logs were written to the text file C:\ProgramData\ssh\logs\sshd.log by default.
On Windows 11, SSH logs can be viewed using the Event Viewer console (eventvwr.msc). All SSH events are available in a separate section Application and Services Logs > OpenSSH > Operational.
For example, the screenshot shows an example of an event with a successful connection to the computer via SSH. You can see the ssh client’s IP address (hostname) and the username used to connect.
sshd: Accepted password for jbrown from 192.168.14.14. port 49833 ssh2
SSH-server based on the OpenSSH package is part of the operating system in all modern versions of Windows. In this article, we’ll show you how to install and configure the OpenSSH server on Windows 10/11 and Windows Server 2022/2019 and connect to it remotely via a secure SSH connection (just like in Linux 🙂).
Contents:
- How to Install OpenSSH Server on Windows
- Configuring SSH Server on Windows
- Sshd_config: OpenSSH Server Configuration File
- How to Connect to a Remote Windows Computer via SSH?
- Checking SSH Connection Logs in Windows
How to Install OpenSSH Server on Windows
The OpenSSH Server package is a part of all modern versions of Windows 10 (starting with 1803), Windows 11, and Windows Server 2022/2019 as a Feature on Demand (FoD). To install the OpenSSH server, open the elevated PowerShell prompt and run the command:
Get-WindowsCapability -Online | Where-Object Name -like ‘OpenSSH.Server*’ | Add-WindowsCapability –Online
Or using DISM:
dism /Online /Add-Capability /CapabilityName:OpenSSH.Server~~~~0.0.1.0
If your computer is directly connected to the Internet, the OpenSSH.Server package will be downloaded and installed on Windows.
You can also install OpenSSH on Windows 10/11 through the modern Settings panel (Settings -> Apps and features -> Optional features -> Add a feature). Find Open SSH Server in the list and click Install.
On computers in disconnected (offline) environments, you can install the OpenSSH Server from the Feature on Demand ISO image (available in your account on the Microsoft websites: MSDN or my.visualstudio.com). Download the ISO and extract its contents to the E:\FOD folder (you can only extract the file OpenSSH-Server-Package~31bf3856ad364e35~amd64~~.cab) and install the Windows feature from the local repository:
Add-WindowsCapability -Name OpenSSH.Server~~~~0.0.1.0 -Online -Source E:\FOD
An MSI installer for OpenSSH for Windows is also available in the official Microsoft repository on GitHub (https://github.com/PowerShell/Win32-OpenSSH/releases/). For example, for Windows 10 x64, you need to download and install the OpenSSH-Win64-v8.9.1.0.msi package. The following PowerShell command will download the MSI file and install the OpenSSH client and server on your computer:
Invoke-WebRequest https://github.com/PowerShell/Win32-OpenSSH/releases/download/v8.9.1.0p1-Beta/OpenSSH-Win64-v8.9.1.0.msi -OutFile $HOME\Downloads\OpenSSH-Win64-v8.9.1.0.msi -UseBasicParsing
msiexec /i $HOME\Downloads\OpenSSH-Win64-v8.9.1.0.msi
You can install an OpenSSH server in previous Windows versions as well (Windows 8.1, Windows Server 2016/2012R2/2012). Check the example on how to install and configure Win32-OpenSSH in the article “How to Configure SFTP Server (SSH FTP) on Windows?”.
To make sure the OpenSSH server has been installed, run the command:
Get-WindowsCapability -Online | ? Name -like 'OpenSSH.Ser*'
State : Installed
Configuring SSH Server on Windows
After installing the OpenSSH server on Windows, two services are added:
- ssh-agent (OpenSSH Authentication Agent) – can be used to manage private keys if you have configured SSH key authentication;
- sshd (OpenSSH SSH Server).
You need to change the startup type of the sshd service to automatic and start the service using PowerShell:
Set-Service -Name sshd -StartupType 'Automatic'
Start-Service sshd
Use the netstat command to make sure that the SSH server is running and waiting for the connections on TCP port 22:
netstat -na| find ":22"
Make sure that Windows Defender Firewall allows inbound connections to Windows through TCP port 22:
Get-NetFirewallRule -Name *OpenSSH-Server* |select Name, DisplayName, Description, Enabled
Name DisplayName Description Enabled ---- ----------- ----------- ------- OpenSSH-Server-In-TCP OpenSSH SSH Server (sshd) Inbound rule for OpenSSH SSH Server (sshd) True
If the rule is disabled (Enabled=False) or missing, you can create a new inbound rule using the New-NetFirewallRule cmdlet:
New-NetFirewallRule -Name sshd -DisplayName 'OpenSSH Server (sshd)' -Enabled True -Direction Inbound -Protocol TCP -Action Allow -LocalPort 22
By default, key OpenSSH components are located in these folders:
- OpenSSH Server executables:
C:\Windows\System32\OpenSSH\(sshd.exe, ssh.exe, ssh-keygen.exe, sftp.exe, etc.) - The sshd_config file (created after the first service start of the service):
C:\ProgramData\ssh - The authorized_keys file and keys can be stored in the user profile folder:
%USERPROFILE%\.ssh\
Sshd_config: OpenSSH Server Configuration File
You can change your OpenSSH server settings in the config file: %programdata%\ssh\sshd_config. This is a plain text file with a set of directives. You can use any text editor for editing:
start-process notepad C:\Programdata\ssh\sshd_config
For example, to deny SSH connection for a specific domain user account (or all users in the specified domain), add these directives to the end of the file:
DenyUsers woshub\[email protected] DenyUsers corp\*
To allow SSH connection to the specific domain security group only:
AllowGroups woshub\sshadmins
You can allow access to a local user group:
AllowGroups sshadmins
By default, all Windows users can connect to OpenSSH. Directives in the sshd_config files are processed in the following order: DenyUsers, AllowUsers, DenyGroups, AllowGroups.
You can deny SSH login for the accounts with administrator privileges. In this case, if you need to perform any privileged actions in your SSH session, you will have to use runas.
DenyGroups Administrators
The following directives allow you to access Windows using SSH private keys or a password.
PubkeyAuthentication yes PasswordAuthentication yes
You can change the default TCP/22 port on which OpenSSH Server connections are accepted in the sshd_config configuration file using the Port directive.
After making any changes to the sshd_config file, you need to restart the sshd service
restart-service sshd
How to Connect to a Remote Windows Computer via SSH?
Now you can try to connect to your Windows 10 computer using the SSH client (I’m using putty in this example).
You can use the built-in Windows SSH client to connect to a remote host. To do this, open the command prompt and run the following command:
ssh [email protected]
In this example, max is the username on the remote Windows computer, and 192.168.13.12 is the IP address or DNS name of the computer.
Note that you can use the following username formats when connecting to Windows via SSH:
max@server1– local Windows user[email protected]@server1– Active Directory user or Microsoft/Azure account (use the UserPrincipalName format)woshub\max@server1– NetBIOS name format
In an Active Directory domain, you can use Kerberos authentication in SSH. To do this, you need to enable the following directive in sshd_config:
GSSAPIAuthentication yes
You can now transparently connect to an SSH server from a domain-joined Windows machine with a domain user session. In this case, the user’s password will not be requested, and SSO authentication via Kerberos will be performed:
ssh -K server1
The first time you connect, you will be prompted to add the host to the list of known SSH hosts (C:\Users\your_user\.ssh\known_hosts).
Click Yes, and login under your Windows user account.
If the SSH connection is successful, you will see the cmd.exe shell prompt.
admin@win10pc C:\Users\admin>
You can run different commands, scripts, and apps in the SSH command prompt.
I prefer working in the PowerShell console. To start it, run:
powershell.exe
In order to change the default cmd.exe shell in OpenSSH to PowerShell, make changes to the registry using the following PowerShell command:
New-ItemProperty -Path "HKLM:\SOFTWARE\OpenSSH" -Name DefaultShell -Value "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -PropertyType String –Force
Restart your SSH connection and make sure that PowerShell is now used as a default SSH shell (this is indicated by the prompt PS C:\Users\admin>).
The PowerShell prompt has been started in my SSH session, where the usual functions work: tab autocomplete, PSReadLine syntax highlighting, command history, etc. If the current user is a member of the local administrators’ group, all session commands are executed elevated even if UAC is enabled.
OpenSSH server on Windows can be used in various SSH tunneling scenarios.
Checking SSH Connection Logs in Windows
By default in Windows SSH server connection logs are written not to text files, but to a separate event log via Event Tracing for Windows (ETW). Open the Event Viewer console (eventvwr.msc ) and navigate to Application and services logs -> OpenSSH -> Operational.
If you successfully connect to the SSH server using a password, an event will appear in the log:
EventID: 4 sshd: Accepted password for root from 192.168.1.53 port 65749 ssh2
If SSH key authentication was performed, you will see the following event:
sshd: Accepted publickey for locadm from 192.168.1.53 port 61426 ssh2: ED25519 SHA256:FEHDEC/G42FS23209C2KMb4335923pigN31s3qMK322lGibD
If you want the SSH connection logs to be written to a local text file, you need to enable the following parameters in the sshd_config file:
SyslogFacility LOCAL0 LogLevel INFO
Restart the sshd service and make sure that the SSH server logs are now written to a plain text file C:\ProgramData\ssh\logs\sshd.log
You can use a secure SSH connection with PSRemoting to manage remote computers via WinRM.
The latest Windows versions include a built-in OpenSSH server which allows to remotely connect Windows hosts over the an encrypted SSH connection. This article describes how to enable and configure an SSH server on Windows 10/11 and connect to it using SSH clients.
How to Install SSH Server on Windows
OpenSSH Server is available as an optional feature in all new versions of Windows starting with Windows 10 (build 1809) and Windows Server 2019. This means you don’t need third-party SSH server software to access Windows remotely via SSH.
The OpenSSH server feature can be installed on Windows 10 and 11 via the Settings app.
- Go to Settings > System > Optional features (or run the command: ms-settings:optionalfeatures)
- Click View Feature, select OpenSSH Server (OpenSSH-based secure shell (SSH) server, for secure key management and access from remote machines), and click Install.
Or, use this PowerShell command to install the SSH server:
Add-WindowsCapability -Online -Name OpenSSH.Server~~~~0.0.1.0
Check if the OpenSSH server is installed:
Get-WindowsCapability -Online | ? Name -like 'OpenSSH.Server*'
The OpenSSH components are downloaded from the Internet. In an offline (disconnected) environment, you can add the OpenSSH server from the Features on Demand (FoD) ISO image.
- Download the FoD ISO image for your version of Windows from the Volume Licensing Service Centre (VLSC) or from the My Visual Studio portal (requires active subscription).
- Mount the FoD ISO image on Windows to a virtual DVD drive;
- Install the OpenSSH.Server from virtual drive with the command:
Add-WindowsCapability -online -name OpenSSH.Server~~~~0.0.1.0 -source -Source "E:\" -LimitAccess
Note. For previous Windows versions, you can manually install the Win32-OpenSSH port from the GitHub repository.
The OpenSSH binaries are located in the C:\Windows\System32\OpenSSH\ folder.
How to Enable and Configure OpenSSH Server on Windows
OpenSSH service is stopped by default on Windows. Use the PowerShell Get-Service command to check its status:
Get-Service -Name sshd
Start the sshd service and enable the automatic startup:
Start-Service sshd Set-Service -Name sshd -StartupType 'Automatic'
Then enable the inbound Windows Defender firewall rule that allows remote connections to the SSH server (on TCP port 22):
Get-NetFirewallRule -Name OpenSSH-Server-In-TCP |Enable-NetFirewallRule
Check that the sshd service is running and listening on port TCP/22:
netstat -nao | find /i '":22"'
Several configuration files containing OpenSSH server settings can be used in Windows.
- Global (system-wide) configuration file: %programdata%\ssh\sshd_config
- A user’s configuration file in the user profile folder: %userprofile%\.ssh\config
You can open and edit the sshd_config file using Notepad:
Notepad.exe $env:PROGRAMDATA\ssh\sshd_config
By default, most of the configuration options in the sshd_config file are disabled. To enable and configure the OpenSSH option, remove the # character at the beginning of the line to uncomment it.
Let’s look at some of the sshd_config directives:
- Enable the SSH key-based authentication: PubkeyAuthentication yes
- Disable password auth: PasswordAuthentication no
- Change the SSH port number (from the default TCP 22): Port 22
The AllowGroups, AllowUsers, DenyGroups, and DenyUsers directives allow to specify which users and groups are allowed or denied to connect to Windows via SSH. For example:
- DenyUsers theitbros\jbrown@192.168.1.15 — deny connection to username jbrown from 192.168.1.15 host;
- DenyUsers theitbros\* — prevent all users from theitbros domain from connecting to the host via SSH;
- AllowGroups theitbros\ssh_allow theitbros\admins— Only allow users from specified groups to SSH to the host;
- AllowUsers mylocaluser1@192.168.31.100 – allow SSH access under the mylocaluser1 account from the 192.168.31.100 host.
Note. The allow and deny rules of sshd are processed in the following order: DenyUsers, AllowUsers, DenyGroups, and AllowGroups.
Restart the sshd service after making changes to the sshd_config file:
Get-Service sshd| Restart-Service –force
Change the default OpenSSH shell from cmd.exe to PowerShell using the command:
New-ItemProperty -Path "HKLM:\SOFTWARE\OpenSSH" -Name DefaultShell -Value "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -PropertyType String -Force
Connect to Windows via SSH
Now you can use any OpenSSH-compatible client, from either a Linux or Windows host, to connect to an SSH-enabled Windows computer.
For example, on Linux, run the command:
ssh admin@192.168.1.90
- admin is a local Windows user that you want to connect as. This account must be a member of the built-in Administrators group.
- 192.168.1.90 is an IP address or DNS name of the remote Windows host.
Enter the password of a Windows user and an SSH shell with a remote host will be started.
On Windows 10 and 11, you can use the built-in OpenSSH client (ssh.exe, which is installed by default) to establish a remote SSH session. Check if it is enabled with the command:
Get-WindowsCapability -Online | ? Name -like 'OpenSSH.Client*'
You can connect to a remote SSH host from the Windows command prompt:
ssh user123@192.168.13.202
The first time you connect to a remote SSH host, you must add its public key to the list of known hosts by typing yes -> Enter.
If you want to SSH host under an AD domain account, use the following username format:
ssh theitbros\kirill@192.168.13.202
Enter the user’s password and a command prompt should appear:
To copy files to a remote Windows host via an SSH session, use the command:
scp.exe D:\PS\test1.log root@192.168.13.202:c:\temp
Configure Key-Based Authentication for OpenSSH on Windows
The Windows OpenSSH server supports the password and publickey authentication methods. By default, only password authentication is enabled on Windows OpenSSH server.
Let’s look at how to enable and configure OpenSSH key-based authentication instead of username/password pair auth.
Generate public/private key pairs using the Ed25519 algorithm on a Windows client, run the command:
ssh-keygen -t ed25519
Note. For additional key protection, you can set a passphrase.
The ssh-keygen tool will generate two key files and save them in the current user’s profile (C:\Users\%username%\.ssh):
- id_ed25519 – private key
- id_ed25519.pub – public key
The next step is to add the generated public key to the authorized_keys file on the OpenSSH server. Copy the public key from the id_ed25519.pub file and paste it into the administrators_authorized_keys file on the SSH server:
Notepad.exe $env:PROGRAMDATA\ssh\administrators_authorized_keys
Note. The administrators_authorized_keys file is used if the user belongs to the administrator group. For non-privileged Windows users, add the public key to the .ssh/authorised_keys file in the user profile.
Open the file C:\ProgramData\ssh\sshd_config and enable key-based authentication:
PubkeyAuthentication yes
Restart the sshd service:
Get-service sshd|Restart-Service
The ssh-agent will now automatically use the private key for authentication when connecting to a remote host.
Or you can manually specify the path to the key file:
ssh username1@192.168.13.202 -i "C:\Users\user\.ssh\id_ed25519"
On Windows, SSH logs can be viewed using the Event Viewer console (eventvwr.msc). Expand Application and Services Logs > OpenSSH > Operational.
Cyril Kardashevsky
I enjoy technology and developing websites. Since 2012 I’m running a few of my own websites, and share useful content on gadgets, PC administration and website promotion.
As you may already know, Windows 10 includes built-in SSH software — both a client and a server! In this article, we will see how to enable the SSH Server.
Note: The OpenSSH Server app will allow you to establish a connection to your computer using the SSH protocol. It won’t allow you to access other computers on your network. To connect to other computers, you should install the OpenSSH Client.
With Windows 10, Microsoft has finally listened to its users after years of them requesting an SSH client and server. By including an OpenSSH implementation, the value of the OS increases.
At the moment of this writing, the OpenSSH software included in Windows 10 is at a BETA stage. This means it can have some stability issues.
The provided SSH server is similar to the Linux app. At first glance, it appears to support the same features as its *NIX counterpart. It is a console app, but it works as a Windows Service.
Let’s see how to enable the OpenSSH server in Windows 10.
- Open the Settings app and go to Apps -> Apps & features.
- On the right, click Manage optional features.
- On the next page, click the button Add a feature.
- In the list of features, select OpenSSH Server and click on the Install button.
- Restart Windows 10.
This will install the OpenSSH Server software in Windows 10.
Its binary files are located under the folder c:\windows\system32\Openssh. Besides the SSH client apps, the folder contains the following server tools:
- sftp-server.exe
- ssh-agent.exe
- ssh-keygen.exe
- sshd.exe
- and the config file «sshd_config».
The SSH server is configured to run as a service.
At the moment of this writing, it doesn’t start automatically. You need to configure it manually.
How to Start the OpenSSH Server in Windows 10
- Double-click the sshd entry in Services to open its properties.
- On the «Log On» tab, see the user account which is used by the sshd server. In my case, it is NT Service\sshd.
- Now, open an elevated command prompt.
- Go to the c:\windows\system32\Openssh directory using the command
cd c:\windows\system32\Openssh. - Here, run the command
ssh-keygen -Ato generate security keys for the sshd server. - Now, in the elevated command prompt, type
explorer.exe .to launch File Explorer in the OpenSSH folder. - Update: Microsoft has published a tutorial which makes the right assignment process very simple.
Open PowerShell as Administrator and execute these commands:Install-Module -Force OpenSSHUtils Repair-SshdHostKeyPermission -FilePath C:\Windows\System32\OpenSSH\ssh_host_ed25519_key
That’s it! All the required permissions are set.
- Alternatively, you can perform these steps.
Right-click the ssh_host_ed25519_key file and change its ownership to the sshd service user, e.g. NT Service\sshd. - Click «Add» and add the permission «Read» for the user «NT Service\sshd». Now, remove all other permissions to get something like this:
Click «Apply» and confirm the operation.
- Finally, open Services (Press the Win + R keys and type services.msc in the Run box) and start the sshd service. It should start:
- Allow the SSH port in Windows Firewall. By default, the server is using port 22. Run this command in an elevated command prompt:
netsh advfirewall firewall add rule name="SSHD Port" dir=in action=allow protocol=TCP localport=22Microsoft has supplied the following alternative command for PowerShell:
New-NetFirewallRule -Name sshd -DisplayName 'OpenSSH Server (sshd)' -Service sshd -Enabled True -Direction Inbound -Protocol TCP -Action Allow -Profile Domain - Finally, set a password for your user account if you don’t have it.
Now, you can try it in action.
Connecting to the SSH Server in Windows 10
Open your ssh client. You can start it on the same computer, e.g. using the built-in OpenSSH client or start it from another computer on your network.
In the general case, the syntax for the OpenSSH console client is as follows:
ssh username@host -p port
In my case, the command looks as follows:
ssh winaero@192.168.2.96
Where winaero is my Windows user name and 192.168.2.96 is the IP address of my Windows 10 PC. I will connect to it from another PC, running Arch Linux.
Finally, you are in!
The server runs classic Windows console commands, e.g. more, type, ver, copy.
But I cannot run FAR Manager. It appears black and white and broken:
Another interesting observation: You can start GUI apps like explorer. If you are signed in to the same user account that you use for SSH, they will start on the desktop. See:
Well, the built-in SSH server is definitely an interesting thing to play with. It allows you to manage a Windows machine without installing tools like rdesktop on your Linux computer, or even changing Windows settings from a Linux computer which has no X server installed.
As of this writing, the built-in SSH server in Windows 10 is at a BETA stage, so it should get more interesting and become a useful feature in the near future.
Support us
Winaero greatly relies on your support. You can help the site keep bringing you interesting and useful content and software by using these options:
If you like this article, please share it using the buttons below. It won’t take a lot from you, but it will help us grow. Thanks for your support!
