Как переустановить ssh windows 10

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

On older versions of Windows, i.e. Windows Vista, 7, and 8/8.1, getting SSH running wasn’t easy. You had to do quite a bit to set it up. This was true for Windows 10 up to the Creators Update. The Fall Creators Update is a different story though; you can now install OpenSSH on Windows 10 as an optional feature. You can install both the OpenSSH client, and the OpenSSH Server.

Open the Settings app and go to the Apps group of settings.

Go to the Apps & features tab and click ‘Manage optional features’.

The Manage Optional Features screen only lists language packs. To view other features that you can install, click the Add a Feature button.

Look for the OpenSSH Client or OpenSSH Server feature. Click it, and click the Install button. Wait for it to install and that’s about it. You can install either one or both OpenSSH client and OpenSSH Server using this same method. We should mention that it is in Beta so expect the usual bugs that you can expect from Microsoft.

You will have additional things to set up, but OpenSSH is there and you can use SSH now to securely connect to a server, among other things.

Uninstall OpenSSH

To uninstall OpenSSH on Windows 10, open the Settings app and go to Apps>Apps & features. Click Manage options features again. This time, scan the list of installed optional features i.e. the list that normally shows you the language packs that can be installed. OpenSSH both sever and client will appear here if they’re installed. Click it and click the Uninstall button.

Given both OpenSSH client and server are in beta, you can expect bugs but you should also be prepared for a lesser product offering. Most users will likely compare it to Putty and it doesn’t stack up just yet.

The Fall Creators Update arrived this October so this feature is more or less still in its very early stages, its infancy if you will. That’s both good and bad. Bad because it mean bugs and limited functionality and good because it means users can hope for improvements and they can hope that one day it will stack up again Putty.

The team at Microsoft responsible for developing OpenSSH has a rough road map that might give you an idea on what to expect. Mind you, this road map isn’t the most recent. Windows 10 has had support for SSH for a while now but before the Fall Creators Update, users who wanted to install OpenSSH on Windows 10 had to install it via Github. If you still haven’t upgraded to the Fall Creators Update, or you’re interested in trying the most recent versions of OpenSSH, you can do so from the project’s Github page.

default avatar image

Fatima Wahab

Fatima has been writing for AddictiveTips for six years. She began as a junior writer and has been working as the Editor in Chief since 2014.

Fatima gets an adrenaline rush from figuring out how technology works, and how to manipulate it. A well-designed app, something that solves a common everyday problem and looks

Table of Contents

Native SSH Client in Windows 10

The built-in SSH client appeared in Windows 10 and Windows Server 2019. ssh.exe can be used to securely connect to Linux/UNIX servers, VMWare ESXi hosts and other devices instead of Putty. The native Windows SSH client is based on the OpenSSH port and is preinstalled in Windows starting from Windows 10 build 1809.

The OpenSSH client is included in Windows 10 Features on Demand. The SSH client is installed by default on Windows Server 2019, Windows 10 1809 and newer builds.

Install OpenSSH Client using PowerShell

1️⃣ Check that the SSH client is installed. Open Windows PowerShell then run bellow command. In my example, the OpenSSH client is installed (State: Installed)

Get-WindowsCapability -Online | ? Name -like 'OpenSSH.Client*'
Name  : OpenSSH.Client~~~~0.0.1.0
State : Installed

#Output when OpenSSH client not installed 
Name  : OpenSSH.Client~~~~0.0.1.0
State : NotPresent

2️⃣ If not (State: Not Present), you can install it using the PowerShell command: Add-WindowsCapability -Online -Name OpenSSH.Client*

Add-WindowsCapability -Online -Name OpenSSH.Client*
Path          :
Online        : True
RestartNeeded : False

Alternatively, OpenSSH Client can be enabled using DISM as below:

dism /Online /Add-Capability /CapabilityName:OpenSSH.Server~~~~0.0.1.0
Deployment Image Servicing and Management tool
Version: 10.0.19041.844

Image Version: 10.0.19044.1706

[==========================100.0%==========================]
The operation completed successfully.

Install OpenSSH Client using Windows Settings

If you don’t want to do it using PowerShell. You can enable it from Windows Settings.

1️⃣ Open Settings -> Apps -> Manage optional features.

2️⃣ Select +Add features.

3️⃣ Search for OpenSSH client in the list and click Install button.

Connect to a remote system with SSH

