Ssh config windows 10 где находится

How do I set the host name and port in a config file for Windows, using OpenSSH through PowerShell? As on Unix/Linux: Edit or create the file now by typing: nano ~/.ssh/config In here...

In Windows 10 with PowerShell, the configuration files are not created, so we have to create them ourselves.

This answer was done with: Windows 10 PRO 20H2 (Build 19042.804)
And with the last OpenSSH-Portable (v8.1.0.0p1-Beta) from the official GitHub here

NOTE 1 : Here I show how to configure only the configuration file «config» in the folder .ssh, which should be in the user folder $HOME.ssh , because it is what is required, normally, it seems to me that the other files are created automatically when one Install Open-SSH server. if this is not the case, simply adapt the command lines

NOTE 2 : Have Git for Windows and OpenSSH-portable can cause problems for the configuration of the agent, so you should know that it is the SSH-Agent uses by the Windows service

You can find out which ssh-agent is used by the Windows service with this command :

Get-WmiObject win32_service | ?{$_.Name -like 'ssh-agent'} | select PathName

If the Get-WmiObject command no longer works you can use the Get-CimInstance command which should be its definitive successor for new versions of PowerShell


# Create the config file with Powershell
New-Item -Path $HOME.sshconfig -ItemType File

# Open config File with Notepad
C:WINDOWSSystem32notepad.exe $HOME.sshconfig

# or Open file with Visual Code
code $HOME.sshconfig

After that, you can configure the SSH configuration file as you want with the same syntax as on Linux

Little example

# Config for use specific key for github
Host github.com
  HostName github.com
  User git
  IdentityFile ~/.ssh/id_ed25519_github
  IdentitiesOnly yes

# For server 172.x.x.x
Host 172.x.x.x
  User user
  Port 2121
  IdentityFile ~/.ssh/id_ed25519
  IdentitiesOnly yes

# For all other servers
Host *
        User root

Now you can test your config like that :

# For Github

ssh -T git@github.com

# For other
# It is possible not to put the user to check,
# if you have indicated a specific user
# in the conf file, to test if the configuration
# will connect well with this user

ssh -T 172.x.x.x

If ssh doesn’t work, this is because you don’t have the OpenSSH folder in your environment variables, you can add it to your system environment variable like that in Powershell if you install
OpenSSH Binary in C:Program Files
and the folder name is OpenSSH-Win64

# PowerShell admin
# Add folder OpenSSH to your System Environnement
[System.Environment]::SetEnvironmentVariable('OPENSSH', 'C:Program FilesOpenSSH-Win64', [System.EnvironmentVariableTarget]::Machine)

Other Command

# Generate EdDSA Key
ssh-keygen.exe -t ed25519 -a 100 -o -C "user@example.com" -f "$HOME.sshid_ed25519_example.com"

# Config the SSH Agent service
# For start the service when logon
Set-Service ssh-agent -StartupType Automatic

# Start the SSH Agent
Start-Service ssh-agent

# Restart service always when you change the config file
Restart-Service ssh-agent

# Add the key to the SSH Agent
ssh-add $HOME.sshid_ed25519_example.com

В современных версиях 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 $HOMEDownloadsOpenSSH-Win64-v8.9.1.0.msi -UseBasicParsing

msiexec /i c:usersrootdownloadsOpenSSH-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:WindowsSystem32OpenSSH
    (sshd.exe, ssh.exe, ssh-keygen.exe, sftp.exe и т.д.)
  • Конфигурационный файл sshd_config (создается после первого запуска службы):
    C:ProgramDatassh
  • Файлы authorized_keys и ssh ключи можно хранить в профиле пользователей:
    %USERPROFILE%.ssh

Sshd_config: Конфигурационный файл сервера OpenSSH

Настройки сервере OpenSSH хранятся в конфигурационном файле %programdata%sshsshd_config. Это обычный текстовый файл с набором директив. Для редактирования можно использовать любой текстовый редактор (я предпочитаю notepad++). Можно открыть с помощью обычного блокнота:

start-process notepad C:Programdatasshsshd_config

Например, чтобы запретить SSH подключение для определенного доменного пользователя (и всех пользователей указанного домена), добавьте в конце файле директивы:

DenyUsers winitpro[email protected]
DenyUsers corp*

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

AllowGroups winitprosshadmins

Либо можете разрешить доступ для локальной группы:

AllowGroups sshadmins

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

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

DenyGroups Administrators

Следующие директивы разрешают SSH доступ по ключам (SSH аутентификации в Windows с помощью ключей описана в отдельной статье) и по паролю:

PubkeyAuthentication yes
PasswordAuthentication yes

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

sshd - смена порта ssh 22

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

restart-service sshd

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

Теперь вы можете попробовать подключиться к своей Windows 10 через SSH клиент (в этом примере я использую putty).

Вы можете использовать встроенный SSH клиентом Windows для подключения к удаленному хосту. Для этого нужно в командной строке выполнить команду:

