- Установка и настройка SFTP сервера (SSH FTP) в Windows на базе OpenSSH
- Особенности протокола SFTP
- Реализация SFTP в системах Windows
- Установка Win32 OpenSSH в Windows 10 1803+/Windows Server 2019
- Установка Win32 OpenSSH на Windows Server 2016/2012 R2
- Тестируем SFTP подключение с помощью WinSCP
- Удаление службы Win32 OpenSSH
- WinSCP Downloads
- Download latest WinSCP 5.17
- Portable executables
- .NET assembly / COM library
- Source code
- Download WinSCP 5.18 RC
- Installing SFTP/SSH Server on Windows using OpenSSH
- Installing SFTP/SSH Server
- On Windows 10 version 1803 and newer
- On earlier versions of Windows
- Configuring SSH server
- Setting up SSH public key authentication
- Connecting to the server
- Finding Host Key
- Connecting
- Download and Install WinSCP
- Downloading
- Installation
- Further Reading
Установка и настройка SFTP сервера (SSH FTP) в Windows на базе OpenSSH
С помощью официального пакета OpenSSH для Windows вы можете с легкостью организовать безопасный обмен файлами между клиентом и серверов Windows по защищенному протоколу передачи файлов SFTP (Secure FTP). В этой статье мы покажем, как с помощью Win32-OpenSSH установить SFTP сервер на Windows 10 или Windows Server 2016/2012R2.
Особенности протокола SFTP
Протокол SFTP (Secure File Transfer Protocol , Secure FTP или SSH FTP) это расширение протокола SSH, являющимся стандартом мира UNIX/Linux систем. Хотя с точки зрения пользователей он похож на FTP, но на самом деле это абсолютно другой протокол, не имеющий с FTP ничего общего. Данные между клиентом и сервером передаются по порту 22 через SSH туннель.
Основные преимущества протокола SFTP:
- Передача файлов и команд происходит внутри защищенной SSH-сессии;
- Для передачи файлов и команд используется одно соединение;
- Поддержка символических ссылок, функций прерывания, возобновления передачи, удаления файла и пр;
- Как правило, на каналах, где FTP работает медленно или с перебоем, SFTP-соединение работает более надежно и быстро;
- Возможность аутентификации с помощью SSH ключей.
Реализация SFTP в системах Windows
Исторически в операционных системах Windows отсутствуют встроенные средства для организации защищенного SFTP сервера. Для этих целей обычно использовались открытые или коммерческие решения, к примеру, Core FTP, FileZilla, CYGWIN, OpenSSH, FTP Shell, IPSwitch и пр. Однако несколько лет назад Microsoft выпустила свою версию порта OpenSSH для win32. Данный проект называется Win32-OpenSSH.
Рассмотрим процесс настройки SFTP сервера в Windows 10 и Windows Server 2016/2012 R2 с помощью пакета Win32-OpenSSH.
Установка Win32 OpenSSH в Windows 10 1803+/Windows Server 2019
В Windows 10, начиная с билда 1803, и в Windows Server 2019 пакет OpenSSH (как и RSAT) уже включен в операционную систему в виде Feature on Demand (FoD).
В Windows 10 и Windows Server 2019 вы можете установить сервер OpenSSH с помощью командлета PowerShell:
Add-WindowsCapability -Online -Name OpenSSH.Server*
Или с помощью DISM:
dism /Online /Add-Capability /CapabilityName:OpenSSH.Server
Или можно установить OpenSSH из графического интерфейса Windows 10 (Settings -> Apps -> Optional Features -> Add a feature -> Open SSH Server -> Install).
Исполняемые файлы OpenSSH находятся в каталоге:
Конфигурационный файл sshd_config находится в каталоге C:\ProgramData\ssh (каталог создается после первого запуска службы).
Файл authorized_keys и ключи хранятся в каталоге %USERPROFILE%\.ssh\.
Установка Win32 OpenSSH на Windows Server 2016/2012 R2
В предыдущих версиях Windows 10 и в Windows Server 2016/2012 R2 вы должны скачать и установить OpenSSH с GitHub (https://github.com/PowerShell/Win32-OpenSSH/releases). Нам нужна версия для 64 битной версии Windows: OpenSSH-Win64.zip (3,5 Мб).
- Распаковываем содержимое архива в целевой каталог, к примеру: C:\OpenSSH-Win
- Запускаем командную строку PowerShell с правами администратора и переходим в каталог OpenSSH: Cd C:\OpenSSH-Win
- Добавьте путь к каталогу OpenSSH в переменную окружения Path;
- Установите сервер OpenSSH: .\install-sshd.ps1 (должно появиться зеленое сообщение “sshd and ssh-agent services successfully installed”);
- Сгенерируйте SSH ключи для сервера (нужны для запуска службы sshd): ssh-keygen.exe –A
, убедитесь, что создан каталог %programdata%\ssh.
Тестируем SFTP подключение с помощью WinSCP
Попробуем подключиться к поднятому нами SSH серверу по протоколу SFTP. Для этих целей воспользуемся свободным клиентом WinSCP.
В окне настройки подключения выберите протокол передачи файлов SFTP, укажите имя сервера и данные учетной записи Windows, под которой осуществляется подключение (возможно также настроить авторизацию по ключам).При первом подключении появится окно с предупреждением о том, что ключ хоста отсутствует в локальном кеше.
Если все настроено правильно, клиент должен подключиться к SFTP серверу и отобразить список файлов в домашнем каталоге пользователя (по умолчанию каталог с профилем пользователя).
С помощью привычного интерфейса файлового менеджера можно безопасно копировать файлы между сервером и клиентом. Передача файлов будет осуществляться по защищённому протоколу SFTP.
Удаление службы Win32 OpenSSH
Чтобы корректно удалить службу Win32 OpenSSH из системы:
- Откроем консоль Powershell с правами администратора
- Остановим службу SSHD: Stop-Service sshd
- Удалим службу OpenSSD:Удалим ключи: .\uninstall-sshlsa.ps1
WinSCP Downloads
Download latest WinSCP 5.17
WinSCP 5.17 is a major application update. New features and enhancements include:
- Improvements to sessions and workspace management, so that WinSCP can now easily restore tabs that were open when it was last closed.
- Hardware-accelerated AES .
- Extension Archive and Download to archive remote files and download the archive.
- Improvements to Synchronization checklist window.
- Allowed sorting of find results.
- SSH core upgraded to PuTTY 0.73.
- The binaries are signed with new EV certificate valid until February 2023.
- Download WinSCP 5.17.10 (10.6 MB) 3,494,610 downloads since release
What is this?
- List of changes
Portable executables
8.7 MB
63,571 downloads since release
.NET assembly / COM library
8.7 MB
4,918 downloads since release
Source code
13.6 MB
1,217 downloads since release
Download WinSCP 5.18 RC
The most important changes/additions are:
- A complete list of files that are queued for a transfer can be shown.
- A streaming support in scripting and .NET assembly.
- An extension for synchronizing two remote servers.
- Enabled TLS 1.3 and added support for SHA-256 TLS/SSL fingerprints.
- Download WinSCP 5.18.3 RC (10.8 MB) 3,747 downloads since release
- List of changes
Installing SFTP/SSH Server on Windows using OpenSSH
Recently, Microsoft has released a port of OpenSSH for Windows. You can use the package to set up an SFTP /SSH server on Windows.
Installing SFTP/SSH Server
On Windows 10 version 1803 and newer
- In Settings app, go to Apps > Apps & features > Manage optional features.
- Locate “OpenSSH server” feature, expand it, and select Install.
Binaries are installed to %WINDIR%\System32\OpenSSH . Configuration file ( sshd_config ) and host keys are installed to %ProgramData%\ssh (only after the server is started for the first time).
You may still want to use the following manual installation, if you want to install a newer version of OpenSSH than the one built into Windows 10.
On earlier versions of Windows
- Download the latest OpenSSH for Windows binaries (package OpenSSH-Win64.zip or OpenSSH-Win32.zip )
- As the Administrator, extract the package to C:\Program Files\OpenSSH
- As the Administrator, install sshd and ssh-agent services:
Configuring SSH server
- Allow incoming connections to SSH server in Windows Firewall:
- When installed as an optional feature, the firewall rule “OpenSSH SSH Server (sshd)” should have been created automatically. If not, proceed to create and enable the rule as follows.
- Either run the following PowerShell command as the Administrator:
Replace C:\System32\OpenSSH\sshd.exe with the actual path to the sshd.exe ( C:\Program Files\OpenSSH\ssh.exe , had you followed the manual installation instructions above). - or go to Control Panel > System and Security > Windows Defender Firewall1> Advanced Settings > Inbound Rules and add a new rule for port 22.
- Start the service and/or configure automatic start:
- Go to Control Panel > System and Security > Administrative Tools and open Services. Locate OpenSSH SSH Server service.
- If you want the server to start automatically when your machine is started: Go to Action > Properties. In the Properties dialog, change Startup type to Automatic and confirm.
- Start the OpenSSH SSH Server service by clicking the Start the service.
Setting up SSH public key authentication
Follow a generic guide for Setting up SSH public key authentication in *nix OpenSSH server, with the following difference:
Connecting to the server
Finding Host Key
Before the first connection, find out fingerprint of the server’s host key by using ssh-keygen.exe for each file.
In Windows command-prompt, use:
Replace %WINDIR%\System32 with %ProgramFiles% , if appropriate.
In PowerShell, use:
Replace $env:WINDIR\System32 with $env:ProgramFiles , if appropriate.
You will get an output like this:
Connecting
Start WinSCP. Login dialog will appear. On the dialog:
- Make sure New site node is selected.
- On New site node, make sure the SFTP protocol is selected.
- Enter your machine/server IP address (or a hostname) into the Host name box.
- Enter your Windows account name to the User name box. It might have to be entered in the format user@domain , if running on a domain.
- For a public key authentication:
- Press the Advanced button to open Advanced site settings dialog and go to SSH > Authentication page.
- In Private key file box select your private key file.
- Submit Advanced site settings dialog with the OK button.
- For a password authentication:
- Enter your Windows account password to the Password box.
- If you Windows account does not have a password, you cannot authenticate with the password authentication (i.e. with an empty password), you need to use the public key authentication.
- Save your site settings using the Save button.
- Login using Login button.
- Verify the host key by comparing fingerprint with those collected before (see above).
If you cannot authenticate to the server, and you are using Windows 10 Developer mode, make sure that your OpenSSH server does not conflict with an internal SSH server used by the Developer mode. You may need to turn off the SSH Server Broker and SSH Server Proxy Windows services. Or run your OpenSSH server on a different port than 22.
Download and Install WinSCP
This guide contains a simplified description of downloading and installing WinSCP. You may want to see detailed documentation of the process instead.
Downloading
You can obtain WinSCP from the WinSCP download page. Follow the Installation package link. You should save the installer to an easily accessible location such as your Windows desktop or your My Documents folder.
WinSCP is also available from Microsoft Store.
Installation
- Open the installation program by double clicking on its icon.
- If your Windows language is not supported by the installer, select an alternative language you want to use (both for installation and later when using WinSCP).
- On the License Agreement screen click Accept after reviewing the license.
- You will be prompted to select a setup type. For a basic setup, choose Typical installation.
- Then you will be prompted for Initial User Settings. This allows you to select user interface style. If you have used (and enjoyed) file managers like Total Commander, Altap Salamander or Norton Commander before, keep default Commander interface. Otherwise you will probably be more familiar with Explorer interface.
- After you select the interface, the Ready to Install screen opens. On this screen, you can review the installation options you’ve selected. Click Install to start the installation.
- A brief installation process will take place. You may have to restart Windows File Explorer or your computer. If you choose not to restart, some WinSCP functions may not be available until you do so.
Further Reading
If you need more details check documentation for installing WinSCP.
Once you have WinSCP installed you may want to check:
- Other guides to using WinSCP;
- Tasks you can do with WinSCP;
- Using WinSCP as portable application.