Ssh connection to windows server

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

Время на прочтение3 мин

Количество просмотров100K

Меня всегда удручало подключение к Windows машинам. Нет, я не противник и не сторонник Microsoft и их продуктов. Каждый продукт существует для своей цели, но речь не об этом.
Для меня всегда было мучительно больно подключаться к серверам с Windows, потому что эти подключения либо настраиваются через одно место (привет WinRM с HTTPS) либо работают не очень стабильно (здравствуй RDP к виртуалкам за океаном).

Поэтому, случайно натолкнувшись на проект Win32-OpenSSH, я решил поделиться опытом настройки. Возможно кому-нибудь эта тулза сэкономить кучу нервов.

Варианты установки:

  1. Вручную
  2. Через пакет Chocolatey
  3. Через Ansible, например роль jborean93.win_openssh

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

Отмечу, что данный проект пока что находится на стадии beta, поэтому его не рекомендуют использовать в production.

Итак, скачиваем последний релиз, на текущий момент это 7.9.0.0p1-beta. Есть версии как для 32 так и для 64 битных систем.

Распаковываем в C:\Program Files\OpenSSH
Обязательный момент для корректной работы: права на запись в этой директории должны быть только у SYSTEM и у админской группы.

Устанавливаем сервисы скриптом install-sshd.ps1 находящимся в этой директории

powershell.exe -ExecutionPolicy Bypass -File install-sshd.ps1

Разрешаем входящие подключения на 22 порт:

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

Уточнение: апплет New-NetFirewallRule используется на Windows Server 2012 и новее. В наиболее старых системах (либо десктопных) можно воспользоваться командой:

netsh advfirewall firewall add rule name=sshd dir=in action=allow protocol=TCP localport=22

Запускаем сервис:

net start sshd

При запуске будут автоматически сгенерированы хост-ключи (если отсутствуют) в %programdata%\ssh

Автозапуск сервиса при запуске системы мы можем включить командой:

Set-Service sshd -StartupType Automatic

Так же, можно сменить командную оболочку по умолчанию (после установки, по умолчанию — cmd):

New-ItemProperty -Path "HKLM:\SOFTWARE\OpenSSH" -Name DefaultShell -Value "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -PropertyType String -Force

Уточнение: Необходимо указывать абсолютный путь.

Что дальше?

А дальше настраиваем sshd_config, который расположем в C:\ProgramData\ssh. Например:

PasswordAuthentication no
PubkeyAuthentication yes

И создаем в пользовательской папке директорию .ssh, а в ней файл authorized_keys. Туда записываем публичные ключи.

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

Но если у вас проблемы с этим, всегда можно выключить проверку прав в конфиге:

StrictModes no

К слову, в C:\Program Files\OpenSSH лежат 2 скрипта (FixHostFilePermissions.ps1, FixUserFilePermissions.ps1), которые должны

но не обязаны

фиксить права, в том числе и с authorized_keys, но почему-то не фиксят.

Не забывайте перезапускать сервис sshd после для применения изменений.

ru-mbp-666:infrastructure$ ssh Administrator@192.168.1.10 -i ~/.ssh/id_rsa
Windows PowerShell
Copyright (C) 2016 Microsoft Corporation. All rights reserved.

PS C:\Users\Administrator> Get-Host


Name             : ConsoleHost
Version          : 5.1.14393.2791
InstanceId       : 653210bd-6f58-445e-80a0-66f66666f6f6
UI               : System.Management.Automation.Internal.Host.InternalHostUserInterface
CurrentCulture   : en-US
CurrentUICulture : en-US
PrivateData      : Microsoft.PowerShell.ConsoleHost+ConsoleColorProxy
DebuggerEnabled  : True
IsRunspacePushed : False
Runspace         : System.Management.Automation.Runspaces.LocalRunspace

PS C:\Users\Administrator>

Субъективные плюсы/минусы.