ssh [email protected]

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

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

  • [email protected]
    – локальный пользователь Windows
  • [email protected]@server1
    –пользователь Active Directory (в виде UPN) или аккаунт Microsoft/ Azure(Microsoft 365)
  • winitpro[email protected]
    – NetBIOS формат имени

В домене Active Directory можно использовать Kerberos аутентификацию в SSH. Для этого в sshd_config нужно включить параметр:

GSSAPIAuthentication yes

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

ssh -K server1

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

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

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

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

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

[email protected] C:Usersadmin>

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

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

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

powershell.exe

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

Чтобы изменить командную оболочку (Shell) по умолчанию в OpenSSH с cmd.exe на PowerShell, внесите изменение в реестр такой командой:

New-ItemProperty -Path "HKLM:SOFTWAREOpenSSH" -Name DefaultShell -Value "C:WindowsSystem32WindowsPowerShellv1.0powershell.exe" -PropertyType String –Force

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

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

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:ProgramDatasshlogssshd.log

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

title description ms.date ms.topic ms.author author

OpenSSH Server configuration for Windows

Learn about the Windows-specific configuration options for OpenSSH Server on Windows Server and Windows.

07/12/2022

conceptual

damaerte

maertendmsft

OpenSSH Server configuration for Windows Server and Windows

Applies to Windows Server 2022, Windows Server 2019, Windows 10 (build 1809 and later)

This article covers the Windows-specific configuration for OpenSSH Server (sshd).

OpenSSH maintains detailed documentation for configuration options online at OpenSSH.com, which isn’t duplicated in this documentation set.

OpenSSH configuration files

OpenSSH has configuration files for both server and client settings. OpenSSH is open-source and is
added to Windows Server and Windows Client operating systems, starting with Windows Server 2019 and
Windows 10 (build 1809). As a result, open-source documentation for OpenSSH configuration files
isn’t repeated here. Client configuration files and can be found on the
ssh_config manual page and for OpenSSH Server configuration
files can be found on the sshd_config manual page.

Open SSH Server (sshd) reads configuration data from %programdata%sshsshd_config by default, or
a different configuration file may be specified by launching sshd.exe with the -f parameter. If
the file is absent, sshd generates one with the default configuration when the service is started.

In Windows, the OpenSSH Client (ssh) reads configuration data from a configuration file in the
following order:

  1. By launching ssh.exe with the -F parameter, specifying a path to a configuration file and an
    entry name from that file.
  2. A user’s configuration file at %userprofile%.sshconfig.
  3. The system-wide configuration file at %programdata%sshssh_config.

Configuring the default shell for OpenSSH in Windows

The default command shell provides the experience a user sees when connecting to the server using SSH.
The initial default Windows is the Windows Command shell (cmd.exe).
Windows also includes PowerShell, and third-party command shells are also available for Windows and may be configured as the default shell for a server.

To set the default command shell, first confirm that the OpenSSH installation folder is on the system path.
For Windows, the default installation folder is %systemdrive%WindowsSystem32openssh.
The following command shows the current path setting, and adds the default OpenSSH installation folder to it.

Command shell Command to use
Command path
PowerShell $env:path

Configuring the default ssh shell is done in the Windows registry by adding the full path to the shell executable to HKEY_LOCAL_MACHINESOFTWAREOpenSSH in the string value DefaultShell.

As an example, the following elevated PowerShell command sets the default shell to be powershell.exe:

New-ItemProperty -Path "HKLM:SOFTWAREOpenSSH" -Name DefaultShell -Value "C:WindowsSystem32WindowsPowerShellv1.0powershell.exe" -PropertyType String -Force

Windows Configurations in sshd_config

In Windows, sshd reads configuration data from %programdata%sshsshd_config by default, or a different configuration file may be specified by launching sshd.exe with the -f parameter.
If the file is absent, sshd generates one with the default configuration when the service is started.

The elements listed below provide Windows-specific configuration possible through entries in sshd_config.
There are other configuration settings possible that aren’t listed here, as they’re covered in detail in the online Win32 OpenSSH documentation.

[!TIP]
The OpenSSH Server (sshd) reads the configuration file when the service starts. Any changes to the
configuration file requires the service to be restarted.

AllowGroups, AllowUsers, DenyGroups, DenyUsers

Controlling which users and groups can connect to the server is done using the AllowGroups, AllowUsers, DenyGroups, and DenyUsers directives.
The allow/deny directives are processed in the following order: DenyUsers, AllowUsers, DenyGroups, and finally AllowGroups.
All account names must be specified in lower case.
For more information about PATTERNS and wildcard in the ssh_config, see the sshd_config OpenBSD manual page.

When configuring user/group based rules with a domain user or group, use the following format: user?domain*.
Windows allows multiple formats for specifying domain principals, but many conflict with standard Linux patterns.
For that reason, * is added to cover FQDNs.
Also, this approach uses «?», instead of @, to avoid conflicts with the username@host format.