OpenSSH binary files are located in C:\Windows\System32\OpenSSH\.

  • ssh.exe – the SSH client executable;
  • scp.exe – tool for copying files in an SSH session;
  • ssh-keygen.exe – tool to generate RSA SSH authentication keys;
  • ssh-agent.exe – used to manage RSA keys;
  • ssh-add.exe – adds a key to the SSH agent database.
PS C:\WINDOWS\system32\OpenSSH> dir

    Directory: C:\WINDOWS\system32\OpenSSH

Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
-a----          1/8/2022   4:09 PM         307712 scp.exe
-a----          1/8/2022   4:09 PM         374272 sftp.exe
-a----          1/8/2022   4:09 PM         481280 ssh-add.exe
-a----          1/8/2022   4:09 PM         382976 ssh-agent.exe
-a----          1/8/2022   4:09 PM         662016 ssh-keygen.exe
-a----          1/8/2022   4:09 PM         557568 ssh-keyscan.exe
-a----          1/8/2022   4:09 PM         946176 ssh.exe

Once done, now we can use the Windows PowerShell to connect to a Linux machine using SSH natively.

When you connect to a machine using SSH. For the first time you will need to accept the host’s key. Just type yes then hit Enter.

PS C:\> ssh [email protected]

The authenticity of host '10.10.6.22 (10.10.6.22)' can't be established.
ECDSA key fingerprint is SHA256:PeU7o9cNTIhcNPGtYOOPXs/p8b4WfMLJ752yMUPO/Ts.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes

Warning: Permanently added 10.10.6.22' (ECDSA) to the list of known hosts.
[email protected] password:
Last login: Mon May 30 02:36:11 2022 from 20.232.18.206

If you have SSH running on a different port than the default port 22, then you can change the port number with the -p flag:

Home

Windows

By

Anup Thapa


How to Install OpenSSH on Windows

Until recently, if you wanted to use SSH on Windows, you’d need to rely on third-party clients like PuTTY or install SSH server packages from similar sources.

However, the April 2018 update (version 1803) introduced OpenSSH as a built-in feature. As long as you’re running supported Windows versions, you can install the OpenSSH client and server components as optional features.

As such, we’ll cover the prerequisites, full steps to install OpenSSH using various methods, and how to get started with it in this article.

How to Install OpenSSH

Before you begin, you’ll want to ensure the following requirements are met:

  • Windows Server 2019 or later / Windows 10 build 1809 or later
  • PowerShell 5.1 or later
  • Your account is a member of the Administrators group

Optional Features (GUI)

The easiest way to install OpenSSH on Windows is from the Optional Features page in Windows Settings.

  1. Press Win + I and go to Apps > Optional Features.
  2. Click on View features in the Add an optional feature section.
    add-an-optional-feature

  3. Select OpenSSH Client and OpenSSH Server from the list and press Next > Install.
    install-openssh-client-server

  4. After the components are installed, press Win + R, type services.msc, and press Enter.
  5. Locate the OpenSSH SSH Server and OpenSSH Authentication Agent services here.
    openssh-ssh-server-service-sshd

  6. Double-click them and start these services. If you want, you can also change the startup type to Automatic. Save the changes afterward.
    sshd-startup-type-automatic

  7. Next, press Win + R, type wf.msc, and press Enter.
  8. In the Inbound Rules section, ensure the OpenSSH SSH Server (sshd) rule is enabled.
    openssh-windows-firewall-rule

  9. The basic setup is complete. Check the Get Started with OpenSSH section for further steps. You can also follow the same steps to uninstall OpenSSH if required.

PowerShell

If you want to be more efficient, you can also perform the same steps as above in an elevated PowerShell window.

  1. Press Win + R, type powershell, and press CTRL + Shift + Enter.
  2. First, ensure that the OpenSSH components are available:
    Get-WindowsCapability -Online | Where-Object Name -like 'OpenSSH*'
    get-windows-capability-openssh

  3. Next, install the OpenSSH client and server components:
    Add-WindowsCapability -Online -Name OpenSSH.Client~~~~0.0.1.0
    Add-WindowsCapability -Online -Name OpenSSH.Server~~~~0.0.1.0
    add-windows-capability-openssh

  4. Start the sshd and ssh-agent services and change their startup type to Automatic as such:
    Set-Service -Name sshd -StartupType 'Automatic' -Status Running
    Set-Service -Name ssh-agent -StartupType 'Automatic' -Status Running
    set-service-sshd-status-running

  1. Next, configure the necessary Windows firewall rule for SSH traffic:
    New-NetFirewallRule -Name 'OpenSSH-Server-In-TCP' -DisplayName 'OpenSSH Server (sshd)' -Enabled True -Direction Inbound -Protocol TCP -Action Allow -LocalPort 22
    new-net-firewall-rule-ssh

  2. Now that the setup is complete, you can start using SSH. Refer to the get started with OpenSSH section if you need help with this.
  3. Also, if you want to uninstall the OpenSSH components, here are the necessary commands:
    Remove-WindowsCapability -Online -Name OpenSSH.Client~~~~0.0.1.0
    Remove-WindowsCapability -Online -Name OpenSSH.Server~~~~0.0.1.0
    remove-windows-capability-ssh

