Как включить ssh сервер на windows

В этой статье рассмотрим, как установить и настроить встроенный SSH сервер на базе OpenSSH в Windows 10/11 и Windows Server 2022/2019. Вы узнаете, как подключиться к системе по защищенному SSH протоколу, как это делается в Linux.

Приобрести оригинальные ключи активации Windows Server можно у нас в каталоге от 1190 ₽
Установка OpenSSH сервера в Windows

OpenSSH сервер включен в современные версии Windows 10 (начиная с 1803), Windows 11 и Windows Server 2022/2019 как Feature on Demand (FoD). Установить его можно несколькими способами.

1. Установка через PowerShell:

Get-WindowsCapability -Online | Where-Object Name -like 'OpenSSH.Server*' | Add-WindowsCapability -Online

2. Установка через DISM:

dism /Online /Add-Capability /CapabilityName:OpenSSH.Server~~~~0.0.1.0

3. Через панель «Параметры»:

— Перейдите в Настройки -> Приложения -> Дополнительные компоненты -> Добавить компонент.

— Найдите OpenSSH Server и нажмите Установить.

4. Установка с помощью MSI пакета:

Вы можете установить OpenSSH с помощью MSI установщика, доступного на GitHub:

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 сервер установлен, выполните:

Get-WindowsCapability -Online | ? Name -like 'OpenSSH.Ser*'

State : Installed

Настройка SSH сервера в Windows

После установки OpenSSH на Windows появляются две службы:

ssh-agent (для управления ключами если вы настроили SSH аутентификацию по ключам)

sshd (собственно сам SSH сервер)

1. Настройка автозапуска SSH службы:

Выполните команду PowerShell для включения автозапуска SSH сервера:

Set-Service -Name sshd -StartupType 'Automatic'

Start-Service sshd

2. Проверка порта SSH:

Убедитесь, что сервер слушает на порту TCP:22:

netstat -na | find ":22"

3. Настройка брандмауэра:

Убедитесь, что брандмауэр разрешает подключения по SSH:

Get-NetFirewallRule -Name *OpenSSH-Server* |select Name, DisplayName, Description, Enabled

Если правило отключено, включите его:

New-NetFirewallRule -Name sshd -DisplayName 'OpenSSH Server (sshd)' -Enabled True -Direction Inbound -Protocol TCP -Action Allow -LocalPort 22

Если правило отключено (состоянии Enabled=False) или отсутствует, вы можете создать новое входящее правило командой New-NetFirewallRule:

New-NetFirewallRule -Name sshd -DisplayName 'OpenSSH Server (sshd)' -Enabled True -Direction Inbound -Protocol TCP -Action Allow -LocalPort 22

Конфигурация файла sshd_config

Конфигурационный файл OpenSSH сервера находится по пути C:\ProgramData\ssh\sshd_config. Вы можете отредактировать его через любой текстовый редактор. Например, откройте файл с помощью блокнота:

start-process notepad C:\ProgramData\ssh\sshd_config

1. Запрет подключения для пользователей/групп:

— Запретить подключение для определенного пользователя:

DenyUsers softcomputers\admin@192.168.1.10
DenyUsers corp\*

— Разрешить доступ только для локальной группы:

AllowGroups sshadmins

2. Изменение порта SSH:

Для смены порта измените значение директивы Port.

После изменений не забудьте перезапустить службу:

Restart-Service sshd

3. Чтобы разрешить подключение только для определенной доменной группы:

AllowGroups softcomputers\sshadmins

По умолчанию могут к openssh могут подключаться все пользователи Windows. Директивы обрабатываются в следующем порядке: DenyUsers, AllowUsers, DenyGroups,AllowGroups.

4. Можно запретить вход под учетными записями с правами администратора, в этом случае для выполнения привилегированных действий в SSH сессии нужно делать runas.

DenyGroups Administrators

Следующие директивы разрешают SSH доступ по ключам и по паролю

PubkeyAuthentication yes
PasswordAuthentication yes

5. Вы можете изменить стандартный SSH порт TCP/22, на котором принимает подключения OpenSSH в конфигурационном файле sshd_config в директиве Port.