Плюсы:

  • Стандартный подход к подключению к серверам.
    Когда есть немного Windows машин, очень неудобно когда:
    Так, сюда мы ходим по ssh, а тут рдп,
    и вообще best-practice с бастионами, сначала ssh-туннель, а через него RDP.
  • Простота настройки
    Считаю что это очевидно.
  • Скорость подключения и работы с удаленной машиной
    Нет графической оболочки, экономятся как ресурсы сервера, так и количество передаваемых данных.

Минусы:

  • Не заменяет RDP полностью.
    Не все можно сделать из консоли, увы. Я имею ввиду ситуации, когда требуется GUI.

Материалы использованные в статье:
Ссылка на сам проект
Варианты установки бессовестно скопированы с Ansible docs.

В данном руководстве посмотрим, как настроить подключение по SSH к виртуальному Windows-серверу. Для работы мы будем использовать VPS, работающий на операционной системе Windows Server 2016. Заказ подобного сервера производится в личном кабинете на сайте UltraVDS.

Загрузка и установка OpenSSH

На первом шаге настройки подключения к Windows-серверу по протоколу SSH необходимо установить на него оболочку OpenSSH. В Windows Server 2016 это удобнее осуществить путём загрузки и инсталляции OpenSSH из репозитория на GitHub.

Для этого подключитесь к вашему VDS через RDP и уже с удалённого рабочего стола вашего виртуального сервера перейдите по ссылке. На момент написания данного мануала последней версией OpenSSH на GitHub была версия v9.1.0.0p1-Beta. Поэтому на ресурсе последней версии необходимо найти и загрузить оттуда архив дистрибутива — файл OpenSSH-Win64.zip.

Архив дистрибутива OpenSSH на GitHub - Настройка SSH-подключения к Windows-серверу

После того, как загрузка файла будет завершена, папку OpenSSH-Win64 скопируйте из архива OpenSSH-Win64.zip в каталог Program Files.

Каталог Program Files