Work group users/groups and internet-connected accounts are always resolved to their local account name (no domain part, similar to standard Unix names).
Domain users and groups are strictly resolved to NameSamCompatible format — domain_short_nameuser_name.
All user/group based configuration rules need to adhere to this format.

The following example denies contosoadmin from the host 192.168.2.23, and blocks all users from contoso domain. It also allows users who are a member of the contososshusers and contososerveroperators groups.

DenyUsers contosoadmin@192.168.2.23
DenyUsers contoso*
AllowGroups contososshusers contososerveroperators

The example below allow the user localusers to sign-in from the host 192.168.2.23 and allows members of the group sshusers.

AllowUsers localuser@192.168.2.23
AllowGroups sshusers

AuthenticationMethods

For Windows OpenSSH, the only available authentication methods are password and publickey.

[!IMPORTANT]
Authentication using an Azure AD account is not currently supported.

AuthorizedKeysFile

The default is .ssh/authorized_keys. If the path isn’t absolute, it’s taken relative to user’s
home directory (or profile image path), for example, C:Usersusername. If the user belongs to
the administrator group, %programdata%/ssh/administrators_authorized_keys is used instead.

[!TIP]
The administrators_authorized_keys file must only have permission entries for the NT
AuthoritySYSTEM account and BUILTINAdministrators security group. The NT AuthoritySYSTEM
account must be granted full control. The BUILTINAdministrators security group is required for
administrators to manage the authorized keys, you can choose the required access. To grant
permissions you can open an elevated PowerShell prompt, and running the command
icacls.exe "C:ProgramDatasshadministrators_authorized_keys" /inheritance:r /grant "Administrators:F" /grant "SYSTEM:F".

ChrootDirectory (Support added in v7.7.0.0)

This directive is only supported with sftp sessions. A remote session into cmd.exe wouldn’t honor
the ChrootDirectory. To set up a sftp-only chroot server, set ForceCommand to internal-sftp. You may also set up
scp with chroot, by implementing a custom shell that would only allow scp and sftp.

GSSAPIAuthentication

The GSSAPIAuthentication configuration argument specifies whether GSSAPI based user authentication is allowed. The
default for GSSAPIAuthentication is no.

GSSAPI authentication also requires the use of the -K switch specifying the hostname when using
the OpenSSH client. Alternatively, you can create a corresponding entry in the SSH client
configuration. In Windows, the OpenSSH client reads configuration data from
%userprofile%.sshconfig by default.

You can see an example GSSAPI OpenSSH client configuration below.

# Specify a set of configuration arguments for a host matching the pattern SERVER01.contoso.com
# Patterns are case sensitive
Host SERVER01.contoso.com
    # Enables GSSAPI authentication
    GSSAPIAuthentication yes
    # Forward (delegate) credentials to the server.
    GSSAPIDelegateCredentials yes

[!IMPORTANT]
GSSAPI is only available starting in Windows Server 2022, Windows 11, and Windows 10 xxxx.

HostKey

The defaults are:

#HostKey __PROGRAMDATA__/ssh/ssh_host_rsa_key
#HostKey __PROGRAMDATA__/ssh/ssh_host_dsa_key
#HostKey __PROGRAMDATA__/ssh/ssh_host_ecdsa_key
#HostKey __PROGRAMDATA__/ssh/ssh_host_ed25519_key

If the defaults aren’t present, sshd automatically generates them on a service start.

Match

Matches conditions using one or more criteria. Upon a match, the subsequent configuration arguments are applied. Matches uses the pattern rules covered in the AllowGroups, AllowUsers, DenyGroups, DenyUsers section. User and group names should be in lower case.

PermitRootLogin

Not applicable in Windows. To prevent administrators signing in, use Administrators with DenyGroups
directive.

SyslogFacility

If you need file based logging, use LOCAL0. Logs are generated under %programdata%sshlogs. For
any other value, including the default value, AUTH directs logging to ETW. For more info, see
Logging Facilities in Windows.

Configuration arguments

The following configuration argument is available starting in Windows Server 2022, Windows 11, and
Windows 10 xxxx:

  • GSSAPIAuthentication

The following configuration arguments aren’t available in the OpenSSH version that ships in Windows
Server and the Windows client:

  • AcceptEnv
  • AllowStreamLocalForwarding
  • AuthorizedKeysCommand
  • AuthorizedKeysCommandUser
  • AuthorizedPrincipalsCommand
  • AuthorizedPrincipalsCommandUser
  • Compression
  • ExposeAuthInfo
  • GSSAPICleanupCredentials
  • GSSAPIStrictAcceptorCheck
  • HostbasedAcceptedKeyTypes
  • HostbasedAuthentication
  • HostbasedUsesNameFromPacketOnly
  • IgnoreRhosts
  • IgnoreUserKnownHosts
  • KbdInteractiveAuthentication
  • KerberosAuthentication
  • KerberosGetAFSToken
  • KerberosOrLocalPasswd
  • KerberosTicketCleanup
  • PermitTunnel
  • PermitUserEnvironment
  • PermitUserRC
  • PidFile
  • PrintLastLog
  • PrintMotd
  • RDomain
  • StreamLocalBindMask
  • StreamLocalBindUnlink
  • StrictModes
  • X11DisplayOffset
  • X11Forwarding
  • X11UseLocalhost
  • XAuthLocation

