The latest builds of Windows 10 and Windows 11 include a built-in 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, similar to Linux distros. In this article, we’ll show you 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. OpenSSH is built-in into the operating system image in the latest versions of Windows Server 2022/2019 and Windows 11.
How to Enable SSH Server on Windows 10?
Make sure your build of Windows 10 is 1809 or newer. The easiest way to do this is by running the command:
winver
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 Windows 10 build (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 from GitHub.
You can enable the OpenSSH server in Windows 10 through the graphical Settings panel:
- Go to Settings > Apps > Apps and features > Optional features (or run the command 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 click Install.
You can also install the sshd server using PowerShell:
Add-WindowsCapability -Online -Name OpenSSH.Server*
Or 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*' Name : OpenSSH.Server~~~~0.0.1.0 State : Installed
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:WindowsSystem32OpenSSH folder.
Configuring SSH Service on Windows 10 and 11
Check the status of ssh-agent and sshd services using the PowerShell Get-Service command:
Get-Service -Name *ssh*
As you 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'
You also need to allow incoming connections to TCP port 22 in the Windows Defender firewall settings. You can open the port using netsh:
netsh advfirewall firewall add rule name=”SSHD service” dir=in action=allow protocol=TCP localport=22
Or you 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
You can configure various OpenSSH server settings in Windows using the %programdata%sshsshd_config configuration file.
For example, you can disable password authentication and leave only key-based auth with:
PubkeyAuthentication yes PasswordAuthentication no
Here you can also specify a new TCP port (instead of the default TCP 22 port) on which the SSHD will accept connections. For example:
Port 2222
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 theitbrosjbrown@192.168.1.15 — denies connections to username jbrown from 192.168.1.15 host;
- DenyUsers theitbros* — prevent all users from theitbros domain to connect host using ssh;
- AllowGroups theitbrosssh_allow — only allow users from theitbrosssh_allow to connect host.
The allow and deny rules of sshd are processed in the following order: DenyUsers, AllowUsers, DenyGroups, and AllowGroups.
For example, to allow to connect to SSH under mylocaluser1 account from 192.168.31.100 host, add the following directive:
AllowUsers mylocaluser1@192.168.31.100
After making changes to the sshd_config file, you need to restart the sshd service:
Get-Service sshd| Restart-Service –force
Connect to Windows via SSH
Now you 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 you want to connect. This account must be a member of the built-in Administrators group. 192.168.1.90 is an IP address of your Windows 10 computer.
After that, a Windows command prompt window will open in the SSH session.
You can use the Putty client to connect to a Windows computer via SSH:
- Download and run putty.exe;
- Enter the hostname or IP address of the remote Windows host you want to connect over SSH;
- Select the Connection type: SSH and make sure port 22 is specified;
- Click Open;
- The first time you connect to a Windows host via SSH, a Security Alert will appear asking you to confirm that you want to add the ssh-ed25519 key fingerprint of the remote machine to your local cache. If you trust this host, click the Accept button. This will add that server to the list of known SSH hosts;
Note. OpenSSH server fingerprint stored in a file C:ProgramDatasshssh_host_ecdsa_key.pub. You can determine the current ECDSA key fingerprint on a Windows 10 host with the command:ssh-keygen -lf C:ProgramDatasshssh_host_ed25519_key.pub
- A Putty window will appear. Here you need to specify the Windows username and password that you want to use to connect to SSH;
- Once logged in, the command line of the remote Windows host will open;
- You can now interactively run commands on the remote host.
You can also use the built-in Windows SSH client to connect to another Windows host. Install the ssh.exe client on Windows using the command:
Add-WindowsCapability -Online -Name OpenSSH.Client*
Now you can connect to a remote SSH host directly from the Windows command prompt. Use the following command:
ssh root@192.168.13.202
The first time you connect, you will also need to add the fingerprint of the SSH server’s ECDSA key to the list of known hosts. To do this, type “yes” > “enter”.
Enter the user’s password. The command line C:Windowssystem32conhost.exe should appear:
You can now use the OpenSSH.Client tools (scp.exe, sftp.exe) to copy a file between hosts using the SSH protocol. The following command will copy the local test1.log file to a remote Windows SSH host:
scp.exe D:PStest1.log root@192.168.13.202:c:temp
If you prefer to use Windows Terminal, you can add the required SSH host profiles to it for quick connection:
- Run Windows Terminal and go to its Settings;
- Click the Add a new profile button in the Profiles section;
- Specify that you want to create a duplicate of Windows PowerShell profile;
- Specify a profile name (“SSH Windows 10 DEVPC” in this example);
- In the Command line parameter, specify the connection string to your SSH host. For example: %SystemRoot%System32WindowsPowerShellv1.0powershell.exe ssh root@192.168.13.202
- Save the profile;
- Now in the Windows Terminal menu you will have a separate option for a quick SSH connection to a Windows host.
Hint. In some scenarios, you will need to run the PowerShell.exe cli instead of the cmd.exe shell when logging in via SSH on Windows 10. You can do this by running the following command in Windows 10 (under the admin account):
New-ItemProperty -Path "HKLM:SOFTWAREOpenSSH" -Name DefaultShell -Value "C:WindowsSystem32WindowsPowerShellv1.0powershell.exe" -PropertyType String -Force
Now, you 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. In such a case, the contents of the id_rsa.pub file must be copied to the c:usersadmin.sshauthorized_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
In previous versions of OpenSSH on Windows, all of the sshd service logs were written to the text file C:ProgramDatasshlogssshd.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
- About
- Latest Posts
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.
Contents
- 1 How to Install the SSH Client on Windows 10
- 2 How to Use SSH Commands in Windows 10
- 3 How to Open a Port in Firewall or Enable the Telnet Client
Using SSH on Windows 10 used to be a pain that required third-party software such as PuTTy. In 2018, though, Microsoft enabled native SSH commands via an OpenSSH Windows integration.
If you’re unfamiliar with SSH, it stands for Secure Shell, a protocol typically used for connecting to Linux servers. The command-line SSH tool lets you log into your server and run commands remotely to perform any required task.
The Integrated OpenSSH for Windows Client
The OpenSSH client for Windows is installed by default on Windows Server 2019 and Windows 10 build 1809 and later. However, if SSH commands aren’t working for you, it’s because you need to enable them in your Windows features. We’re going to walk you through enabling SSH on Windows 10 via this method, then show you how to use it. Let’s get started:
How to Install the SSH Client on Windows 10
Though Windows 10 OpenSSH is installed by default on most versions, it may not be for everyone. Thankfully, enabling SSH only takes a few seconds. Here’s how:
- Press the Search button and type “Optional feature”
Click the top result, which should read, “Add an optional feature”.
- Click “Add a feature” in Settings
- Install the Windows OpenSSH Client
Type “SSH” in the optional features search bar, then tick the entry that reads “OpenSSH Client”. Finally, click the “Install” button at the bottom of your Window. The process will take a few seconds to complete and shouldn’t require a restart.
Once you have the Windows 10 SSH client installed, using it is a simple matter. You can use Command Prompt for this, or PowerShell SSH, whichever you prefer. The SSH commands are the same across both applications, so you can still follow along.
- Open Command Prompt (or PowerShell)
Press Start and then type “Command Prompt”. Click the top result.
- Run the SSH command to view its usage guide
Command Prompt will return a full list of options and syntax for you to use as you require.
- Connect to your server via your Windows Open SSH client
In most cases, you won’t need the above options to connect to your SSH server. Instead, you can simply run:
ssh [email protected]
You’ll be prompted for your server’s root password, which you can type and press Enter to log in.
If your server uses a different port to the standard for SSH, you can specify it by adding
-p portnumber
to the end of your command.The first time you connect to a server, you’ll receive a warning asking if you’re sure you want to connect. Type
yes
and press Enter to connect.
How to Open a Port in Firewall or Enable the Telnet Client
Now you know how to install SSH on Windows. However, if you’re still having issues, you may need to follow our tutorial on how to open or close a port in Windows 10 Firewall to add an exception for your SSH port.
Finally, if your server uses the older Telnet protocol, you may want to follow our tutorial on how to enable the Telnet client in Windows 10 instead.
В современных версиях 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 $HOMEDownloadsOpenSSH-Win64-v8.9.1.0.msi -UseBasicParsing
msiexec /i c:usersrootdownloadsOpenSSH-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:WindowsSystem32OpenSSH
(sshd.exe, ssh.exe, ssh-keygen.exe, sftp.exe и т.д.) - Конфигурационный файл sshd_config (создается после первого запуска службы):
C:ProgramDatassh
- Файлы authorized_keys и ssh ключи можно хранить в профиле пользователей:
%USERPROFILE%.ssh
Sshd_config: Конфигурационный файл сервера OpenSSH
Настройки сервере OpenSSH хранятся в конфигурационном файле %programdata%sshsshd_config. Это обычный текстовый файл с набором директив. Для редактирования можно использовать любой текстовый редактор (я предпочитаю notepad++). Можно открыть с помощью обычного блокнота:
start-process notepad C:Programdatasshsshd_config
Например, чтобы запретить SSH подключение для определенного доменного пользователя (и всех пользователей указанного домена), добавьте в конце файле директивы:
DenyUsers winitpro[email protected] DenyUsers corp*
Чтобы разрешить подключение только для определенной доменной группы:
AllowGroups winitprosshadmins
Либо можете разрешить доступ для локальной группы:
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:
-
[email protected]
– локальный пользователь Windows -
[email protected]@server1
–пользователь Active Directory (в виде UPN) или аккаунт Microsoft/ Azure(Microsoft 365) -
winitpro[email protected]
– NetBIOS формат имени
В домене Active Directory можно использовать Kerberos аутентификацию в SSH. Для этого в sshd_config нужно включить параметр:
GSSAPIAuthentication yes
После этого можно прозрачно подключать к SSH сервер с Windows компьютера в домене из сессии доменного подключается. В этом случае пароль пользователя не указывается и выполняется SSO аутентификация через Kerberos:
ssh -K server1
При первом подключении появится стандартный запрос на добавление узла в список известных SSH хостов.
Нажимаем Да, и в открывшееся окне авторизуемся под пользователем Windows.
При успешном подключении запускается командная оболочка cmd.exe со строкой-приглашением.
[email protected] C:Usersadmin>
В командной строке вы можете выполнять различные команды, запускать скрипты и программы.
Я предпочитаю работать в командной строке PowerShell. Чтобы запустить интерпретатор PowerShell, выполните:
powershell.exe
Чтобы изменить командную оболочку (Shell) по умолчанию в OpenSSH с cmd.exe на PowerShell, внесите изменение в реестр такой командой:
New-ItemProperty -Path "HKLM:SOFTWAREOpenSSH" -Name DefaultShell -Value "C:WindowsSystem32WindowsPowerShellv1.0powershell.exe" -PropertyType String –Force
Осталось перезапустить SSH подключение и убедиться, что при подключении используется командный интерпретатор PowerShell (об этом свидетельствует приглашение
PS C:Usersadmin>
).
В 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:ProgramDatasshlogssshd.log
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 $HOMEDownloadsOpenSSH-Win64-v8.9.1.0.msi -UseBasicParsing
msiexec /i $HOMEDownloadsOpenSSH-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:WindowsSystem32OpenSSH
(sshd.exe, ssh.exe, ssh-keygen.exe, sftp.exe, etc.) - The sshd_config file (created after the first service start of the service):
C:ProgramDatassh
- 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%sshsshd_config
. This is a plain text file with a set of directives. You can use any text editor for editing:
start-process notepad C:Programdatasshsshd_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 woshubadmin@192.168.1.10 DenyUsers corp*
To allow SSH connection to the specific domain security group only:
AllowGroups woshubsshadmins
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 max@192.168.13.12
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 usermax@woshub.com@server1
– Active Directory user or Microsoft/Azure account (use the UserPrincipalName format)woshubmax@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:Usersyour_user.sshknown_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:Usersadmin>
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:SOFTWAREOpenSSH" -Name DefaultShell -Value "C:WindowsSystem32WindowsPowerShellv1.0powershell.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:Usersadmin>
).
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:ProgramDatasshlogssshd.log
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:windowssystem32Openssh
. 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 Servicesshd.
- Now, open an elevated command prompt.
- Go to the c:windowssystem32Openssh directory using the command
cd c:windowssystem32Openssh
. - Here, run the command
ssh-keygen -A
to 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:WindowsSystem32OpenSSHssh_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 Servicesshd. - Click «Add» and add the permission «Read» for the user «NT Servicesshd». 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=22
Microsoft 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!
How to enable ssh on Windows?
Tested on Windows Version 10.0.17755.1
-
Run
cmd
as admin -
Install OpenSSH.Client —
dism /online /Add-Capability /CapabilityName:OpenSSH.Client~~~~0.0.1.0
C:WINDOWSsystem32>dism /online /Add-Capability /CapabilityName:OpenSSH.Client~~~~0.0.1.0 Deployment Image Servicing and Management tool Version: 10.0.17755.1 Image Version: 10.0.17755.1 [==========================100.0%==========================] The operation completed successfully.
- Install OpenSSH.Server
dism /online /Add-Capability /CapabilityName:OpenSSH.Server~~~~0.0.1.0
C:WINDOWSsystem32>dism /online /Add-Capability /CapabilityName:OpenSSH.Server~~~~0.0.1.0 Deployment Image Servicing and Management tool Version: 10.0.17755.1 Image Version: 10.0.17755.1 [==========================100.0%==========================] The operation completed successfully.
-
Launch Services (
services.msc
) -
Start OpenSSH services (change Startup Type to Automatic)
- OpenSSH Authentication Agent
- OpenSSH SSH Server
-
Test ssh to remote server
ssh user@remote
C:WINDOWSsystem32>ssh user@remote user@remote's password: Welcome to Ubuntu 16.04 LTS (GNU/Linux 4.4.0-128-generic x86_64) * Documentation: https://help.ubuntu.com * Management: https://landscape.canonical.com * Support: https://ubuntu.com/advantage user@remote:~#
- Test ssh from remote server to local machine
ssh domain\myuser@local
user@remote:~# ssh domain\myuser@local domain\myuser@local's password: Microsoft Windows [Version 10.0.17755.1] (c) 2018 Microsoft Corporation. All rights reserved. domainmyuser@local C:Usersmyuser>whoami domainmyuser