Установка и настройка 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
ftp ftp
Область применения: Windows Server (половина ежегодного канала), Windows Server 2019, Windows Server 2016, Windows Server 2012 R2, Windows Server 2012 Applies to: Windows Server (Semi-Annual Channel), Windows Server 2019, Windows Server 2016, Windows Server 2012 R2, Windows Server 2012
Передает файлы на компьютер, на котором запущена служба протокол FTP (FTP), и с него. Transfers files to and from a computer running a File Transfer Protocol (ftp) server service. Эту команду можно использовать интерактивно или в пакетном режиме, обрабатывая текстовые файлы ASCII. This command can be used interactively or in batch mode by processing ASCII text files.
Синтаксис Syntax
Параметры Parameters
Параметр Parameter | Описание Description |
---|---|
-v -v | Отключает отображение ответов на удаленные серверы. Suppresses display of remote server responses. |
-d -d | Включает отладку, отображая все команды, передаваемые между FTP-клиентом и FTP-сервером. Enables debugging, displaying all commands passed between the FTP client and FTP server. |
-i -i | Отключает Интерактивные запросы во время передачи нескольких файлов. Disables interactive prompting during multiple file transfers. |
-n -n | Подавляет автоматическое имя входа при начальном подключении. Suppresses auto-login upon initial connection. |
-g -g | Отключает имя файла глобализации. Disables file name globbing. Стандартная маска позволяет использовать звездочку (*) и вопросительный знак (?) в качестве подстановочных знаков в именах локальных файлов и путей. Glob permits the use of the asterisk (*) and question mark (?) as wildcard characters in local file and path names. |
#d0 -s: | Указывает текстовый файл, содержащий команды FTP . Specifies a text file that contains ftp commands. Эти команды выполняются автоматически после запуска FTP . These commands run automatically after ftp starts. Этот параметр не допускает пробелов. This parameter allows no spaces. Используйте этот параметр вместо перенаправления ( ). Use this parameter instead of redirection ( ). Примечание. В операционных системах Windows 8 и Windows Server 2012 или более поздней версии текстовый файл должен быть написан в кодировке UTF-8. Note: In Windows 8 and Windows Server 2012 or later operating systems, the text file must be written in UTF-8. |
-a -a | Указывает, что при привязке подключения к данным FTP можно использовать любой локальный интерфейс. Specifies that any local interface can be used when binding the ftp data connection. |
-A -A | Выполняет вход на FTP-сервер как анонимный. Logs onto the ftp server as anonymous. |
x -x: | Переопределяет размер SO_SNDBUF по умолчанию 8192. Overrides the default SO_SNDBUF size of 8192. |
Cерверный -r: | Переопределяет размер SO_RCVBUF по умолчанию 8192. Overrides the default SO_RCVBUF size of 8192. |
& -b: | Переопределяет число асинхронных буферов по умолчанию, равное 3. Overrides the default async buffer count of 3. |
Белая -w: | Задает размер буфера перемещения. Specifies the size of the transfer buffer. Размер окна по умолчанию составляет 4096 байт. The default window size is 4096 bytes. |
Указывает имя компьютера, IP-адрес или IPv6-адрес сервера FTP, к которому осуществляется подключение. Specifies the computer name, IP address, or IPv6 address of the ftp server to which to connect. Имя узла или адрес, если он указан, должен быть последним параметром в строке. The host name or address, if specified, must be the last parameter on the line. | |
-? -? | Отображение справки в командной строке. Displays help at the command prompt. |
Примечания Remarks
Параметры командной строки FTP чувствительны к регистру. The ftp command-line parameters are case-sensitive.
Эта команда доступна, только если протокол Internet Protocol (TCP/IP) установлен в качестве компонента в свойствах сетевого адаптера в окне Сетевые подключения. This command is available only if the Internet Protocol (TCP/IP) protocol is installed as a component in the properties of a network adapter in Network Connections.
Команду FTP можно использовать в интерактивном режиме. The ftp command can be used interactively. После запуска FTP создает подсреду, в которой можно использовать команды FTP . After it is started, ftp creates a sub-environment in which you can use ftp commands. Вы можете вернуться в командную строку, введя команду Quit . You can return to the command prompt by typing the quit command. При запуске вспомогательной среды FTP она указывается в ftp > командной строке. When the ftp sub-environment is running, it is indicated by the ftp > command prompt. Дополнительные сведения см. в разделе команды FTP . For more information, see the ftp commands.
При установке протокола IPv6 команда FTP поддерживает использование IPv6. The ftp command supports the use of IPv6 when the IPv6 protocol is installed.
Slow SMB files transfer speed
This article provides suggested troubleshooting procedures for slow file transfer speeds through SMB.
Large file transfer is slow
If you observe slow transfers of large files, consider the following steps:
Try the file copy command for unbuffered IO (xcopy /J or robocopy /J).
Test the storage speed. This is because file copy speeds are limited by storage speed.
File copies sometimes start fast and then slow down. Follow these guidelines to verify this situation:
This usually occurs when the initial copy is cached or buffered (either in memory or in the RAID controller’s memory cache) and the cache runs out. This forces data to be written directly to disk (write-through). This is a slower process.
Use storage performance monitor counters to determine whether storage performance degrades over time. For more information, see Performance tuning for SMB file servers.
Use RAMMap (SysInternals) to determine whether «Mapped File» usage in memory stops growing because of free memory exhaustion.
Look for packet loss in the trace. This can cause throttling by the TCP congestion provider.
For SMBv3 and later versions, make sure that SMB Multichannel is enabled and working.
On the SMB client, enable large MTU in SMB, and disable bandwidth throttling. To do this, run the following command:
Small file transfer is slow
Slow transfer of small files through SMB occurs most commonly if there are many files. This is an expected behavior.
During file transfer, file creation causes both high protocol overhead and high file system overhead. For large file transfers, these costs occur only one time. When a large number of small files are transferred, the cost is repetitive and causes slow transfers.
The following are technical details about this problem:
SMB calls a create command to request that the file be created. Some code will check whether the file exists, and then create the file. Or some variation of the create command creates the actual file.
Each create command generates activity on the file system.
After the data is written, the file is closed.
All some time, the process suffers from network latency and SMB server latency. This is because the SMB request is first translated to a file system command and then to the actual file system latency to complete the operation.
If any antivirus program is running, the transfer slows down even more. This is because the data is typically scanned one time by the packet sniffer and a second time when it is written to disk. In some scenarios, these actions are repeated thousands of time. You potentially observe speeds of less than 1 MB/s.
Opening Office documents is slow
This problem generally occurs on a WAN connection. This is common and typically is caused by the manner in which Office apps (Microsoft Excel, in particular) access and read data.
We recommend that you make sure that the Office and SMB binaries are up-to-date, and then test by having leasing disabled on the SMB server. To do this, follow these steps:
Run the following PowerShell command in Windows 8 and Windows Server 2012 or later versions of Windows:
Or, run the following command in an elevated Command Prompt window:
After you set this registry key, SMB2 leases are no longer granted, but oplocks are still available. This setting is used primarily for troubleshooting.
Restart the file server or restart the Server service. To restart the service, run the following commands:
To avoid this issue, you can also replicate the file to a local file server. For more information, see aving Office documents to a network server is slow when using EFS.