In previous article i describe How to install Open SSH in Windows 10 as Optional Feature and use it. Today i will continue with OpenSSH and i will describe step by step how can install OpenSSH Server in Windows 10 and configure it.

OpenSSH Server and client included in Windows 10 v.1809 and later and in Windows Server 2019

So let’s start!!

How to Identify if Windows 10 Open SSH Server installed from GUI

Before start with the installation its better to identify if already OpenSSH Server installed.

  • Click Start and Gear Icon
  • Click in Apps
  • From the right side select Manage Optional Features.
  • if you see Open SSH Server then it means that already installed.
  • If you can’t see this means that you must install the Feature.

How to Identify if  OpenSSH Server installed from Powershell

If you like Powershell you can use the following command to identify if OpenSSH Server already installed

Get-WindowsCapability -Online | ? name -like "openssh*"

Check the State status to identify if is installed or not

  1. State:Installed means it’s already installed
  2. State:Not Present means it’s not installed

How to Install in Windows 10 the OpenSSH Server from GUI

After identify that OpenSSH Server it’s not installed we can proceed to install the OpenSSH Server

  • Click Start and Gear Icon
  • Click in Apps
  • From the right side select Manage Optional Features
  • Click Add Feature
  • Find and click Open SSH Server
  • Click Install

How to Install in Windows 10 the OpenSSH Server from Powershell

If you would like to proceed the installation of OpenSSH Server from Powershell you can do it with one command.

Type the following command and wait to finish the installation

Add-WindowsCapability -Online -Name OpenSSH.Server~~~~0.0.1.0

How to start and Configure in Windows 10 the OpenSSH Server

Now it’s time to Configure OpenSSH Server to start use it.

  • Open Powershell command as Administrator
  • Type the following command to start the Service of the OpenSSH Server
    Start-service sshd
  • Type the following command to add Automatic Startup in Service
  • Set-Service -Name sshd -StartupType 'Automatic'
  • Type the following command to find the Rule for OpenSSH Server in Windows Firewall and verify that is Allow
    Get-NetFirewallRule -Name *ssh*

How to connect with ssh from Linux to Windows 10 OpenSSHServer

The reality with ssh is that most of them use it with Public key authentication instead of password authentication because it prevent attacks.

But by default after the installation the OpenSSH Server use password authentication.

We will keep the password authentication to be able to connect through the configuration that must be done to use the Public key authentication

So for the best practices and better security let’s explain how can generate ssh keys and use it to connect in OpenSSH Server

  • Login in Windows 10 OpenSSH Server and create the users that you want to connect.
  • If you have Domain users and have already decide which should be connect then avoid the previous step
  • Login in the Linux that you will use it to connect in OpenSSH Server
  • Type the following command to start generate the keys
    • ssh keygen
  • It will ask how you would like to save the file name but you can leave it as the default and click Enter
  • Also it will ask to create a passphrase.
  • Just write down a passphrase and keep it in a safe place because it will ask when you will connect in OpenSSH Server.

  • Now if you type ls to see the files and folder of the ssh directory you will see 2 files. These are the private key and the public key with the extension .pub
    • id_rsa
    • id_rsa.pub

  • To be able create the authentication must be copy the public key in the Openssh Server in the following path of the user which will connect from Linux. Note that we must have create the user before proceed with this step.
  • The name of the public key file must be authorized_keys in the .ssh folder
    • C:Users<username>.ssh
  • So let’s type the following command from the Linux which create the ssh keys and replace the user1@192.168.50.151 with your username and ip address of the opensshserver
    • scp ~/.ssh/id_rsa.pub user1@192.168.50.151:»c:usersuser1.sshauthorized_keys»

  • Login in the Openssh server and verify that the authorized_keys created in the .ssh of the user folder.
  • Now we must configure the permission of the authorized_keys because if you try to connect as it you will get an error Permission denied (publickey,keyboard-interactive)
  • If we check the permissions of the authorized_keys file we will see that has access the user which will connect in my scenario is the user1 and the Domain Administrator.
  • But these users must be removed.

  • If you search in Google you will find most of the Blogs and forums to say that you can download the Powershell module OpenSSHUtil but this module has been deprecated and if you try you will fail to downloaded 
  • Before try to remove the access from users in the authorized_keys file must be disable the inheritance. If you don’t do it and try to remove the users with icacls command then you will get the info that succesfull proceed with the file but if you will check the permission will be the same without remove the users.
  • Right click in authorized_keys file — Properties.
  • Click Advanced button.
  • Click Disable inheritance.
  • Click Convert inherited permissions into explicit permissions on this object.

  • Login again in Linux which will use it to connect and type the following command to connect with ssh and password authentication for now
    • ssh user1@192.168.50.151
  • After connect type the following commands to remove the user access from the authorized_keys
    • Icacls «authorized_keys» /remove user1
    • Icacls «authorized_keys» /remove administrator

  • Now type the following command to check the permissions in the file.
  • Only these users must has access in this file
    • icacls authorized_keys

  • The last step is to disable the password authentication and enable the Pubkey authentication from the ssh_config file to be able authorized only with the ssh keys and not with password