6. После любых изменений в конфигурационном файле sshd_config нужно перезапускать службу sshd:

restart-service sshd

Подключение по SSH к Windows компьютеру

Для подключения к Windows через SSH можно использовать любые SSH клиенты (например, PuTTY или встроенный клиент Windows). Пример команды для подключения:

ssh alexbel@192.168.31.102

В этом примере alexbel – имя пользователя на удаленном Windows компьютере, и 192.168.31.102 – IP адрес или DNS имя компьютера.

Обратите внимание что можно использовать следующие форматы имен пользователей Windows при подключении через SSH:

alex@server1 – локальный пользователь Windows

alex@softcomputers.org@server1 – пользователь Active Directory (в виде UPN) или аккаунт Microsoft/ Azure(Microsoft 365)

softcomputers\alex@server1 – NetBIOS формат имени

Если используется аутентификация по Kerberos в домене, включите ее в конфигурационном файле:

GSSAPIAuthentication yes

После этого можно прозрачно подключать к SSH серверу с Windows компьютера в домене из сессии доменного подключения. В этом случае пароль пользователя не указывается и выполняется SSO аутентификация через Kerberos:

ssh -K server1

При первом подключении появится стандартный запрос на добавление узла в список известных SSH хостов.

Нажимаем — «Да»

В открывшееся окне авторизуемся под пользователем Windows.

При успешном подключении запускается командная оболочка cmd.exe со строкой-приглашением.

admin@win10tst C:\Users\admin>

В командной строке вы можете выполнять различные команды, запускать скрипты и приложения.

Чтобы запустить интерпретатор 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

Логи SSH подключений пишутся в журнал событий Windows через Event Tracing for Windows (ETW). Чтобы просмотреть логи:

1. Откройте Event Viewer (eventvwr.msc).

2. Перейдите в Application and Services Logs -> OpenSSH -> Operational.

Пример события успешного подключения по паролю:

EventID: 4

sshd: Accepted password for user1 from 192.168.31.102 port 55432 ssh2

Если необходимо, вы можете настроить запись логов в текстовый файл. Для этого добавьте в файл sshd_config директивы:

SyslogFacility LOCAL0

LogLevel INFO

Перезапустите службу sshd для применения изменений и проверьте, что теперь логи SSH сервера пишутся в файл C:\ProgramData\ssh\logs\sshd.log

Теперь вы знаете, как настроить и использовать OpenSSH сервер на Windows для удаленного подключения по защищенному протоколу SSH.

В современных версиях 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).

Установка openssh сервера из панели параметры windows 10

На изолированных от интернета компьютерах вы можете установить компонент с 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

установочный msi файл openssh server для windows

Также вы можете вручную установить 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

проверить что установлен OpenSSH сервер в windows 10

Настройка 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

Start-Service sshd - запустить openssh

С помощью nestat убедитесь, что теперь в системе запущен SSH сервер и ждет подключений на порту TCP:22 :

netstat -na| find ":22"

nestat - порт 22 ssh сервера windows

