Openssh server windows powershell

Подключение к Windows по SSH с помощью встроенного OpenSSH

Начиная с Windows 10 1809 и Windows Server 2019 в операционной системе имеется встроенный SSH сервер, основанный на OpenSSH. В этой статье мы покажем, как установить и настроить OpenSSH сервер в Windows 10 и подключиться к нему удаленно по защищенному SSH протоколу (ну прям как в Linux 🙂 ).

Установка сервера OpenSSH в Windows

Рассмотрим, как установить компонент OpenSSH Server в Windows 10 1903 (Windows Server 2019 все выполняется аналогично).

Пакет OpenSSH (как и RSAT) уже включен в данные версии Windows в виде Feature on Demand (FoD).

При наличии прямого Интернет-подключения вы можете установить сервер OpenSSH с помощью PowerShell

Add-WindowsCapability -Online -Name OpenSSH.Server*

Или при помощи DISM:

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

В Windows 10 этот компонент также можно установить через панель Параметры (Приложения -> Управление дополнительными компонентами -> Добавить компонент). Найдите в списке Open SSH Server и нажмите кнопку Install).

Чтобы проверить, что OpenSSH сервер установлен, выполните:
Get-WindowsCapability -Online | ? Name -like ‘OpenSSH.Ser*’

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

После уставной сервера OpenSSH в Windows вам нужно изменить тип запуска службы sshd на автоматический и запустить службу с помощью PowerShell:

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

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

netstat -na| find «:22»

Проверьте, что включено правило брандмауэра (Windows Defender Firewall), разрешающее входящие подключения к Windows по порту TCP/22.

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

