Установить ssh на windows server 2016

You might find it useful to install OpenSSH on your Windows server. Running SSH on your Windows server means that you can transfer files using Secure Copy (SCP) or SFTP.  Aside from SCP and SFTP, you can open a secure Powershell shell or a Bash shell if Windows Subsystem for Linux (WSL) is enabled on your Windows server.

By default, you will enter into a Windows CMD shell when you connect to the server using SSH.

This guide will explain the steps to install and configure OpenSSH in Windows Server 2016. It would be best if you were prepared to log in to your Hostwinds Windows Server to continue with this guide.

Step 1: Download and Install OpenSSH

Start by accessing your server via RDP (from Mac), and download the latest release of OpenSSH (OpenSSH-Win64.zip).

Locate the downloaded file, right-click it, and Extract All to C:\Program Files\OpenSSH-Win64.

Optional: To change the default SSH port to something other than 22, select the sshd_config_default file in the OpenSSH folder and open with a text editor:

Uncomment Port 22 and change it to your desired port, then save the file:

End optional step.

Next, search for and right-click Powershell to Run as administrator:

Modify the Path system environment variable by running the command:

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

You should see the following output:

SUCCESS: Specified value was saved.

Next, change to the OpenSSH directory:

cd "C:\Program Files\OpenSSH-Win64"

Then run the install script:

.\install-sshd.ps1

Next, enable automatic startup and start sshd and ssh-agent:

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

Step 2: Allow Access in Windows Firewall

Start by opening Control Panel > Windows Firewall:

Select Advanced Settings on the left-hand side, then select Inbound Rules > New Rule…:

Under Rule Type, select Custom > Next.

Under Program, select All programs > Next.

Under Protocols and Ports, enter your desired SSH port with the following selections:

Under Scope, let the rule apply to Any IP address for remote and local IP addresses, then Next.

Under Action, select Allow the connection > Next.

Under Profile, leave Domain, Private, and Public checked > Next.

Lastly, name the rule and select Finish.

Now you can access your Windows server using SSH!

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

  • 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

In this tutorial, I will explain how to install the OpenSSH client and Server on Windows Server 2012R2 and 2016.

At the time of writing this tutorial, this feature is native to Windows 10 and Windows Server 2019 and you might also want to have OpenSSH client or server on an earlier version.

Personally, I use the SSH client very regularly through PowerShell or Command Prompt windows, it avoids having to install Putty.

  1. Recover Win32 OpenSSH
  2. «Installation» of files on the server
  3. Adding the environment variable
  4. Use the SSH client of Windows Server 2012R2 / 2016
  5. Install the OpenSSH server on Windows Server 2012R2 / 2016
  6. Connect to Windows on the SSH server
  7. Conclusion

Recover Win32 OpenSSH

The first step is to retrieve from the GitHub repository PowerShell/Win32-OpenSSH: Win32 port of OpenSSH (github.com), the latest version available.

Go to the realeases page and download the latest version available corresponding to the architecture of the Windows installation (32 or 64 bits).

Github Windows OpenSSH

For me, it will be the 64 Bits version.

Once the archive has been downloaded, unzip it.

“Installation” of files on the server

Now, we will copy the folder from the unzipped archive to the C: \ Program Files folder.

The SSH client is now functional, but for ease of use, we will configure its location in the environment variables so as not to have to call the executable by its full path.

Adding the environment variable

Open the system window and click on Advanced system settings 1.

On the Advanced system parameters tab, click on the Environment variables 1 button.

In the System variable part, find the Path 1 variable, once selected, click on the Modify 2 button.

On Windows 2012R2, add at the end; C: \Program Files\OpenSSH-Win64\

On Windows 2016, click on New 1.

Add the location of the OpenSSH folder: C:\Program Files\OpenSSH-Win64\ 1 and click on OK 2.

Close the various windows.

Use the SSH client of Windows Server 2012R2 / 2016

Open a command prompt or PowerShell.

The easiest way to find out if it’s okay is to enter the ssh command. This command should return the various parameters of the SSH utility.

To connect to a server (Linux) enter the command ssh USER @ IP_SERVER

It is also possible to configure an OpenSSH server on Windows Server with Win32 OpenSSH which will allow you to connect to the Windows server in the same way as a Linux OS.

From a PowerShell window, go to the C: \ Program Files \ OpenSSH-Win64 \ folder, in the folder is a PowerShell script that will configure the server part.

Run the install-sshd.ps1 PowerShell script

Install OpenSSH Server on Windows

If the installation is successful, the message is displayed: sshd and ssh-agent services successfully installed.

Open Windows Service Manager and search for OpenSSH SSH Server, by default it is stopped. Start the service.

If necessary, configure the service to start automatically

Depending on your configuration, remember to allow incoming connections on port 22.

The server part is operational.

Connect to Windows on the SSH server

From another computer, use an SSH client to connect, being in an Active Directory environment, I just need to use the ssh IP_SERVER command and then enter my password.

Connection to OpenSSH Server on Windows target

Once connected, enter a command such as ipconfig or hostname to validate that the command has been executed on the remote server.

ipconfig on remote server

Conclusion

For the client part, for my part, I find the use in native practical which avoids going through a third-party tool and we quickly get used to when we use Windows 10 and the SSH client I find, missing on Windows 2012R2 and Windows 2016 , the problem is now resolved 🙂

For the server part, I find it useful for non-domain servers, because configuring WinRM and PSSession for connection can quickly become “a headache”.

How to Install OpenSSH Server/Client on Windows Server 2016 1607 or Before

OpenSSH is the premier connectivity tool for remote login with the SSH protocol. It encrypts all traffic to eliminate eavesdropping, connection hijacking, and other attacks. In addition, OpenSSH provides a large suite of secure tunneling capabilities, several authentication methods, and sophisticated configuration options. Installation of OpenSSH server/client on Windows 2016 1709 onward is really easy. its just few powershell commands away from using it but for older versions it can be a time wasting activity. The easiest way to install is still very long but I would to wrap in few basic steps:

Download OpenSSH

First you need to Download OpenSSH using the attached URL. A zip file will be downloaded on your desired system. Unzip it and copy it under Windows\system32 directory.

Open PowerShell ISE

Open PowerShell ISE with administrative privileges so that you can run the desired commands without any problem. Change the directory to c:\windows\system32\openssh

Run the Commands

First you need to modify the required permission so run the under given command from OpenSSh Directory. The commands are given in the picture below:

openssh server

Run the commands in the given order and OpenSSH server will be installed on the Windows Server 2016 1607 or earlier version.

Environment Variables

Copy the directory path and set the system environment variables so that the commands can work without giving the exact path. You can use PowerShell commands to set the path or go to system settings and manually set the path.

Start the services

Change the service startup type from manual to automatic and start the service to use OpenSSH server.

Windows Firewall Settings

SSH works on TCP port 22 so you need to open in-bound port in Windows firewall so that in-coming connections can be accepted. Opening firewall port is pretty simple and I think there is no need to share any command or process to do it.

Thanks for visiting. I hope you like the post.

Search code, repositories, users, issues, pull requests…

Provide feedback

Saved searches

Use saved searches to filter your results more quickly

Sign up

  • Установить smtp сервер на windows
  • Установить windows 10 enterprise ltsc
  • Установить ssh server windows server 2019
  • Установить whatsapp на компьютер на русском для windows 10
  • Установить shareman бесплатно для windows 10