Если вам понадобился SFTP/SSH сервер на Windows Server 2012 R2, то вы попали по адресу. Установим, запустим, настроим и протестируем OpenSSH Server в Windows Server 2012 R2.
Установка OpenSSH в Windows Server 2012 R2
Скачиваем последнюю версию дистрибутива OpenSSH:
https://github.com/PowerShell/Win32-OpenSSH/releases
Сейчас доступна версия v8.0.0.0p1-Beta. Скачиваю OpenSSH-Win64.zip.
Создаю директорию C:\Program Files\OpenSSH, распаковываю в неё содержимое архива.
Запускаю powershell от имени администратора.
Выполняю скрипт установки:
cd "\Program Files\OpenSSH"
.\install-sshd.ps1
sshd and ssh-agent services successfully installed
Если произошла ошибка политики безопасности, то можно выполнить установку так:
powershell -ExecutionPolicy Bypass -File .\install-sshd.ps1
Генерирую ключи:
.\ssh-keygen.exe -A
В результате вижу ошибку:
Исправляется легко, захожу в папку C:\ProgramData и создаю вручную директорию «ssh».
Снова пытаюсь сгенерировать ключи:
.\ssh-keygen.exe -A
На этот раз процедура выполняется успешно.
Настраиваю владельца файлов и права доступа:
PowerShell -ExecutionPolicy Bypass -File .\FixHostFilePermissions.ps1
На каждый вопрос отвечаю «A».
Открыть 22 порт
OpenSSH работает по порту TCP 22. Открою доступ в Firewall:
New-NetFirewallRule -Protocol TCP -LocalPort 22 -Direction Inbound -Action Allow -DisplayName SSH
То же самое можно сделать через GUI в оснастке Windows Firewall with Advanced Security.
Запуск службы OpenSSH
Открываю список служб:
services.msc
Нахожу службу «OpenSSH SSH Server». В свойствах службы делаю автоматический запуск и запускаю её.
Проверим что 22 порт работает:
netstat -tan | find "22"
22 порт слушается.
Проверка OpenSSH
Проверю с помощью WinSCP. Для доменного пользователя используется логин вида domain\username.
При первом входе появится окно:
Yes.
Всё работает.
Настройка доступа
Конфигурационный файл находится здесь: C:\ProgramData\ssh\sshd_config.
Собственно, OpenSSH конфигурируется здесь. Например, чтобы разрешить доступ по OpenSSH определённой группе пользователей, допишу в конец файла:
DenyUsers *
AllowGroups my_domain\my_group_for_ssh_access
Для удаленного запуска скриптов на Windows Server 2012 решил установить OpenSSH Server. В Windows Server 2019 такая задача проходит легко, OpenSSH спрятан в программы и компоненты, пару галочек и все готово.
Дистрибутив для установки находится на гитхабе. Установка заключается в запуске скриптов на PowerShell.
Скачиваем последнюю версию программы и извлекаем архив. Распакованный архив копируем в C:\Program Files\OpenSSH
Запускаем консоль PowerShell от имени администратора и запускам скрипт:
Дальше необходимо сгенерировать ключи:
Что бы избежать ошибки при генерации ключей, необходимо создать папку SSH в C:\ProgramData
Далее необходимо проверить права доступа на файлы запустив скрипт:
.\FixHostFilePermissions.ps1 |
На возникающие вопросы в скрипте отвечаем — А.
Если используется Windows Firewall, то необходимо добавить исключение для 22 порта.
Правило добавляется командой:
New—NetFirewallRule —Protocol TCP —LocalPort 22 —Direction Inbound —Action Allow —DisplayName Allow—SSH |
Теперь необходимо включить службу OpenSSH SSH Server в оснастке служб.
Тип запуска указываем автоматический и жмем кнопку — запустить.
С помощью встроенного пакета OpenSSH для Windows вы можете легко настроить безопасную передачу файлов между клиентом и серверов Windows по защищенному протоколу передачи файлов SFTP (Secure FTP). В этой статье мы покажем, как установить и настроить установить SFTP сервер в Windows 10/11 или Windows Server 2022/2019/2016/2012R2 с помощью встроенных средств (Win32-OpenSSH).
Содержание:
- Установка OpenSSH в Windows
- Настройка SFTP сервера на базе OpenSSH в Windows
- Подключение к SFTP серверу с помощью PowerShell и WinSCP
- Настройка SFTP аутентификации по ключам
Протокол SFTP (Secure File Transfer Protocol , Secure FTP или SSH FTP) это расширение протокола SSH, являющимся стандартом мира UNIX/Linux систем. Хотя с точки зрения пользователей он похож на FTP, но на самом деле это абсолютно другой протокол, не имеющий с FTP ничего общего. Данные между клиентом и сервером передаются по порту 22 через SSH туннель.
Основные преимущества протокола SFTP:
- Передача файлов и команд происходит внутри защищенной SSH-сессии;
- Для передачи файлов и команд используется одно соединение;
- Поддерживаются символические ссылки, доступны функций прерывания, возобновления передачи, удаления файла и другие;
- Обычно на каналах, где FTP работает медленно или с перебоями, SFTP-соединение работает более надежно и быстро;
- Возможность аутентификации с помощью SSH ключей.
Не нужно путать протоколы SFTP и FTPS. FTPS – это по сути обычный FTP с SSL сертификатом, а SFTP – это передача FTP данных и команд внутри SSH сессии.
В современные версии Windows по-умолчанию встроен порт OpenSSH для win32 (Win32-OpenSSH). Вы можете использовать его для организации защищенного SFTP сервера вместо таких сторониих продуктов как Core FTP, FileZilla, CYGWIN, OpenSSH, FTP Shell, IPSwitch и пр.
Установка OpenSSH в Windows
Пакет OpenSSH уже включен в операционную систему в современных билдах Windows 10 (начиная с 1803), Windows 11, Windows Server 2022/2019 в виде Feature on Demand (как и RSAT).
В этих версиях Windows вы можете установить сервер OpenSSH с помощью PowerShell:
Add-WindowsCapability -Online -Name OpenSSH.Server*
Или с помощью DISM:
dism /Online /Add-Capability /CapabilityName:OpenSSH.Server~~~~0.0.1.0
Также можно установить OpenSSH из графического интерфейса Windows 10 (Settings -> Apps -> Optional Features -> Add a feature -> Open SSH Server -> Install).
Чтобы проверить, установлен ли пакет:
Get-WindowsCapability -Online | ? Name -like 'OpenSSH*'
Исполняемые файлы OpenSSH находятся в каталоге:
C:\windows\system32\OpenSSH\
Конфигурационный файл sshd_config находится в каталоге C:\ProgramData\ssh (каталог создается после первого запуска службы).
Лог — c:\windows\system32\OpenSSH\logs\sshd.log
Файл authorized_keys и ключи хранятся в каталоге %USERPROFILE%\.ssh\.
В предыдущих версиях Windows 10, в Windows 8.1 или в Windows Server 2016/2012 R2 вам придется скачать Win32-OpenSSH для Windows с GitHub и установить вручную (https://github.com/PowerShell/Win32-OpenSSH/releases). Нам нужна версия для 64 битной версии Windows: OpenSSH-Win64.zip (4,15 Мб).
- Распакуйте содержимое архива в целевой каталог, к примеру:
C:\OpenSSH-Win
- Запустите командную строку PowerShell с правами администратора и перейдите в каталог OpenSSH:
cd C:\OpenSSH-Win
- Добавьте путь к каталогу OpenSSH в переменную окружения Path;
- Установите сервер OpenSSH:
.\install-sshd.ps1
должно появиться зеленое сообщение “sshd and ssh-agent services successfully installed”).
Настройка SFTP сервера на базе OpenSSH в Windows
Теперь вам нужно настроить OpenSSH для режима SFTP.
Включите автозапуск для службы SSHD и запустите ее с помощью следующих PowerShell команд управления службами:
Set-Service -Name sshd -StartupType ‘Automatic’
Start-Service sshd
С помошью PowerShell отройте в брандмауэре Windows порт TCP 22 для входящего трафика на SSH сервер:
New-NetFirewallRule -Protocol TCP -LocalPort 22 -Direction Inbound -Action Allow -DisplayName SSH
Откройте в любом текстовом редакторе конфигурационный файл «C:\ProgramData\SSH\sshd_config», найдите и проверьте значение директивы Subsystem sftp. Здесь должен быть указан файл sftp-server.exe.
Рассмотрим полезные директивы в конфигурационном файле sshd_config:
# разрешить подключение к OpenSSH только для пользователей из этой группы
AllowGroups corp\admingroup
# включить аутентификацию по паролю (нельзя использовать ключи SSH)
AuthenticationMethods password ForceCommand internal-sftp
#каталог для SFTP пользователей (по умолчанию пользователь подключается в каталог со своим профилем в папке C:\users\username)
ChrootDirectory C:\SFTPRoot
#Для каждого пользователя можно индивидуальную chrootdirectory:
Match User user1 ChrootDirectory c:\SFTPRoot\user1 ForceCommand internal-sftp X11Forwarding no AllowTcpForwarding no
Match User user2 ChrootDirectory c:\SFTPRoot\user2 ForceCommand internal-sftp X11Forwarding no AllowTcpForwarding no
Подключение к SFTP серверу с помощью PowerShell и WinSCP
Теперь вы может подключиться к вашему SSH серверу на Windows по протоколу SFTP. Ниже мы покажем, как подключиться к SFTP серверу с помощью бесплатного клиента клиент WinSCP, консоли PowerShell и встроенной утилиты sftp.exe.
В окне настройки подключения выберите протокол передачи файлов SFTP, укажите имя сервера и данные учетной записи Windows (в формате
user@domain
для доменных пользователей), под которой осуществляется подключение (возможно также настроить авторизацию по ключам). При первом подключении появится окно с предупреждением о том, что ключ хоста отсутствует в локальном кеше.
При первом подключении появится окно с предупреждением о том, что ключ хоста отсутствует в локальном кеше.
Если все настроено правильно, клиент должен подключиться к SFTP серверу и отобразить список файлов в домашнем каталоге пользователя (по умолчанию каталог с профилем пользователя).
С помощью привычного интерфейса файлового менеджера можно безопасно копировать файлы между сервером и клиентом по защищённому протоколу SFTP.
Для подключения к SFTP серверу из PowerShell можно использовать модуль Posh-SSH. Вы можете скачать установить модуль из PowerShell Gallery или офлайн:
Install-Module -Name Posh-SSH
Для подключения к SFTP серверу с помощью пароля, нужно получить имя пользователя и пароль через Get-Credential:
$usrCreds= Get-Credential
Теперь можно подключиться к вашем SFTPS серверу:
$SFTPSession = New-SFTPSession -ComputerName 192.168.13.200 -Credential $usrCreds
Теперь вы можете вывести список файлов в удаленном каталоге на SFTP сервере. В этом примере я получу список файлов на рабочем столе пользователя (профиль пользователя в этом случае будет являться корнем)
Get-SFTPChildItem -SFTPSession $SFTPSession -Path "desktop" –Recurse
Чтобы скачать файл с удаленного SFTP сервера:
Get-SFTPItem -SessionId $SFTPSession.SessionId -Path "desktop/OpenVPNScript.log" -Destination c:\temp
Чтобы закачать файл с вашего компьютера на удаленный SFTP хост:
Set-SFTPItem -SessionId $SFTPSession.SessionId -Path C:\Temp\mytestfile.log -Destination “desktop”
Завершить SFTP сессию:
Remove-SFTPSession -SFTPSession $SFTPSession
В Windows вы можете использоваться встроенную утилиту sftp.exe (устанавливается вместе с клиентом OpenSSH) для подключения к SFTP серверу.
Подключиться к sftp серверу:
sftp [email protected]
Подключиться с помощью ssh ключа:
sftp -i .ssh/id_rsa [email protected]
Вывести список файлов в удаленном каталоге:
pwd
Скачать файл с SFTP в локальный каталог на ваш компьютер:
get file-test1.txt
Загрузить файл с вашего компьютера на SFTP сервер:
put file-test2.txt
Закрыть сессию:
exit
Настройка SFTP аутентификации по ключам
Вы можете настроить SFTP аутентификацию по ключам. В этом случае при подключении к SFTP серверу вам не нужно будет указывать пароль пользователя.
Подробно настройка SSH аутентификации по ключам описана в этой статье.
Для этого нужно:
- Создать на вашем компьютере (SFTP клиент) ключи для пользователя, под которым вы будете подключаться к серверу:
ssh-keygen -t ed25519
- Утилита сгенерирует два файла
id_ed25519
(закрытый ключ для клиента) и
id_ed25519.pub
(открытый ключ для сервера); - Теперь нужно добавить ваш SSH ключ на сервер. Скопируйте файл id_ed25519.pub(или id_rsa.pub в зависимости от типа ключа) в каталог .ssh профиля пользователя, под которым вы будете подключаться к SFTP серверу. Переименуйте файл в authorized_keys (например для пользователя alex путь будет выглядеть так:
C:\Users\alex\.ssh\authorized_keys
)
Теперь вы можете использоваться файл id_ed25519 для аутентификации на SFTP сервере в настройках WinSCP (настройки подключения Advanced -> to SSH > Authentication page -> Private key file).
Если вы хотите задать SSH ключ при подключении к SFTP из PowerShell, используйте такую команду:
New-SFTPSession -ComputerName 192.168.13.200 -Credential user1 -KeyFile C:\Users\alex\.ssh\id_ed25519" -Verbose
Для тех, кто ищет способ внедрить OpenSSH в среде Windows, данная статья предоставляет простое руководство по установке и настройке OpenSSH на Windows Server 2012 R2.
1. Загрузка дистрибутива OpenSSH
Переходите на официальную страницу релизов OpenSSH и скачивайте последнюю версию дистрибутива. На момент написания данной статьи актуальной была версия v9.2.2.0p1-Beta Для примера я скачал OpenSSH-Win64.zip
.
2. Распаковка и установка дистрибутива OpenSSH
Создайте директорию C:\Program Files\OpenSSH
и распакуйте в неё содержимое скаченного архива.
Далее запустите Powershell от имени администратора и выполните следующие команды:
cd "\Program Files\OpenSSH" .\install-sshd.ps1
Если вы столкнулись с ошибкой политики безопасности, попробуйте выполнить установку с помощью этой команды:
powershell -ExecutionPolicy Bypass -File .\install-sshd.ps1
3. Генерация ключей
.\ssh-keygen.exe -A
При попытке генерации ключей командой .\ssh-keygen.exe -A
может возникнуть ошибка. Чтобы её устранить, перейдите в папку C:\ProgramData
и создайте директорию «ssh». После этого снова выполните команду для генерации ключей.
4. Настройка прав доступа
Для правильной настройки доступа к файлам выполните следующую команду:
PowerShell -ExecutionPolicy Bypass -File .\FixHostFilePermissions.ps1
Отвечайте на каждый запрос подтверждением «A».
5. Настройка Firewall
OpenSSH по умолчанию работает на порту TCP 22. Чтобы разрешить доступ, добавьте правило в брандмауэр Windows с помощью команды:
New-NetFirewallRule -Protocol TCP -LocalPort 22 -Direction Inbound -Action Allow -DisplayName SSH
Альтернативно, это можно сделать и через графический интерфейс, используя инструмент «Windows Firewall with Advanced Security».
6. Запуск службы OpenSSH
Перейдите в список служб, выбрав services.msc
, и найдите «OpenSSH SSH Server». Установите для этой службы режим автоматического запуска и запустите её.
7. Проверка работы
Чтобы удостовериться, что 22 порт активен, выполните:
netstat -a | findstr "22"
Если порт слушается, это значит, что установка прошла успешно.
8. Проверка OpenSSH
Теперь, когда служба запущена, можно проверить её работоспособность. Подключитесь к серверу с помощью команды:
ssh <username>@<your_server_ip>
Если подключение прошло успешно, это значит, что OpenSSH установлен и настроен правильно.
В заключение, OpenSSH – это мощный инструмент для безопасного доступа к удаленным серверам. С его помощью можно легко и безопасно управлять серверами, не беспокоясь о безопасности передаваемых данных.
Также предлагаем рассмотреть другие полезные статьи:
- Как поднять OpenSSH на Windows 2019
- Как поднять OpenSSH на Windows 2016
- Как поднять OpenSSH на Windows 2012
- Подключение к VPS серверу по SSH ключу
Установка OpenSSH Server в Windows Server 2012 R2
Если вам понадобился SFTP/SSH сервер на Windows Server 2012 R2, то вы попали по адресу. Установим, запустим, настроим и протестируем OpenSSH Server в Windows Server 2012 R2.
Установка OpenSSH в Windows Server 2012 R2
Скачиваем последнюю версию дистрибутива OpenSSH:
Сейчас доступна версия v8.0.0.0p1-Beta. Скачиваю OpenSSH-Win64.zip.
Создаю директорию C:\Program Files\OpenSSH, распаковываю в неё содержимое архива.
Запускаю powershell от имени администратора.
Выполняю скрипт установки:
sshd and ssh-agent services successfully installed
Если произошла ошибка политики безопасности, то можно выполнить установку так:
В результате вижу ошибку:
Исправляется легко, захожу в папку C:\ProgramData и создаю вручную директорию «ssh».
Снова пытаюсь сгенерировать ключи:
На этот раз процедура выполняется успешно.
Настраиваю владельца файлов и права доступа:
На каждый вопрос отвечаю «A».
Открыть 22 порт
OpenSSH работает по порту TCP 22. Открою доступ в Firewall:
То же самое можно сделать через GUI в оснастке Windows Firewall with Advanced Security.
Запуск службы OpenSSH
Открываю список служб:
Нахожу службу «OpenSSH SSH Server». В свойствах службы делаю автоматический запуск и запускаю её.
Проверим что 22 порт работает:
22 порт слушается.
Проверка OpenSSH
Проверю с помощью WinSCP. Для доменного пользователя используется логин вида domain\username.
При первом входе появится окно:
Настройка доступа
Конфигурационный файл находится здесь: C:\ProgramData\ssh\sshd_config.
Собственно, OpenSSH конфигурируется здесь. Например, чтобы разрешить доступ по OpenSSH определённой группе пользователей, допишу в конец файла:
Источник
Configuring SFTP (SSH FTP) Server on Windows
You can use the built-in OpenSSH package in Windows to easily enable secure file transfers between the client and Windows server using the SFTP (Secure FTP) protocol. In this article, we will show how to install and configure an SFTP server on Windows 10 or Windows Server 2022/2019/2016/2012R2.
The main advantages of SFTP:
- Files and commands are transferred within a secure SSH session;
- One connection is used to send both files and commands;
- Symbolic links, interrupt/resume the transfer, file delete functions, etc. are supported;
- SFTP connection is much faster and more reliable on WAN links where FTP is slow or intermittent;
- Possibility to authenticate using SSH keys.
The win32 port of OpenSSH (Win32-OpenSSH) is built into all modern versions of Windows by default. You can use it to configure a secure SFTP server instead of using third-party products like Core FTP, FileZilla, CYGWIN, FTP Shell, IPSwitch, etc.
How to Install OpenSSH on Windows?
The OpenSSH package is a part of the operating system in modern builds of Windows 10 (starting from 1803), Windows 11, and Windows Server 2022/2019 as a Feature on Demand (like RSAT).
Add-WindowsCapability -Online -Name OpenSSH.Server*
Or using DISM:
dism /Online /Add-Capability /CapabilityName:OpenSSH.Server
Also, you can install OpenSSH server from Windows 10 GUI (Settings -> Apps -> Optional Features -> Add a feature -> Open SSH Server -> Install).
To check if a package is installed:
Get-WindowsCapability -Online | ? Name -like ‘OpenSSH*’
- OpenSSH executables are located in the directory: c:\windows\system32\OpenSSH\ ;
- The sshd_config configuration file is located in C:\ProgramData\ssh (this directory is created after the first start of the sshd service);
- Log file: c:\windows\system32\OpenSSH\logs\sshd.log ;
- The authorized_keys file and keys are stored in a directory: %USERPROFILE%\.ssh\ .
On the previous earlier builds of Windows 10, Windows 8.1, and on Windows Server 2016/2012 R2, you will have to download Win32-OpenSSH for Windows from GitHub and install it manually (https://github.com/PowerShell/Win32-OpenSSH/releases). We need a version for Windows x64: OpenSSH-Win64.zip (4,15 MB).
- Extract the archive to the target folder: C:\OpenSSH-Win;
- Open an elevated PowerShell prompt and switch to the OpenSSH folder: Cd C:\OpenSSH-Win
- Add the path to the OpenSSH directory to the Path environment variable (System Properties -> Advanced tab -> Environment Variables -> Select and edit the Path system variable -> Add the path to the OpenSSH folder);
- Install the OpenSSH server: .\install-sshd.ps1 (a green message should appear “ sshd and ssh-agent services successfully installed ”);
How to Configure SFTP Server on Windows Using OpenSSH?
Now you need to configure OpenSSH on Windows for SFTP mode.
Enable autostart for the SSHD service and start it using the following PowerShell service management commands:
Set-Service -Name sshd -StartupType ‘Automatic’
Start-Service sshd
Use the PowerShell to open TCP port 22 in the Windows Firewall for incoming SSH traffic:
New-NetFirewallRule -Protocol TCP -LocalPort 22 -Direction Inbound -Action Allow -DisplayName SSH
Open the SSHD configuration file ( C:\ProgramData\SSH\sshd_config ) in any text editor. Find and check the value of the Subsystem sftp directive. The sftp-server.exe file should be specified here.
Connecting to SFTP Server Using WinSCP or PowerShell
Now you can connect to your Windows SSH server using the SFTP protocol. Next, we’ll show you how to connect to an SFTP server using the free WinSCP client, the PowerShell console, and the built-in sftp.exe tool.
In the connection configuration window, select the SFTP as the file transfer protocol, specify the server name and the credentials of the Windows account (use the user@domain format for domain users), which is used for connection (it is also possible to configure public key authentication).
When you try to connect for the first time, the following notification of the host key not found in the local cache appears.
If everything is configured correctly, a client should connect to the SFTP server and display the list of files in the user’s home chroot directory (by default, it is the user’s profile directory).
Using the familiar file manager interface (like Total Commander), you can copy files between the server and the client using the secure SFTP protocol.
You can use the Posh-SSH module to connect to an SFTP server from PowerShell. You can download and install the module from the PowerShell Gallery or offline:
Install-Module -Name Posh-SSH
To connect to the SFTP server using a password, you need to get the username and password via Get-Credential:
Now you can connect to your SFTP server:
$SFTPSession = New-SFTPSession -ComputerName 192.168.3.20 -Credential $usrCreds
Now you can list the files in the remote directory on the SFTP server. In this example, I will get a list of files on the user’s Desktop (the user’s profile will be the root user folder/chroot in this case)
Get-SFTPChildItem -SFTPSession $SFTPSession -Path «desktop» –Recurse
Download a file from a remote SFTP server:
Get-SFTPItem -SessionId $SFTPSession.SessionId -Path «desktop/OpenVPNScript.log» -Destination c:\PS
To upload a file from your computer to a remote SFTP host:
Set-SFTPItem -SessionId $SFTPSession.SessionId -Path C:\PS\mytestfile.log -Destination «desktop»
Close the SFTP session:
Remove-SFTPSession -SFTPSession $SFTPSession
On Windows, you can use the built-in sftp.exe console command (installed with the OpenSSH client) to connect to an SFTP server.
Connect to sftp server:
Connect using ssh private key:
sftp -i .ssh/id_rsa user1@192.168.3.20
List files in a remote directory:
Download the file from SFTP to a local directory on your computer:
Upload a file from your computer to an SFTP server:
Configuring SFTP Public Key Authentication
You can enable SFTP key-based authentication in Windows. In this case, you can authenticate to the SFTP server without entering a password.
- Create SSH keys on your computer (SFTP client) for the user under which you will connect to the server: ssh-keygen -t ed25519
- The ssh-keygen tool will generate two files id_ed25519 (private key for the client computer) and id_ed25519.pub (public key for the SFTP server);
- Now you need to add your SSH key to the Windows server (SFTP host). Copy the file id_ed25519.pub (or id_rsa.pub depending on the key type) to the .ssh directory of the user profile under which you will connect to the SFTP. Rename the file to authorized_keys (for example, the following key file is used for the user max1 : C:\Users\max1\.ssh\authorized_keys )
Now you can use the id_ed25519 file to authenticate on the SFTP server. You can set your key in the WinSCP settings (Advanced -> to SSH connection settings > Authentication page -> Private key file).
If you want to use an SSH key when connecting to SFTP from PowerShell, use the following command:
New-SFTPSession -ComputerName 192.168.3.20 -Credential remoteuser1 -KeyFile C:\Users\max1\.ssh\id_ed25519″ -Verbose
Источник
OpenSSH client and server – installation on Windows Server 2012R2 and 2016
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.
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).
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
Install the OpenSSH server on Windows Server 2012R2 / 2016
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
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.
Once connected, enter a command such as ipconfig or hostname to validate that the command has been executed on the 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”.
Источник