Если правило отключено (состоянии 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_config (создается после первого запуска службы): C:\ProgramData\ssh
  • Журнал OpenSSH: C:\windows\system32\OpenSSH\logs\sshd.log
  • Файл authorized_keys и ключи: %USERPROFILE%\.ssh\

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

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

Вы можете изменить настройки сервере OpenSSH в конфигурационном файле %programdata%\ssh\sshd_config.

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

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

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

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

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

Читайте также:  Что такое менеджер лицензий для windows

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

Подключение к Windows 10 через SSH

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

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

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

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

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

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

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

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

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

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

Install OpenSSH

Applies to Windows Server 2019, Windows 10

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

OpenSSH can be used to connect Window 10 clients to Windows Server 2019. OpenSSH Client is available to install on Windows 10 build 1809 and later, while OpenSSH Server is available to install on Windows Server 2019 and later.

If you downloaded OpenSSH from the GitHub repo at PowerShell/openssh-portable, follow the instructions listed there, not the ones in this article.

Install OpenSSH using Windows Settings

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

To install the OpenSSH components:

Open Settings, select Apps > Apps & Features, 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:

  • On Windows 10, find OpenSSH Client, then click Install
  • On Windows Server 2019, find OpenSSH Server, then click Install

Once setup completes, return to Apps > Apps & Features 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.

Install OpenSSH using PowerShell

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

This should return the following output:

Then, install the server or client components as needed:

Both of these should return the following output:

Start and configure SSH Server

To start and configure OpenSSH server for initial use, open PowerShell as an administrator, then run the following commands to start the SSHD service :

Читайте также:  Диспетчер устройств администратор заблокировал выполнение этого приложения windows 10 home

Connect to SSH Server

Once installed, you can connect to OpenSSH Server from a Windows 10 device with the SSH client installed using PowerShell as follows. Be sure to run PowerShell as an administrator:

Once connected, you get a message similar to the following:

Selecting yes adds that server to the list of known ssh hosts on your Windows client.

You are prompted for the password at this point. As a security precaution, your password will not be displayed as you type.

Once connected, you will see the Windows command shell prompt:

Uninstall OpenSSH using Windows Settings

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.

Uninstall OpenSSH using PowerShell

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.

Using the OpenSSH Beta in Windows 10 Fall Creators Update and Windows Server 1709

December 15th, 2017

I’m thrilled to share that a Beta OpenSSH client and server daemon are available as a Feature-on-Demand in Windows 10 Fall Creators Update and Windows Server 1709. Since our last update blog, we’ve been working hard on a Win32 port of OpenSSH and working closely with members of the OpenSSH Portable and OpenBSD projects with the eventual goal of bringing Win32 support upstream into OpenSSH Portable.

Until then, you should expect OpenSSH support in Windows to continue to improve in future updates of Windows, including upcoming Windows Insider builds. You can track our progress on GitHub where you can find our wiki and the latest builds that include tons of fixes and support for operating systems downlevel to Windows 7 and Server 2008 R2.

Overview

OpenSSH is a collection of client/server utilities that enable secure remote login, remote file transfer, and public/private key pair management. It’s an extremely powerful tool that originated as part of the OpenBSD project, and has been used for many years across the BSD, Linux, macOS, and Unix ecosystems.

Note: The OpenSSH client and server are still very much in Beta, so we do not recommend using them in production environments.

Installation

Great! So how do I install the bits?

Installing with the Settings UI

To install it using the Settings UI, go to Apps -> Apps and Features -> Manage optional features -> Add a feature:

Then select OpenSSH Client (Beta) or OpenSSH Server (Beta) and Install:

Installing with PowerShell

To install OpenSSH using PowerShell, first launch PowerShell as an Administrator.

To make sure that the OpenSSH features are available for install:

This should return the following output:

Then, install the server and/or client features:

Both of these should return the following output:

Installing with DISM.exe

To install OpenSSH with DISM.exe, first open CMD as an Administrator.

To make sure that OpenSSH features are available for install:

This should return the following output:

Then, install the server and/or client features:

Configuration

Great! You’ve installed OpenSSH. What now?

Читайте также:  Fl studio linux alternative

Configuring the SSH Client (ssh.exe)

Password-based authentication

If you want to use the SSH client with password authentication, no configuration is necessary. Just pop open PowerShell or cmd, and use ssh to connect to your SSH server:

Key-based authentication

If you want to use key-based authentication, you first need to generate some public/private key pairs for your client. From PowerShell or cmd, use ssh-keygen to generate some key files.

This should output something like:

You can hit Enter to accept the default or specify a path where you’d like your keys to be generated. At this point, you’ll be prompted to use a passphrase to encrypt your private key files.

Now you have a public/private ED25519 key pair (the .pub files are public keys and the rest are private keys):

Your private key files are the equivalent of a password. You should protect them under any and all circumstances. If someone acquires your private key, they can log in to any SSH server as an identity that authorizes the corresponding public key to log in.

For that reason, we should take advantage of ssh-agent to securely store the private keys within a Windows security context. To do that, we simply start the ssh-agent service (as Administrator) and use ssh-add to store our private key. Then, whenever a private key is needed for authentication, ssh-agent will automatically retrieve your local user’s private key and pass it to your SSH client.

Move the contents of your public key (

\.ssh\id_ed25519.pub ) into a text file called authorized_keys in

\.ssh\ on your server/host.

Note: these directions assume your sshd server is a Windows-based machine using our OpenSSH-based server, and that you’ve properly configured it based on the instructions below (including the installation of the OpenSSHUtils PowerShell module). If you’re using a non-Windows machine, you should replace all remote instances of C:\users\user1 with something like /home/user1 . Additionally, the ACL line should be unnecessary that uses PowerShell should be unnecessary.

Congrats! You should no longer need a password when authenticating as User1 against contoso.com .

Configuring the OpenSSH Server (sshd)

First, it’s worth noting again that this OpenSSH for Windows is still very much in beta form. It should only be used in safe, testing environments.

To enable authentication into an SSH server on Windows, you first have to generate host keys. As an Administrator:

Due to certain security requirements, you will also have to install our OpenSSHUtils helper module to appropriately ACL your host keys. As an Administrator:

Then you can start sshd and your server is ready to go:

Note: currently only the built-in ED25519 authentication key type is supported. In the future, we plan to add support for LibreSSL which will enable additional authentication key types. In the meantime, you can experiment with LibreSSL builds on GitHub.

You may also need to add a firewall rule like this one that allows traffic on port 22 (though your requirements may vary based on your environment, e.g. Domain might be Private ):

Stay tuned!

Enjoy playing with OpenSSH on Windows, and keep your eyes peeled on the PowerShell blog for upcoming news.

Оцените статью