How to disable password authentication in OpensshServer

After the basic configuration of OpensshServer to set Automatic the Service and verify the Rule in Windows Firewall you can proceed in more advance configuration.

Let’s explain how can change configuration of Openssh server.

  • Open Powershell as Administrator
  • Type the command notepad.exe $env:PROGRAMDATAsshsshd_config to open the ssh_config file

  • Change the following lines with these values.
    • PubkeyAuthentication yes
    • PasswordAuthentication no
      PermitEmptyPasswords no

  • Then type the following commands to restart the Openssh Server service
    • Stop-Service sshd
    • Start-Service sshd

  • Let’s connect in Linux and type the command to connect trough ssh.
  • If all works without issues you will see that ask the passphrase before connect

  • Type it and the connection will be established.

If you failed to connect with Public key authentication then the better solution is to use Logs of SSH to identify the cause of the issue.

This has been change from previous versions and now the SSH Logs located in Windows Event Logs in stead of the C:ProgramDatasshlogssshd.log and you can find it in Application and Services Logs — OpenSSH Logs

I hope my article to help you or explore something new or resolve a problem.

Have a nice weekend !!

I invite you to follow me on Twitter or Facebook. If you have any questions, send me an email at info@askme4tech.com

Клиент 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:WindowsSystem32OpenSSH
  • Конфигурационный файл sshd_config: C:ProgramDatassh
  • Журнал OpenSSH: C:ProgramDatasshlogssshd.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.

SSH-server based on the OpenSSH package is part of the operating system in all modern versions of Windows. In this article, we’ll show you how to install and configure the OpenSSH server on Windows 10/11 and Windows Server 2022/2019 and connect to it remotely via a secure SSH connection (just like in Linux 🙂).

Contents:

  • How to Install OpenSSH Server on Windows?
  • Configuring SSH Server on Windows
  • Sshd_config: OpenSSH Server Configuration File
  • How to Connect to a Remote Windows Computer via SSH?
  • Checking SSH Connection Logs in Windows

How to Install OpenSSH Server on Windows?

The OpenSSH Server package is a part of all modern versions of Windows 10 (starting with 1803), Windows 11, and Windows Server 2022/2019 as a Feature on Demand (FoD). To install the OpenSSH server, open the elevated PowerShell prompt and run the command:

Get-WindowsCapability -Online | Where-Object Name -like ‘OpenSSH.Server*’ | Add-WindowsCapability –Online

Or using DISM:

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

If your computer is directly connected to the Internet, the OpenSSH.Server package will be downloaded and installed on Windows.

You can also install OpenSSH on Windows 10/11 through the modern Settings panel (Settings -> Apps and features -> Optional features -> Add a feature). Find Open SSH Server in the list and click Install.

install openssh server on windows 10 via settings app

On computers in disconnected (offline) environments, you can install the OpenSSH Server from the Feature on Demand ISO image (available in your account on the Microsoft websites: MSDN or my.visualstudio.com). Download the ISO and extract its contents to the E:FOD folder (you can only extract the file OpenSSH-Server-Package~31bf3856ad364e35~amd64~~.cab) and install the Windows feature from the local repository:

Add-WindowsCapability -Name OpenSSH.Server~~~~0.0.1.0 -Online -Source E:FOD