Проверьте, что включено правило брандмауэра (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

правило firewall для доступа к windows через ssh

Если правило отключено (состоянии 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 хостов.

putty сохранить ключ

Нажимаем Да, и в открывшееся окне авторизуемся под пользователем Windows.

ssh сессия в win 10 на базе openssh

При успешном подключении запускается командная оболочка cmd.exe со строкой-приглашением.

admin@win10tst C:\Users\admin>

В командной строке вы можете выполнять различные команды, запускать скрипты и программы.

подключение к windows 10 через ssh

Я предпочитаю работать в командной строке PowerShell. Чтобы запустить интерпретатор PowerShell, выполните:

powershell.exe

powershell.exe в ssh сессии windows

Чтобы изменить командную оболочку (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

openssh - изменить shell по умолчанию на powershell

Осталось перезапустить SSH подключение и убедиться, что при подключении используется командный интерпретатор PowerShell (об этом свидетельствует приглашение
PS C:\Users\admin>
).

powershell cli в windows 10 через ssh

В 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

события подключения к openssh сервер windows в event viewer

Если была выполнена аутентификация с помощью 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

текстовый sshd.log в windows

Как вы уже знаете, из предыдущей статьи, Windows 10 включает в себя встроенное программное обеспечение SSH — клиент, и сервер! В этой статье мы рассмотрим, как включить SSH-сервер.

Примечание: Приложение OpenSSH Server позволит вам установить соединение с вашим компьютером с использованием протокола SSH. Это не позволит вам получить доступ к другим компьютерам в вашей сети. Чтобы подключиться к другим компьютерам, вы должны установить клиент OpenSSH.

В Windows 10, Microsoft, наконец, прислушалась к просьбам пользователей и добавила поддержку протокола OpenSSH в версии обновления Fall Creators.

На момент написания данной статьи, программное обеспечение OpenSSH, включенное в Windows 10, находится на стадии BETA. Это означает, что у него могут быть проблемы с стабильностью.

Предоставленный SSH-сервер похож на приложение Linux. На первый взгляд, он поддерживает те же функции, что и его аналог * NIX. Это консольное приложение, но оно работает как служба Windows.

Как включить сервер OpenSSH в Windows 10.

  1. Откройте приложение «Параметры» и перейдите в «Приложения» →  «Приложения и возможности».
  1. Справа нажмите «Управление дополнительными компонентами».

  1. На следующей странице нажмите кнопку «Добавить компонент».

  1. В списке компонентов выберите OpenSSH Server и нажмите кнопку «Установить», это установит программное обеспечение OpenSSH Server в Windows 10

  1. Перезагрузите Windows 10.

Также вы можете установить  клиент SSH с помощью PowerShell.

Откройте PowerShell от имени Администратора и выполните следующую команду и перезагрузите систему:

Get-WindowsCapability -Online | Where-Object{$_.Name -like “OpenSSH.Server*”}

Файлы OpenSSH Server находятся в папке c:\windows\system32\Openssh. Помимо клиентских приложений SSH, папка содержит следующие серверные инструменты:

  • SFTP-server.exe
  • SSH-agent.exe
  • SSH-keygen.exe
  • sshd.exe
  • конфигурационный файл «sshd_config».

Сервер SSH настроен для работы в качестве службы.

На момент написания этой статьи он не запускается автоматически. Вам нужно включить его вручную.

Как запустить сервер OpenSSH в Windows 10.

  1. Откройте Службы, (нажмите клавиши Win + R и введите  services.msc в поле «Выполнить») и запустите службу sshd. дважды кликните на запись sshd, чтобы открыть ее свойства.

  1. На вкладке «Вход в систему» см. Учетную запись пользователя, которая используется сервером sshd. В моем случае это  NT Service \ sshd 

  1. Теперь откройте командную строку или PowerShell от имени администратора .

С помощью этой команды перейдите в каталог \ Openssh

cd c:\windows\system32\Openssh
  1. Здесь запустите команду для создания ключей безопасности для сервера sshd:
ssh-keygen -A

Сервер Sshd сгенерирует ключи

  1. Теперь в командной строке введите: explorer.exe, чтобы запустить Проводник в папке OpenSSH.

  1. Кликните правой кнопкой мыши файл ssh_host_ed25519_key и измените владельца файла на пользователя службы sshd, например  NT Service\sshd.

  1. Нажмите кнопку «Добавить» и добавьте разрешение «Чтение» для пользователя «NT Service\sshd».
  2. Теперь удалите все другие разрешения, чтобы получить что-то вроде этого:

  1. Нажмите «Применить» и подтвердите операцию.
  1. Наконец, откройте службы (нажмите клавиши Win + R и введите  services.msc в поле «Выполнить») и запустите службу sshd. Она должна запустится:

Служба Sshd работает.

  1. Теперь необходимо разрешить использование SSH-порта в брандмауэре Windows. По умолчанию сервер использует порт 22. Запустите эту команду в командной строке или PowerShell от имени администратора:
netsh advfirewall firewall add rule name="SSHD Port" dir=in action=allow protocol=TCP localport=22

  1. Наконец, установите пароль для своей учетной записи пользователя, если у вас его нет.

Теперь вы можете попробовать его в действии.

Подключение к SSH-серверу в Windows 10.

Откройте свой ssh-клиент. Вы можете запустить его на том же компьютере, например, используя встроенный клиент OpenSSH  или запустить его с другого компьютера в своей сети.

В общем случае синтаксис для клиента консоли OpenSSH выглядит следующим образом:

Имя пользователя ssh @ host -p

В моем случае команда выглядит следующим образом:

ssh alex_@192.168.1.126

Где alex_ — мое имя пользователя Windows, а  192.168.1.126 — это IP-адрес моего ПК с Windows 10. Я подключусь к нему с другого компьютера, Windows 10.

Вход.

Сервер запускает классические консольные команды Windows, например: more, type, ver, copy.

Но я не могу запустить FAR Manager. Он выглядит совсем сломанным:

Еще одно интересное примечание: вы можете запускать приложения с графическим интерфейсом, такие как проводник. Если вы вошли в ту же учетную запись пользователя, которую используете для SSH, они будут запускаться на рабочем столе:

Встроенный SSH-сервер определенно интересен. Он позволяет управлять компьютером сWindows 10, без установки сторонних инструментов, как rdesktop и др..

Начиная с этой версии, встроенный SSH-сервер в Windows 10 находится на стадии BETA, поэтому в будущем он должен стать, более интересным и полезным.

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:

  1. Go to the Settings > Apps > Apps and features > Optional features (or run the command ms-settings:appsfeatures)

  2. 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

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.

  1. Go to Settings > Apps > Optional features;
  2. Click View Features;
    ssh to windows server

Select OpenSSH Server from the list and click Next > Install;

ssh into windows machine

Wait for the installation to complete.

connect to windows via ssh

The OpenSSH binaries are located in the C:\Windows\System32\OpenSSH\ folder.

ssh to windows machine

Configuring SSH Service on Windows 10 and 11

Check the status of ssh-agent and sshd services using the PowerShell command Get-Service:

how to ssh to windows

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.

how to ssh to windows 10

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, and AllowGroups.

After making changes to the sshd_config file, you need to restart the sshd service:

Get-Service sshd | Restart-Service –force

ssh to a windows machine

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 to a windows machine

This is a tutorial that teaches you how to install and configure an SSH server on a Windows 11 machine.

We will present the tutorial in a simple way and with many figures that will help you follow the steps to install the Open SSH server on your Windows.

To follow this tutorial, it is important that the Windows machine is connected to the Internet to allow the OpenSSH Server App to be downloaded and installed.

Table Of Contents

  1. Installing Open SSH Server
  2. Starting SSH server in Windows 11
    • Configure OpenSSH Server to boot alongside Windows
  3. Testing SSH Server on Windows 11
    • Checking if SSH server port 22 is open
    • Checking the internal IP of the Windows machine
    • Testing SSH access within the server
    • To exit the SS connectionH
  4. Using another machine to access the Windows SSH server
  5. Configuring Windows Firewall for SSH Server
  6. Creating a user to access the SSH server on Windows
  7. Important Points When Using an SSH Server on Windows 
    • The Administrator Password for the SSH server
    • Updates: Why Not Every Reminder Can Be Ignored 
    • Firewall: The Digital Bodyguard 
    • Backups: The Plan B Everyone Forgets About Until You Need It 
    • Key Authentication: Why Sometimes Less Is More 

Installing Open SSH Server

To install the SSH server on our Windows 11, we will right-click on the window icon that appears in the bottom menu of Windows.

Next, we will click on the “Settings” option that appears in the new menu.

In the next menu that appears, click on the icon shown in the figure below.

Now, let’s click on “Apps” as shown in the figure below. This icon will allow us to access some apps for installation on Windows 11.

The next step is to click on “Optional features”, following the example in the figure below.

Next, we will click on “View features” as in the figure below. This option is within the same tab as “Add an optional feature”.

In the first search field of this menu, we will type Open and then click on the “OpenSSH Server” checkbox. After that, we will click on “Next”.

Then, we will see a screen like the one in the figure below and click on “Install” to confirm that we want to install Open SSH Server on Windows 11.

After clicking “Install”, we will see a screen that demonstrates the OpenSSH Server installation process. Let’s wait until it is installed as in the pictures below.

Starting SSH server in Windows 11

To start the SSH server on our Windows, we will click on the magnifying glass that appears in the bottom menu.

Next, we will type Services and we will see that a Services icon appears just below the menu as shown in the figure below. So let’s click on Services.

Now, let’s look for “OpenSSH SSH Server” and when we find it, click and we will see the “Start” option on the left part of the menu. Let’s click on Start so that the SSH server starts on our Windows 11.

Configure OpenSSH Server to boot alongside Windows

To make the OpenSSH server start every time Windows starts, let’s right-click on “OpenSSH SSH Server”. When clicking with the right mouse button we will see a menu and within that menu we will click on “Properties” as in the figure below.

Next, we will change the “Startup type” option to “Automatic”, following the figure below. This way, every time the Windows 11 machine starts up the SSH server will start up too. Then we will click on “OK”.

We can see that the OpenSSH SSH Server service is now Running and is also in Automatic mode.

Testing SSH Server on Windows 11

We are going to do some tests to identify whether our SSH server is working correctly within Windows 11. If some of the tests do not occur as expected, it may be necessary to create a rule in the Windows Firewall or create a common user to be able to access the server SSH.

Checking if SSH server port 22 is open

Now let’s see if port 22 on the ssh server is open waiting for connections.

To do this, we will click on the magnifying glass that appears in the bottom menu.

Next we will type cmd and click on the “Command Prompt” icon.

After clicking on the “Command Prompt” icon we will see a terminal. Inside the terminal, let’s type the command below to check the ports that are open. Our objective is to check if port 22 is open as in the figure below.

netstat -an

We can see that port 22 is open and waiting for connections.

Note. It may be that after executing the command “netstat -an” you need to go to the top of the screen at the moment you gave the command. This is because we gave you the command in a simplified way and will show several connections on your Windows machine.

Checking the internal IP of the Windows machine

Within the same terminal that we used to check port 22, we can use the following command to find out the IP of the machine.

ipconfig

By typing ipconfig we can see several IPs. However, let’s look for the IP that belongs to our internal network. In our case, the internal network is 192.168.56.0/24 so the IP we are interested in is IP 192.168.56.3.

In your case you need to check which IP is within your internal network.

Testing SSH access within the server

Within the terminal we just used, we can use the command below to test the connection to our SSH server.

To test access to the ssh server within the Windows machine, we will use the command ssh + our user + loopback IP . The loopback IP is an internal IP that machines have and we generally use “127.0.0.1”. In this command we will use a user called “test” that we created to carry out tests with the Windows SSH server. Therefore, we will use the command below.

ssh [email protected]

After entering the user password, we will have the screen below showing that the connection was successful.

To exit the SS connectionH

To exit a connection to the Windows SSH server, we can use the exit command.

As in the example below, we were logged in and simply typed exit and pressed ENTER.

exit

Using another machine to access the Windows SSH server

On another machine on the same network, we can open a terminal and type “ssh user@windowsIP”.

In our case we will use the user is test and the IP is “192.168.56.3”, so we will use the command below. Remembering that the test user is a user of our Windows machine and this machine has the IP “192.168.56.3”.

ssh [email protected]

The first time you access server SSH you will have to answer yesto continue. After that, enter your Windows user’s password.

Note. Use the username of your Windows machine and use the IP of your Windows machine.

After entering the password, you will see a screen like the one below that indicates that you have logged into Windows.

And congratulations, you have completed the installation and configuration of the SSH server on a Windows 11 machine.

Configuring Windows Firewall for SSH Server

In many cases it is not necessary to create the rule in the firewall, this is because when we install OpenSSH Server on Windows 11 the firewall is already configured to allow access to the network.

However, it is worth checking whether the OpenSSH Server has network access. To do this, click on the magnifying glass in the bottom menu.

And then we will type firewall and then click and m “Firewall & network protection”.

Next, we will click on “Allow an app through firewall”.

Now, let’s look for the OpenSSH Server app and check if the Private and Public boxes are checked.

In our case, the Private and Public boxes were already checked and there was no need to do anything. However, if it is not checked in your case, you will click on “Change settings” and you will be able to check the Private and Public boxes and then click OK.

Creating a user to access the SSH server on Windows

To access the OpenSSH server on Windows 11, we need a local user on Windows. In this case, we can use a standard user, or we can create a user to access the SSH server.

Below we will demonstrate how to create a new user to access using the SSH server.

To do this, let’s click on the magnifying glass in the bottom menu.

Next we will type terminal and then we will click with the right mouse button on the terminal icon and we will click on Runs as administrator .

Inside the terminal, let’s type the command below to create a user test and the password test123.

net user test test123 /add

And that’s it, now you have a new user to test with your SSH server on the Windows 11 machine.

Important Points When Using an SSH Server on Windows 

Let’s talk here about some points that I consider important to consider when we are planning to install an SSH server on a Windows machine.

The Administrator Password for the SSH server

Ah, the passwords… Choosing a good password for your OpenSSH server administrator is like choosing the winner on a reality show: it has to be strong, memorable, and preferably not the same name as your dog. Use a combination of letters, numbers and symbols. And, of course, avoid the classic “123456” or “password”. If you do this, even my great-great-grandfather, who never used a computer, will be able to access your server.

Updates: Why Not Every Reminder Can Be Ignored 

Keep your system and OpenSSH up to date. Ignoring security updates is like forgetting your best friend’s birthday: sooner or later, it’s going to lead to problems. The updates contain fixes for vulnerabilities that, if left unaddressed, could turn your server into a party house for non-peaceful beings. 

Firewall: The Digital Bodyguard 

Configuring the firewall is essential. It’s like having a bodyguard for your server, only he won’t ask for a raise. Make sure that only the necessary ports are open, especially the SSH port (usually 22), to avoid unwanted visitors. 

Backups: The Plan B Everyone Forgets About Until You Need It 

Make regular backups of important settings and data. Backup is that plan B that everyone forgets about until plan A collapses, like that umbrella you never remember to take until you get caught in the rain. 

Key Authentication: Why Sometimes Less Is More 

Consider using key authentication instead of passwords. It’s safer and avoids the daily spectacle of trying to remember which password you used. Plus, it’s like having a VIP pass: only those who have the key can enter. 

In short, treating your OpenSSH server like a castle can not only bring some fun to the world of computing, but also ensure that the main bases of security and efficiency are covered. And remember, in the world of technology,  timing is everything! 

See more:

Install Open VPN on Linux

Install OpenVPN Client on Windows

Update OpenVPN Client on Linux

Install and Configure OpenVPN Server on PfSense

OpenVPN and PfSense Site to Site

Access Internet through site to site VPN

OpenVPN Revoke Certificate

https://www.openssh.com/

Juliana Mascarenhas

Data Scientist and Master in Computer Modeling by LNCC.
Computer Engineer

How to Create a Network with a Switch in Packet Tracer – Step-by-Step Guide for Beginners

In this practical tutorial, I will show you how to create a simple switch network…

Why use Kali Linux inside VirtualBox?

In this article, we will see the main reasons for considering the use of Kali…

How to install pfBlocker on pfSense: step by step guide

Today we will learn how to install pfBLocker NG in PFSense. pfBLocker is an excellent…

Packet Tracer for Dummies: Setting Up Your First Network with 2 PCs (Quick Start Guide)

Are you ready to take the first step into the fascinating world of computer networks?…

Learn how to use the curl command: tutorial with practical examples

Today we are going to learn about the curl command in Linux! This command is…

How to Install Kali Linux on VirtualBox: Step-by-Step Guide for Beginners

Welcome to the ultimate guide for beginners who want to learn how to install Kali…

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Desktop windows xaml source что это
  • Как удалить ccleaner с компьютера полностью windows 10
  • Microsoft store повторите попытку позже возникла внутренняя проблема windows 11
  • Srttrial txt windows 10 проблема как решить
  • Как очистить папку winsxs в windows server 2012 r2