GitHub (MSI)

If you downloaded the OpenSSH package from GitHub, you can install the components using the MSI Installer with msiexec /i <path to openssh.msi>.

  • For instance, if the file is in your current directory, use
    msiexec /i openssh.msi
  • If the file is in, let’s say, your downloads folder, use
    msiexec /i C:\users\anup\downloads\openssh.msi
  • To uninstall OpenSSH, use
    msiexec /x <path to openssh.msi>
  • Let’s say the installer is in the current directory, and you want to install or remove certain components only. You can use the following commands as required:
    msiexec /i openssh.msi ADDLOCAL=Client
    msiexec /i openssh.msi ADDLOCAL=Server
    msiexec /i openssh.msi REMOVE=Client
    msiexec /i openssh.msi REMOVE=Server

After installing the components, follow these steps to update the system PATH variable:

  1. Press Win + R, type systempropertiesadvanced, and press Enter.
  2. Click on Environment Variables. In the System variables section, select Path and click on Edit.
    windows-system-path-variable

  3. Check for %systemroot%\System32\openssh here. If it isn’t present, click on New and add it to the list. Do note that this is the default installation path. If you installed OpenSSH on a different path, change the value accordingly for this step.
    openssh-system-path

  4. Press Ok > Ok to save the changes.

Now, you can run Get-Service -Name ssh* in PowerShell to verify that the components were installed properly. If you also need to start the required services or open ports, please refer to either of the earlier sections for the steps.

Finally, if you want to use other methods like Winget or Chocolatey, we recommend checking out the OpenSSH wiki on GitHub. In addition to install instructions, it also has various usage examples and manuals that you might find useful.

OpenSSH Server Configuration

By default, the OpenSSH server (sshd) in Windows reads the configuration data from %programdata%\ssh\sshd_config. Numerous configuration options are listed in this file, but as the Windows implementation of OpenSSH is still fairly new, only certain configurations are supported at present.

We’ve listed some commonly made configuration changes below for reference. We recommend checking the OpenSSH server configuration guide from Microsoft or the one on GitHub for the full list of options. Also, don’t forget to restart the sshd service to apply any changes made.

  1. Uncomment the Port line and change the value if you want to change the SSH port. You’ll also need to add a firewall rule to allow inbound traffic on said port.
    sshd-config-file

  2. Change the ListenAddress from 0.0.0.0 to something else if you only want to listen to a specific IP address. Add multiple ListenAddress lines in the same manner if you want to listen to multiple IP Addresses.
  3. Change GSSAPIAuthentication to yes if you want to use Kerberos authentication.
  4. Add the AllowGroups, AllowUsers, DenyGroups, and DenyUsers directives to control which groups and users can access the SSH server.
    • If working with domain users and groups, check the following examples for format reference:
      DenyUsers tnt\admin@192.168.10.17
      DenyUsers tnt\*
      AllowGroups tnt\sshclients tnt\serveradmins
    • If dealing with workgroup users and groups, check these examples instead:
      AllowUsers anup@192.168.10.17
      AllowGroups sshclients
  5. Finally, you can use the following command in PowerShell to set the default OpenSSH shell to PowerShell instead of command prompt:
    New-ItemProperty -Path "HKLM:\SOFTWARE\OpenSSH" -Name DefaultShell -Value "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -PropertyType String -Force
    change-ssh-default-shell-to-powershell

Get Started With OpenSSH