An MSI installer for OpenSSH for Windows is also available in the official Microsoft repository on GitHub (https://github.com/PowerShell/Win32-OpenSSH/releases/). For example, for Windows 10 x64, you need to download and install the OpenSSH-Win64-v8.9.1.0.msi package. The following PowerShell command will download the MSI file and install the OpenSSH client and server on your computer:

Invoke-WebRequest https://github.com/PowerShell/Win32-OpenSSH/releases/download/v8.9.1.0p1-Beta/OpenSSH-Win64-v8.9.1.0.msi -OutFile $HOMEDownloadsOpenSSH-Win64-v8.9.1.0.msi -UseBasicParsing
msiexec /i $HOMEDownloadsOpenSSH-Win64-v8.9.1.0.msi

download and run openssh msi installer on windows

You can install an OpenSSH server in previous Windows versions as well (Windows 8.1, Windows Server 2016/2012R2/2012). Check the example on how to install and configure Win32-OpenSSH in the article “How to Configure SFTP Server (SSH FTP) on Windows?”.

To make sure the OpenSSH server has been installed, run the command:

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

State : Installed

check openssh server feature installed on windows Get-WindowsCapability

Configuring SSH Server on Windows

After installing the OpenSSH server on Windows, two services are added:

  • ssh-agent (OpenSSH Authentication Agent) – can be used to manage private keys if you have configured SSH key authentication;
  • sshd (OpenSSH SSH Server).

You need to change the startup type of the sshd service to automatic and start the service using PowerShell:

Set-Service -Name sshd -StartupType 'Automatic'
Start-Service sshd

start sshd service on windows 10
Use the netstat command to make sure that the SSH server is running and waiting for the connections on TCP port 22:
netstat -na| find ":22"
check ssh tcp port 22 listening on windows 10
Make sure that Windows Defender Firewall allows inbound connections to Windows through TCP port 22:
Get-NetFirewallRule -Name *OpenSSH-Server* |select Name, DisplayName, Description, Enabled

Name DisplayName Description Enabled
---- ----------- ----------- -------
OpenSSH-Server-In-TCP OpenSSH SSH Server (sshd) Inbound rule for OpenSSH SSH Server (sshd) True

open inbound ssh port in windows defender firewall

If the rule is disabled (Enabled=False) or missing, you can create a new inbound rule using the New-NetFirewallRule cmdlet:

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

By default, key OpenSSH components are located in these folders:

  • OpenSSH Server executables: C:WindowsSystem32OpenSSH(sshd.exe, ssh.exe, ssh-keygen.exe, sftp.exe, etc.)
  • The sshd_config file (created after the first service start of the service): C:ProgramDatassh
  • The authorized_keys file and keys can be stored in the user profile folder: %USERPROFILE%.ssh

Sshd_config: OpenSSH Server Configuration File

You can change your OpenSSH server settings in the config file: %programdata%sshsshd_config. This is a plain text file with a set of directives. You can use any text editor for editing:

start-process notepad C:Programdatasshsshd_config

For example, to deny SSH connection for a specific domain user account (or all users in the specified domain), add these directives to the end of the file:

DenyUsers woshubadmin@192.168.1.10
DenyUsers corp*

To allow SSH connection to the specific domain security group only:

AllowGroups woshubsshadmins

You can allow access to a local user group:

AllowGroups sshadmins

By default, all Windows users can connect to OpenSSH. Directives in the sshd_config files are processed in the following order: DenyUsers, AllowUsers, DenyGroups, AllowGroups.

You can deny SSH login for the accounts with administrator privileges. In this case, if you need to perform any privileged actions in your SSH session, you will have to use runas.

DenyGroups Administrators

The following directives allow you to access Windows using SSH private keys or a password.

PubkeyAuthentication yes
PasswordAuthentication yes

You can change the default TCP/22 port on which OpenSSH Server connections are accepted in the sshd_config configuration file using the Port directive.

%programdata%sshsshd_config file in windows

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

restart-service sshd

How to Connect to a Remote Windows Computer via SSH?

Now you can try to connect to your Windows 10 computer using the SSH client (I’m using putty in this example).

You can use the built-in Windows SSH client to connect to a remote host. To do this, open the command prompt and run the following command:

ssh max@192.168.13.12

In this example, max is the username on the remote Windows computer, and 192.168.13.12 is the IP address or DNS name of the computer.

Note that you can use the following username formats when connecting to Windows via SSH:

  • max@server1 – local Windows user
  • max@woshub.com@server1 – Active Directory user or Microsoft/Azure account (use the UserPrincipalName format)
  • woshubmax@server1 – NetBIOS name format

In an Active Directory domain, you can use Kerberos authentication in SSH. To do this, you need to enable the following directive in sshd_config:

GSSAPIAuthentication yes

You can now transparently connect to an SSH server from a domain-joined Windows machine with a domain user session. In this case, the user’s password will not be requested, and SSO authentication via Kerberos will be performed:
ssh -K server1

The first time you connect, you will be prompted to add the host to the list of known SSH hosts (C:Usersyour_user.sshknown_hosts).

putty accept rsa key for a ssh server

Click Yes, and login under your Windows user account.

login windows 10 via ssh like in linux

If the SSH connection is successful, you will see the cmd.exe shell prompt.

admin@win10pc C:Usersadmin>

cmd.exe shell in windows ssh session

You can run different commands, scripts, and apps in the SSH command prompt.

run command in windows 10 via ssh

I prefer working in the PowerShell console. To start it, run:

powershell.exe

run powershell in windows ssh

In order to change the default cmd.exe shell in OpenSSH to PowerShell, make changes to the registry using the following PowerShell command:

New-ItemProperty -Path "HKLM:SOFTWAREOpenSSH" -Name DefaultShell -Value "C:WindowsSystem32WindowsPowerShellv1.0powershell.exe" -PropertyType String –Force

New-ItemProperty replacing ssh shell from cmd.exe to powershell.exe

Restart your SSH connection and make sure that PowerShell is now used as a default SSH shell (this is indicated by the prompt PS C:Usersadmin>).

powershell console in windows 10 ssh session

The PowerShell prompt has been started in my SSH session, where the usual functions work: tab autocomplete, PSReadLine syntax highlighting, command history, etc. If the current user is a member of the local administrators’ group, all session commands are executed elevated even if UAC is enabled.

OpenSSH server on Windows can be used in various SSH tunneling scenarios.

Checking SSH Connection Logs in Windows

By default in Windows SSH server connection logs are written not to text files, but to a separate event log via Event Tracing for Windows (ETW). Open the Event Viewer console (eventvwr.msc ) and navigate to Application and services logs -> OpenSSH -> Operational.

If you successfully connect to the SSH server using a password, an event will appear in the log:

EventID: 4
sshd: Accepted password for root from 192.168.1.53 port 65749 ssh2

sshd connection logs in windows event viewer

If SSH key authentication was performed, you will see the following event:

sshd: Accepted publickey for locadm from 192.168.1.53 port 61426 
ssh2: ED25519 SHA256:FEHDEC/G42FS23209C2KMb4335923pigN31s3qMK322lGibD

If you want the SSH connection logs to be written to a local text file, you need to enable the following parameters in the sshd_config file:

SyslogFacility LOCAL0
LogLevel INFO

Restart the sshd service and make sure that the SSH server logs are now written to a plain text file C:ProgramDatasshlogssshd.log

sshd.log file of openssh server on windows

The latest builds of Windows 10 and Windows 11 include a built-in server and client that are based on OpenSSH. This means now you can remotely connect to Windows 10/11 or Windows Server 2019 using any SSH client, similar to Linux distros. In this article, we’ll show you how to configure OpenSSH on Windows 10 and Windows 11, and connect to it using Putty or any other SSH client.

OpenSSH is an open-source, cross-platform version of Secure Shell (SSH) that is used by Linux users for a long time. This project is currently ported to Windows and can be used as an SSH server on almost any version of Windows. OpenSSH is built-in into the operating system image in the latest versions of Windows Server 2022/2019 and Windows 11.

How to Enable SSH Server on Windows 10?

Make sure your build of Windows 10 is 1809 or newer. The easiest way to do this is by running the command:

winver

ssh into windows

Note. If you have an older Windows 10 build installed, you can update it through Windows Update or using an ISO image with a newer Windows 10 build (you can create an image using the Media Creation Tool). If you don’t want to update your Windows 10 build, you can manually install the Win32-OpenSSH port for Windows from GitHub.

You can enable the OpenSSH server in Windows 10 through the graphical Settings panel:

  1. Go to Settings > Apps > Apps and features > Optional features (or run the command ms-settings:appsfeatures);
    ssh to windows
  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.
    ssh into windows machine

You can also install the sshd server using PowerShell:

Add-WindowsCapability -Online -Name OpenSSH.Server*

ssh to windows server

Or using DISM:

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

If you want to make sure the OpenSSH server is installed, run the following PS command:

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

Name : OpenSSH.Server~~~~0.0.1.0

State : Installed

ssh into windows 10

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 10
  3. Select OpenSSH Server from the list and click Next > Install;
    how to ssh into windows 10
  4. Wait for the installation to complete.
    windows 11 ssh server

The OpenSSH binaries are located in the C:WindowsSystem32OpenSSH 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 Get-Service command:

Get-Service -Name *ssh*

how to ssh into windows

As you can see, both services are in a Stopped state and not added to the automatic startup list. To start services and configure autostart for them, run the following commands:

Start-Service sshd

Set-Service -Name sshd -StartupType 'Automatic'

Start-Service ‘ssh-agent’

Set-Service -Name ‘ssh-agent’ -StartupType 'Automatic'

connect to windows via ssh

You also need to allow incoming connections to TCP port 22 in the Windows Defender firewall settings. You can open the port using netsh:

netsh advfirewall firewall add rule name=”SSHD service” dir=in action=allow protocol=TCP localport=22

Or you can add a firewall rule to allow SSH traffic using PowerShell:

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

You can configure various OpenSSH server settings in Windows using the %programdata%sshsshd_config configuration file.

enable ssh windows 11

For example, you can disable password authentication and leave only key-based auth with:

PubkeyAuthentication yes

PasswordAuthentication no

Here you can also specify a new TCP port (instead of the default TCP 22 port) on which the SSHD will accept connections. For example:

Port 2222

Using the directives AllowGroups, AllowUsers, DenyGroups, DenyUsers, you can specify users and groups who are allowed or denied to connect to Windows via SSH:

  • DenyUsers theitbrosjbrown@192.168.1.15 — denies connections to username jbrown from 192.168.1.15 host;
  • DenyUsers theitbros* — prevent all users from theitbros domain to connect host using ssh;
  • AllowGroups theitbrosssh_allow — only allow users from theitbrosssh_allow to connect host.

The allow and deny rules of sshd are processed in the following order: DenyUsers, AllowUsers, DenyGroups, and AllowGroups.

For example, to allow to connect to SSH under mylocaluser1 account from 192.168.31.100 host, add the following directive:

AllowUsers mylocaluser1@192.168.31.100

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

Get-Service sshd| Restart-Service –force

how to ssh to windows

Connect to Windows via SSH

Now you can connect to Windows 10 using any SSH client. To connect from Linux, use the command:

ssh -p 22 admin@192.168.1.90

Here, the admin is a local Windows user under which you want to connect. This account must be a member of the built-in Administrators group. 192.168.1.90 is an IP address of your Windows 10 computer.

windows allow ssh connections

After that, a Windows command prompt window will open in the SSH session.

You can use the Putty client to connect to a Windows computer via SSH:

  1. Download and run putty.exe;
  2. Enter the hostname or IP address of the remote Windows host you want to connect over SSH;
  3. Select the Connection type: SSH and make sure port 22 is specified; ssh into windows server
  4. Click Open;
  5. The first time you connect to a Windows host via SSH, a Security Alert will appear asking you to confirm that you want to add the ssh-ed25519 key fingerprint of the remote machine to your local cache. If you trust this host, click the Accept button. This will add that server to the list of known SSH hosts;
    ssh to windows pc
    Note. OpenSSH server fingerprint stored in a file C:ProgramDatasshssh_host_ecdsa_key.pub. You can determine the current ECDSA key fingerprint on a Windows 10 host with the command:

    ssh-keygen -lf C:ProgramDatasshssh_host_ed25519_key.pub

    windows 11 enable ssh

  6. A Putty window will appear. Here you need to specify the Windows username and password that you want to use to connect to SSH;
    ssh into windows pc
  7. Once logged in, the command line of the remote Windows host will open;
  8. You can now interactively run commands on the remote host.
    can you ssh into windows

You can also use the built-in Windows SSH client to connect to another Windows host. Install the ssh.exe client on Windows using the command:

Add-WindowsCapability -Online -Name OpenSSH.Client*

Now you can connect to a remote SSH host directly from the Windows command prompt. Use the following command:

ssh root@192.168.13.202

The first time you connect, you will also need to add the fingerprint of the SSH server’s ECDSA key to the list of known hosts. To do this, type “yes” > “enter”.

ssh into a windows machine

Enter the user’s password. The command line C:Windowssystem32conhost.exe should appear: windows 11 enable ssh server

You can now use the OpenSSH.Client tools (scp.exe, sftp.exe) to copy a file between hosts using the SSH protocol. The following command will copy the local test1.log file to a remote Windows SSH host:

scp.exe D:PStest1.log root@192.168.13.202:c:temp

ssh to a windows machine

If you prefer to use Windows Terminal, you can add the required SSH host profiles to it for quick connection:

  1. Run Windows Terminal and go to its Settings;
  2. Click the Add a new profile button in the Profiles section; ssh into windows computer
  3. Specify that you want to create a duplicate of Windows PowerShell profile; install ssh windows 11
  4. Specify a profile name (“SSH Windows 10 DEVPC” in this example);
  5. In the Command line parameter, specify the connection string to your SSH host. For example: %SystemRoot%System32WindowsPowerShellv1.0powershell.exe ssh root@192.168.13.202 windows 11 ssh
  6. Save the profile;
  7. Now in the Windows Terminal menu you will have a separate option for a quick SSH connection to a Windows host. ssh on windows 11

Hint. In some scenarios, you will need to run the PowerShell.exe cli instead of the cmd.exe shell when logging in via SSH on Windows 10. You can do this by running the following command in Windows 10 (under the admin account):

New-ItemProperty -Path "HKLM:SOFTWAREOpenSSH" -Name DefaultShell -Value "C:WindowsSystem32WindowsPowerShellv1.0powershell.exe" -PropertyType String -Force

Now, you change the default OpenSSH shell. From here, when connecting to Windows via SSH, you will immediately see PowerShell prompt instead of cmd.exe.

ssh into windows 11

If you want to use key-based ssh authentication instead of password authentication, you need to generate a key using ssh-keygen on your client. In such a case, the contents of the id_rsa.pub file must be copied to the c:usersadmin.sshauthorized_keys file in Windows 10.

After that, you can connect from your Linux client to Windows 10 without a password. Use the command:

ssh -l admin@192.168.1.90

In previous versions of OpenSSH on Windows, all of the sshd service logs were written to the text file C:ProgramDatasshlogssshd.log by default.

On Windows 11, SSH logs can be viewed using the Event Viewer console (eventvwr.msc). All SSH events are available in a separate section Application and Services Logs > OpenSSH > Operational.

For example, the screenshot shows an example of an event with a successful connection to the computer via SSH. You can see the ssh client’s IP address (hostname) and the username used to connect.

Sshd: Accepted password for jbrown from 192.168.14.14. port 49833 ssh2

how to ssh into a windows machine

  • About
  • Latest Posts

I enjoy technology and developing websites. Since 2012 I’m running a few of my own websites, and share useful content on gadgets, PC administration and website promotion.

Like this post? Please share to your friends:
  • Ssd накопитель не отображается в windows 10
  • Ssd нагружается на 100 windows 10
  • Ssd мини твикер windows 10 скачать
  • Ssd какой объем выбрать под систему windows 10
  • Ssd как кэш для hdd windows 10