Далее перейдите в папку OpenSSH-Win64 и при помощи текстового редактора Notepad отредактируйте файл sshd_config_default. А именно, в нём необходимо снять комментарии (удалить символ #) в строке:

#Port 22

И в строке:

#PasswordAuthentication yes

После чего закройте файл sshd_config_default с сохранением внесённых изменений.

Теперь можно перейти непосредственно к установке OpenSSH. Для этого от имени администратора запустите оболочку PowerShell.

Далее в командной строке PowerShell наберите следующую команду:

setx PATH "$env:path;C:\Program Files\OpenSSH-Win64" -m

При её успешном выполнении вывод команды должен выглядеть как на скриншоте ниже:

Создание переменной среды для каталога OpenSSH-Win64

Следующая команда осуществляет переход в папку C:\Program Files\OpenSSH-Win64 и запускает скрипт install-sshd.ps1.

cd "C:\Program Files\OpenSSH-Win64"; .\install-sshd.ps1

В процессе выполнения своих инструкций скрипт дважды запросит разрешение на их запуск. Для проведения успешной установки OpenSSH нажмите R при каждом запросе.

Инсталляция OpenSSH - Настройка SSH-подключения к Windows-серверу

Первоначальная настройка OpenSSH

Для того, чтобы оболочка OpenSSH была доступна всегда и самостоятельно запускалась при перезагрузке сервера, необходимо запустить службы sshd и ssh-agent, а также включить их автоматический старт. Производится это при помощи следующей команды:

Set-Service sshd -StartupType Automatic; Set-Service ssh-agent -StartupType Automatic; Start-Service sshd; Start-Service ssh-agent

На заключительном этапе установки OpenSSH необходимо разрешить в брандмауэре Windows доступ к серверу по протоколу SSH. По умолчанию SSH использует TCP-порт 22. Таким образом, следующей командой нужно будет открыть доступ к данному порту в Windows Firewall.

New-NetFirewallRule -DisplayName "OpenSSH-Server-In-TCP" -Direction Inbound -LocalPort 22 -Protocol TCP -Action Allow

Открытие доступа для SSH в Windows Firewall

Подключение к VPS по SSH

Теперь можно попробовать подключиться к вашему VPS с использованием протокола SSH. С компьютера, работающего под управлением как Windows, так и одной из операционных систем Linux, подключение производится из командной строки или терминала при помощи команды:

$ ssh your_user_name@your_server_IP

Здесь:

  • your_user_name — имя учётной записи, под которой производится подключение к VDS;
  • your_server_IP — IP-адрес вашего виртуального Windows-сервера.

При первом подключении система предупредит вас о невозможности установления подлинности удалённого хоста. Для того, чтобы рабочая станция, с которой производится подключение получила отпечаток ключа для проверки, необходимо ответить на предупреждение набрав yes.

При первом подключение необходимо ввести yes - Настройка SSH-подключения к Windows-серверу

При каждом повторном подключении к тому же удалённому серверу SSH будет проверять принятый вами фингерпринт для подтверждения его легитимности.

The latest builds of Windows 10 and Windows 11 include a build-in SSH server and client that are based on OpenSSH.
This means now you can remotely connect to Windows 10/11 or Windows Server 2019 using any SSH client, like Linux distros.
Let’s see how to configure OpenSSH on Windows 10 and Windows 11, and connect to it using Putty or any other SSH client.

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

How to install SSH Server on Windows 10?

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

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

Enable feature

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

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

  2. Click Add a feature, select OpenSSH Server (OpenSSH-based secure shell (SSH) server, for secure key management and access from remote machines), and click Install

Install using PowerShell

We can also install sshd server using PowerShell:

Add-WindowsCapability -Online -Name OpenSSH.Server*

Install using DISM

Or we can also install sshd server using DISM:

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

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

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

How to uninstall SSH Server?

Use the following PowerShell command to uninstall the SSH server:

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

How to Install SSH Server on Windows 11?

Also, you can add the OpenSSH Server on Windows 11.

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

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

ssh into windows machine

Wait for the installation to complete.

connect to windows via ssh

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

ssh to windows machine

Configuring SSH Service on Windows 10 and 11

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

how to ssh to windows

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

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

Start-Service 'ssh-agent'
Set-Service -Name 'ssh-agent' -StartupType 'Automatic'

We also need to allow incoming connections to TCP port 22 in the Windows Defender Firewall. We can open the port using netsh:

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

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

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

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

ssh -p 22 admin@192.168.1.90

Here, the admin is a local Windows user under which we want to connect. 192.168.1.90 is an IP address of your Windows 10 computer.

how to ssh to windows 10

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

Hint. To run the PowerShell.exe cli instead of cmd.exe shell when logging in via SSH on Windows 10, we need to run the following command in Windows 10 (under admin account):

New-ItemProperty -Path "HKLM:\SOFTWARE\OpenSSH" -Name DefaultShell -Value "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -PropertyType String -Force

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

If you want to use key-based ssh authentication instead of password authentication, you need to generate a key using ssh-keygen on your client.

Then, the contents of the id_rsa.pub file must be copied to the c:\users\admin\.ssh\authorized_keys file in Windows 10.

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

ssh -l admin@192.168.1.90

Configuration

We can configure various OpenSSH server settings in Windows using the %programdata%\ssh\sshd_config configuration file.

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

PubkeyAuthentication yes
PasswordAuthentication no

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

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

  • DenyUsers theitbros\jbrown@192.168.1.15 — blocks connections to username jbrown from 192.168.1.15 hostsж
  • DenyUsers theitbros\* — prevent all users from theitbros domain to connect host using sshж
  • AllowGroups theitbros\ssh_allow — only allow users from theitbtos\ssh_allow connect hostю
  • The allow and deny rules of sshd are processed in the following order: DenyUsers, AllowUsers, DenyGroups, and AllowGroups.

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

Get-Service sshd | Restart-Service –force

ssh to a windows machine

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

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

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

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

ssh to a windows machine

Get started with OpenSSH for Windows

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

OpenSSH is a connectivity tool for remote sign-in that uses the SSH protocol. It encrypts all traffic between client and server to eliminate eavesdropping, connection hijacking, and other attacks.

An OpenSSH-compatible client can be used to connect to Windows Server and Windows client devices.

If you downloaded the OpenSSH beta from the GitHub repo at PowerShell/Win32-OpenSSH, follow the instructions listed there, not the ones in this article. Some information in the Win32-OpenSSH repository relates to prerelease product that may be substantially modified before it’s released. Microsoft makes no warranties, express or implied, with respect to the information provided there.

Prerequisites

Before you start, your computer must meet the following requirements:

  • A device running at least Windows Server 2019 or Windows 10 (build 1809).
  • PowerShell 5.1 or later.
  • An account that is a member of the built-in Administrators group.

Prerequisites check

To validate your environment, open an elevated PowerShell session and do the following:

Type winver.exe and press enter to see the version details for your Windows device.

Run $PSVersionTable.PSVersion . Verify your major version is at least 5, and your minor version at least 1. Learn more about installing PowerShell on Windows.

Run the command below. The output will show True when you’re a member of the built-in Administrators group.

Install OpenSSH for Windows

Both OpenSSH components can be installed using Windows Settings on Windows Server 2019 and Windows 10 devices.

To install the OpenSSH components:

Open Settings, select Apps, then select Optional Features.

Scan the list to see if the OpenSSH is already installed. If not, at the top of the page, select Add a feature, then:

  • Find OpenSSH Client, then select Install
  • Find OpenSSH Server, then select Install

Once setup completes, return to Apps and Optional Features and you should see OpenSSH listed.

Installing OpenSSH Server will create and enable a firewall rule named OpenSSH-Server-In-TCP . This allows inbound SSH traffic on port 22. If this rule is not enabled and this port is not open, connections will be refused or reset.

To install OpenSSH using PowerShell, run PowerShell as an Administrator. To make sure that OpenSSH is available, run the following cmdlet:

The command should return the following output if neither are already installed:

Then, install the server or client components as needed:

Both commands should return the following output:

To start and configure OpenSSH Server for initial use, open an elevated PowerShell prompt (right click, Run as an administrator), then run the following commands to start the sshd service :

Connect to OpenSSH Server

Once installed, you can connect to OpenSSH Server from a Windows or Windows Server device with the OpenSSH client installed. From a PowerShell prompt, run the following command.

Once connected, you get a message similar to the following output.

Entering yes adds that server to the list of known SSH hosts on your Windows client.

At this point, you’ll be prompted for your password. As a security precaution, your password won’t be displayed as you type.

Once connected, you’ll see the Windows command shell prompt:

Uninstall OpenSSH for Windows

To uninstall OpenSSH using Windows Settings:

  1. Open Settings, then go to Apps > Apps & Features.
  2. Go to Optional Features.
  3. In the list, select OpenSSH Client or OpenSSH Server.
  4. Select Uninstall.

To uninstall the OpenSSH components using PowerShell, use the following commands:

You may need to restart Windows afterwards if the service was in use at the time it was uninstalled.

Next steps

Now that you’ve installed OpenSSH Server for Windows, here are some articles that might help you as you use it:

  • Learn more about using key pairs for authentication in OpenSSH key management
  • Learn more about the OpenSSH Server configuration for Windows

Источник

Connect to Windows via SSH like in Linux

The most depressing thing for me is to connect to Windows hosts. I’m not an opponent or a fan of Microsoft and their’s products. Every product has its own purpose. But it is really painful for me to connect to Windows servers, because of 2 points: it is hard to configure (Hi WinRM with HTTPS), and it is really unstable (Hello RDP to VMs across the ocean).

Fortunately, I found the project Win32-OpenSSH. I realized that I want to share my experience with it. I believe it will help somebody and save a lot of nerves.

Installation ways:

  1. Manually
  2. Via Chocolatey package
  3. Via Ansible, let us say the role jborean93.win_openssh

I will explain the manual way because other ones are obvious.

I must note, this project is on beta stage and it isn’t recommended to use it in production.

Well, let’s download latest release. Currently it is 7.9.0.0p1-beta. It also has 32 and 64 bit versions.

Then unpack it to C:\Program Files\OpenSSH.

Important: It is necessary to grant write access to SYSTEM and Administers group only.

Futher, install services via shell script install-sshd.ps1 which is located in the OpenSSH directory

Let’s allow incoming connections on 22 port:

Note: applet New-NetFirewallRule is for Windows Server 2012 and above only. For older or desktop OS, you can use the following command:

Start the service:

This will automatically generate host keys under %programdata%\ssh if they don’t already exist.

You can set up the service auto-start by command:

Also, you can change default shell (it is cmd by default after install):

Note: you must define absolut path.

We can configure sshd_config, which is located in C:\ProgramData\ssh.
E.g.:

Then we create .ssh directory inside the user directory (C:\Users\ ) and authorized_keys file inside it. We can paste public keys into this file.
Important: the only user in which directory it is, must have write permissions for this file.
By the way, if you can’t fix it, you can disable permissions check via config:

Also, directory C:\Program Files\OpenSSH contains 2 scripts (FixHostFilePermissions.ps1, FixUserFilePermissions.ps1), which should but not obliged fix permissions, including authorized_keys permissions, but they don’t.

Don’t forget to restart sshd service to apply changes.

  • Standart way to connect to any server (Windows/Linux)
    When you have a few Windows host, it’s inconvenient:
    So, here we go via ssh, but here via RDP,
    and generally speaking, it is the best-practice with bastions, firstly ssh-tunnel, then RDP via the tunnel. Oh kill me baby one more time.
  • Easy to configure
    I think it is obvious.
  • Connection speed to remote host
    Without GUI we save up host resources, and size of transmitted data

Cons:

  • It can’t replace RDP in some cases.
    Not the all things you can do via PowerShell. I mean the cases when GUI is required.

Links:

Источник

How to Enable and Configure SSH Server on Windows with OpenSSH?

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 🙂).

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

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

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

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

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