You can use any of the methods listed above to set up another Windows system as an OpenSSH client, server, or both. And if you’re new to SSH, here are some basic steps to get started:

  1. First, press Win + R, type sysdm.cpl, and press Enter.
  2. Check if you’re a Workgroup or Domain user here.
    system-properties-workgroup-domain

  3. Press Win + R, type powershell, and press Enter.
  4. If you’re a workgroup user, enter the following command and skip to Step 6:
    ssh user@host
    ssh-user@host

  5. If you’re a domain user, enter any of the following commands:
    ssh -l user@domain host
    ssh domain\user@host
    ssh user@domain@host
    ssh user@host
    ssh-domain-user-command

  1. On the first login, you’ll have to confirm that the host is trusted. If you enter Yes, the host will be added to the list of known hosts.
    ssh-fingerprint

  2. Now, input the host account’s password and press Enter.

Password-based authentication is generally fine, but ideally, you should use even more secure authentication methods like Kerberos and SSH keys. For Kerberos, follow the steps listed below:

  1. On the domain-joined server, navigate to %programdata%\ssh\.
  2. Open the sshd_config file with a text editor.
  3. Uncomment the GSSAPIAuthentication line, set it to yes, and save the changes.
    gssapi-authentication-yes-sshd-config

  4. In Powershell, use the following commands to restart the sshd service and apply the changes from above:
    net stop sshd
    net start sshd
    net-stop-sshd-net-start-sshd

  5. Now, on the Windows client that’s logged in as a Domain user, enter ssh -K hostname.

Authenticate With SSH Key

When connecting across domains, password-based authentication isn’t recommended as its vulnerable to brute forcing. Instead, you should use public key authentication. This uses cryptographic algorithms to generate one public and one private key file.

A user’s public key is stored on the SSH server, and it’s compared with the client-side private key for authentication. As long as the private key is protected properly, this authentication method is much more secure.

You’ll need to generate the key pair on the client system, create an authorized keys file on the server, and store the client’s public key in this file. To do this, start with the following steps on the server system:

  1. Press Win + R, type powershell, and press CTRL + Shift + Enter.
  2. Create the administrators_authorized_keys file.
    • For users in the Administrators group:
      New-Item -Type File -Path C:\ProgramData\ssh\administrators_authorized_keys
    • For standard users:
      New-Item -Type File -Path C:\Users\username\.ssh\administrators_authorized_keys
  3. In our case, we created the file using an Administrator account. If you’re using a standard account, change the file path accordingly in the rest of the commands.
  4. Set the access permissions for the keys file with:
    get-acl C:\ProgramData\ssh\ssh_host_dsa_key | set-acl C:\ProgramData\ssh\administrators_authorized_keys

Now, launch an Elevated PowerShell window on the client system and follow these steps:

  1. Use cd ~/.ssh to get to the .ssh directory and generate the key pair with ssh-keygen.
    ssh-keygen-generate-public-private-rsa-key

  2. When prompted for the file location, press Enter to use the default value :
    C:\Users\username\.ssh\
  3. Add a passphrase for your private key if you want to further improve its security.
    ssh-keygen-randomart-image

  4. Now, change the user and host values and run the commands shown below. It will append the client’s public key to the authorized keys file on the server.
    • $public_key = Get-Content ~/.ssh/id_rsa.pub
    • ssh user@host "'$($public_key)' | Out-File C:\ProgramData\ssh\administrators_authorized_keys -Encoding UTF8 -Append"
      append-ssh-client-public-key-to-server

  5. Enter your password to approve the operation. Now, you’ll be able to connect using public key authentication.

Troubleshooting Common Errors

SSH Errors like Port 22 Connection Refused, or Connection Timed Out are pretty common. If you followed the steps from this article, basic steps like ensuring the SSH services are running, restarting them, allowing SSH traffic through the firewall, adding SSH to system PATH, etc., will already be covered.

In addition to these, here are some more troubleshooting steps worth trying:

  • First, make sure the steps mentioned above are done on the remote system as well.
  • Retry and make sure you entered the correct credentials.
  • Use the host’s IP address instead of the hostname. If this works, resolve DNS problems by flushing the cache or using a different server.
  • Ping the host to ensure there’s no packet loss.
  • Check the SSH port and ListenAddress in the server’s sshd_config file.
  • Use verbose flags (ssh -v or ssh -vvv) to get more details on what’s going wrong.

Клиент 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.

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

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Как поменять системный язык в windows 11
  • Windows отменить обновление драйвера
  • Как изменить код установки windows
  • Windows 11 как сдвинуть меню пуск влево
  • Windows server 2019 remote desktop services per device client access license enterprise agreement