В современных версиях 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
Как вы уже знаете, из предыдущей статьи, 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.
- Откройте приложение «Параметры» и перейдите в «Приложения» → «Приложения и возможности».
- Справа нажмите «Управление дополнительными компонентами».
- На следующей странице нажмите кнопку «Добавить компонент».
- В списке компонентов выберите OpenSSH Server и нажмите кнопку «Установить», это установит программное обеспечение OpenSSH Server в Windows 10
- Перезагрузите 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.
- Откройте Службы, (нажмите клавиши Win + R и введите services.msc в поле «Выполнить») и запустите службу sshd. дважды кликните на запись sshd, чтобы открыть ее свойства.
- На вкладке «Вход в систему» см. Учетную запись пользователя, которая используется сервером sshd. В моем случае это NT Service \ sshd
- Теперь откройте командную строку или PowerShell от имени администратора .
С помощью этой команды перейдите в каталог \ Openssh
cd c:\windows\system32\Openssh
- Здесь запустите команду для создания ключей безопасности для сервера sshd:
ssh-keygen -A
Сервер Sshd сгенерирует ключи
- Теперь в командной строке введите: explorer.exe, чтобы запустить Проводник в папке OpenSSH.
- Кликните правой кнопкой мыши файл ssh_host_ed25519_key и измените владельца файла на пользователя службы sshd, например NT Service\sshd.
- Нажмите кнопку «Добавить» и добавьте разрешение «Чтение» для пользователя «NT Service\sshd».
- Теперь удалите все другие разрешения, чтобы получить что-то вроде этого:
- Нажмите «Применить» и подтвердите операцию.
- Наконец, откройте службы (нажмите клавиши Win + R и введите services.msc в поле «Выполнить») и запустите службу sshd. Она должна запустится:
Служба Sshd работает.
- Теперь необходимо разрешить использование SSH-порта в брандмауэре Windows. По умолчанию сервер использует порт 22. Запустите эту команду в командной строке или PowerShell от имени администратора:
netsh advfirewall firewall add rule name="SSHD Port" dir=in action=allow protocol=TCP localport=22
- Наконец, установите пароль для своей учетной записи пользователя, если у вас его нет.
Теперь вы можете попробовать его в действии.
Подключение к 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, поэтому в будущем он должен стать, более интересным и полезным.
Introduction
So, are you ready to dive into the world of OpenSSH Windows 10? start openssh server windows is not easy, but it does not have to be! OpenSSH is a very powerful tool for secure connection to remote systems and minimal hassle management of these systems. It’s equally important for a developer as for anyone else interested in system security you have to know how to start the OpenSSH server on Windows 10.
Starting OpenSSH Server on Windows 10? Explore Now!
OpenSSH Server is a free utility for gaining start openssh server windows. It allows remote access to machines, hence providing a secure and encrypted data communication channel. You can execute commands, transfer files, and carry out any kind of administrative activity from any location on your Windows 10 computer through open SSH servers, which makes it extremely useful for developers and system administrators alike.
One of start openssh server windows is that it is easy to use. It integrates well with Windows 10, making it easy for users to access its strong capabilities without extensive setup or configuration.
How do you start an OpenSSH server on Windows 10?
It is easy to start openssh server windows 10 machine. But before you can do any of this, you must ensure that your version of Windows 10 comes with an installed OpenSSH feature: First, open Settings> Apps > Optional Features to make sure that OpenSSH Server is not listed by adding a feature, then open Windows Search, type, open, and install “OpenSSH Server.”
Once installed, you can start openssh server windows. Open PowerShell as an administrator and run the command Start-Service sshd. This command will activate the SSH service, allowing you to connect remotely to your machine. If you want the service to start automatically with Windows, start openssh server windows you could use Set-Service -Name sshd -StartupType ‘Automatic.’ In this way, you would not have to start it manually every time you turn on your computer!
How to Use Key-Based Authentication in OpenSSH for Windows?
Key-based authentication is a safe and efficient way to log into your SSH server without using passwords. Instead of typing your password each time, you can use a pair of public and private cryptographic keys. Here is how to set it up on Windows.
1 Generate SSH Key Pair
Open PowerShell or Command Prompt:
- Click on Start, type PowerShell or cmd, and then click Enter
Generate Key Pair
- Use the following command to generate an SSH key pair
When prompted, you may need to answer to enter the name of your chosen key.
Enter Pass Phrase(Optional):
- You will also be prompted to input an optional passphrase for maximum security. If you want to leave it blank, press Enter.
2 Copy the Public Key to the SSH Server
Open the Public Key:
- Locate your.ssh directory and find your public key file, usually named id_rsa.pub. You can paste its contents with
Copy the Public Key:
- You can either hand-copy it or use an start openssh server windows keys file on your server. If you have access to the server, you can log in using your password and type in this command line with bash, then copy: echo <paste your public key here> >> ~/.ssh/authorized_keys If that’s accessible on your machine, you may also want to use ssh-copy-id: bash Copy code ssh-copy-id user@hostname
Configuring the SSH Server for Key-Based Authentication :
Edit the SSH configuration file:
- On the server, you must edit the sshd configuration file (located in /etc/ssh/sshd_config) to enable public key authentication. Search for:
Restart the SSH Service:
- Now you’ve changed the settings, and now it’s time to restart the SSH service and apply the configuration:
Test Key-Based Authentication
Log In Using SSH:
- Now, let’s test your new key-based authentication by logging in to your SSH server:
- If everything is set up correctly, you should be logged in without being prompted for a password.
How to Enable Installing OpenSSH Server on Windows 10
It’s easy to enable the start openssh server windows. First of all, check if the feature of OpenSSH Server is installed. In order to do this, go to Settings and go to Apps > Optional Features. If you find an OpenSSH Server there, you can enable it right now. Hooray!
If it still needs to be installed, click Add a Feature at the top. Now, find the start openssh server windows and click on Install. After installation, you should start the service. So, open PowerShell and type the command Start-Service sshd as administrator. Also, you can configure it to start automatically at every boot by running the command Set-Service -Name sshd -StartupType ‘Automatic.’ And you are done; your OpenSSH Server is now ready to accept remote connections.
How to Install OpenSSH on Windows 10?
Installing start OpenSSH Windows . First, open your Settings, then select the Apps tab. Under Features, you will see that Optional Features is one that you need to click. Then, you scroll through all the available features but find that the OpenSSH Client and OpenSSH Server have already been installed.
If not, click on Add a Feature at the top of the page for Optional Features. Open the search box and enter “OpenSSH” to find the client and server options separately. Select the OpenSSH Client and OpenSSH Server and click Install.
Use the OpenSSH service on Windows 10+ hosts.
With the OpenSSH service on Windows 10 and above versions, the start openssh server windows. It’s one of the most important services that can be deployed for the management of numerous machines without the physical presence of system administrators. OpenSSH uses the SSH protocol for secure access to connect between the server and client, with encrypted data transferring from one to the other.
To install OpenSSH as a Windows service, you must install it on your Windows host. Once it is installed, you will be able to configure the service from the SSHD configuration file, usually at C:\\\\ProgramData\\\\ssh\\\\sshd_config. You can use the file to configure many parameters, including port numbers, authentication methods, and much more. start openssh server windows. The deployed service can then allow incoming SSH connections to help make remote management more accessible and secure!
How to Use Windows 10 SSH:
Trust me, using SSH on Windows 10 is easy and makes everything else possible for remotely working with systems. First, you need to turn on the OpenSSH client. This is done by opening PowerShell and typing in the ssh command, which, if done correctly, should open a window that includes instructions on how to use the application.
To initiate an SSH connection, open PowerShell or Command Prompt and type ssh username@hostname, substituting “username” for the remote machine’s actual username and “hostname” for its IP address or domain name. Pressing Enter will probably then ask for your password, which you can enter to access the remote machine’s command line.
Activation of Windows 10 SSH in a few words:
Activating SSH on Windows 10 is very fast and simple. First, you need to check if the OpenSSH Client is installed in your system. To do that, go to Settings > Apps > Optional features and look for “OpenSSH Client.” If you don’t find it there, you can add it by clicking on “Add a feature,” then searching for “OpenSSH Client,” and installing it.
Next, you must enable OpenSSH Server to allow incoming connections from another computer. You can search for it through Settings > Apps > Optional features, but search for “OpenSSH Server.” Once installed, start the SSH server by executing Start-Service sshd on PowerShell. To run the service automatically with Windows, use Set-Service -Name sshd -StartupType ‘Automatic’. And there you have it-after these steps, your Windows 10 SSH is configured and can be used.
How to Use the Windows 10 SSH Client
The Windows 10 SSH client is the easiest and most effective way to access remote systems with complete security. This is achieved by first accessing PowerShell or Command Prompt: you can find it by opening the “PowerShell” or “cmd” in Start. Once there, you will type the command as follows:
- Ssh username@hostname
- Replacing the “username” with the actual name on the remote machine and “hostname” with its IP address
Theain name.
- After
If you hit Enter, the SSH client will attempt to connect to the remote host specified. If it is your first time connecting to that host, you will be prompted to accept its authenticity. Just type “yes” and enter your remote user account password. Everything being perfect, you would get access to the terminal of the remote machine and be able to execute commands as if you were sitting right in front of it. It’s a very smooth way to manage remote servers, so SSH is a tool of choice for many users!
Conclusion:
Configuring and utilizing OpenSSH on Windows 10 to manage remote servers is straightforward and beneficial. The enabled OpenSSH server lets you safely connect to and control other machines from your Windows device. Whether personal projects or professional tasks are being done, SSH is the reliable and secure way to access files and execute commands remotely. With the help of this guide, you are now equipped with information that allows you to use OpenSSH optimally by enabling and using it correctly to enhance your experience on Windows and make access to your remote machine seamless.
FAQS:
What is the function of OpenSSH for Windows?
OpenSSH in Windows allows remote access over a secured environment. It then provides command-line features or interfaces through which orders can be made, and files can be transmitted.
Is OpenSSH installed in my Windows 10?
Click on settings > applications> optional features, then look for ‘openSSH Client’ and ‘openSSH Server’ if they exist.
Is OpenSSH available for Windows if I use something other than PowerShell?
Yes, you may use SSH commands using Command Prompt. However, PowerShell offers more advanced features and is better integrated into Windows.
Is OpenSSH secure?
Yes, OpenSSH encrypts data in transit, and thus OpenSSH is a secure remote access method.
How can I uninstall OpenSSH from Windows 10?
To uninstall OpenSSH, open Settings > Apps > Optional features, scroll through the list, and select OpenSSH. Tap the same to uninstall the software.
Is it possible to run multiple OpenSSH sessions at once?
Well, sure. You can launch multiple SSH sessions in a different window for your terminal, enabling you to connect to other servers simultaneously.
I forgot my SSH password; what do I do?
If you forget your SSH password on the remote server, you must reset it, usually by accessing it using some other method or through someone with administrative rights who resets it.
Latest post:
- How to convert the putty key to openssh windows?
- How to openssh via terminal windows?
- How to change default sftp location in openssh windows?
- What is the difference between OpenSSH and PuTTY?
- How to Install OpenSSH on Windows?
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
Клиент OpenSSH и сервер OpenSSH являются отдельными устанавливаемыми компонентами в Windows Server 2019 и Windows 10 1809. Чтобы установить сервер, открываем последовательно Параметры → Приложения → Приложения и возможности → Дополнительные возможности → Добавить компонент. Находим в списке компонент «Cервер OpenSSH» и нажимаем кнопку «Установить».
Установка сервера OpenSSH создаст и включит правило брандмауэра, которое разрешает входящий трафик SSH через порт 22.
Запускаем службу, при необходимости в Свойствах устанавливаем Автозапуск:
Проверяем подключение по ssh с другого компьютера:
$ ssh Evgeniy@192.168.110.2 The authenticity of host '192.168.110.2 (192.168.110.2)' can't be established. ECDSA key fingerprint is SHA256:SUosMa1VPeeaxU0Uyo5nG0EKkVEifMWYshHqRGIiz7I. Are you sure you want to continue connecting (yes/no)? yes Warning: Permanently added '192.168.110.2' (ECDSA) to the list of known hosts. Evgeniy@192.168.110.2's password: пароль
По умолчанию для сервера OpenSSH в ОС Windows используется командная оболочка Windows.
Настройка сервера OpenSSH
Компоненты OpenSSH хранятся в следующих каталогах:
- Исполняемые файлы OpenSSH:
C:\Windows\System32\OpenSSH\
- Конфигурационный файл
sshd_config
:C:\ProgramData\ssh\
- Журнал OpenSSH:
C:\ProgramData\ssh\logs\sshd.log
- Файл
authorized_keys
и ключи:~\.ssh\
- При установке в системе создается новый пользователь
sshd
Следующие директивы в sshd_config
разрешают доступ по ключам и по паролю:
# разрешает доступ по ключам PubkeyAuthentication yes # разрешает доступ по паролю PasswordAuthentication yes # доступ с пустым паролем запрещен PermitEmptyPasswords no
Можно изменить порт, на котором принимает подключения OpenSSH сервер:
Port 2222
После любых изменений в конфигурационном файле нужно перезапустить службу. Если был изменен порт — нужно еще изменить правило брандмауэра.
Установка с использованием PowerShell
Запускаем PowerShell от имени администратора. Проверяем, что OpenSSH сервер и клиент доступны для установки:
> Get-WindowsCapability -Online | ? Name -like 'OpenSSH*' Name : OpenSSH.Client~~~~0.0.1.0 State : Installed Name : OpenSSH.Server~~~~0.0.1.0 State : NotPresent
Клиент уже был установлен ранее, а сервер — еще нет. Запускаем установку сервера:
> Add-WindowsCapability -Online -Name OpenSSH.Server~~~~0.0.1.0
Если клиент еще не установлен, установить его можно так:
> Add-WindowsCapability -Online -Name OpenSSH.Client~~~~0.0.1.0
Запустить, остановить или перезапустить службу:
> Start-Service sshd
> Stop-Service sshd
> Restart-Service sshd
Изменить тип запуска службы на Автоматический:
> Set-Service -Name sshd -StartupType 'Automatic'
Для удаления OpenSSH сервера и клиента:
> Remove-WindowsCapability -Online -Name OpenSSH.Server~~~~0.0.1.0
> Remove-WindowsCapability -Online -Name OpenSSH.Client~~~~0.0.1.0
Поиск:
CLI • SSH • Windows • Команда • Конфигурация • Настройка • Сервер
Каталог оборудования
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
Производители
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
Функциональные группы
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.