.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 $HOME\Downloads\OpenSSH-Win64-v8.9.1.0.msi -UseBasicParsing
msiexec /i $HOME\Downloads\OpenSSH-Win64-v8.9.1.0.msi

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

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

Configuring SSH Server on Windows

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

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

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

Set-Service -Name sshd -StartupType ‘Automatic’
Start-Service sshd

Use the netstat command to make sure that the SSH server is running and waiting for the connections on TCP port 22:
netstat -na| find «:22»

Make sure that Windows Defender Firewall allows inbound connections to Windows through TCP port 22:
Get-NetFirewallRule -Name *OpenSSH-Server* |select Name, DisplayName, Description, Enabled

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:\Windows\System32\OpenSSH\ (sshd.exe, ssh.exe, ssh-keygen.exe, sftp.exe, etc.)
  • The sshd_config file (created after the first service start of the service): C:\ProgramData\ssh
  • 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%\ssh\sshd_config . This is a plain text file with a set of directives. You can use any text editor for editing:

start-process notepad C:\Programdata\ssh\sshd_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:

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

You can allow access to a local user group:

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.

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

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.

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

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)
  • woshub\max@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:

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:\Users\your_user\.ssh\known_hosts ).

Click Yes , and login under your Windows user account.

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

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

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

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:\SOFTWARE\OpenSSH» -Name DefaultShell -Value «C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe» -PropertyType String –Force

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

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.

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:

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

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:

Источник

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

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Kernel recovery for windows data recovery
  • Служба общих папок синхронизации windows syncsharesvc остановлено автоматически
  • Как поставить приоритет на игру в windows 10 через настройки
  • Windows 10 pro загрузочная флешка официальный сайт
  • Прикольные скрипты для windows