Настройка sftp сервера на windows server 2019

Организация сервера для защищенной передачи файлов по протоколу SSH на Windows Server 2012 R2

С помощью встроенного пакета 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).

установка сервере openssh в windows

Чтобы проверить, установлен ли пакет:

Get-WindowsCapability -Online | ? Name -like 'OpenSSH*'

Исполняемые файлы OpenSSH находятся в каталоге:

C:windowssystem32OpenSSH

Конфигурационный файл sshd_config находится в каталоге C:ProgramDatassh (каталог создается после первого запуска службы).

Лог — c:windowssystem32OpenSSHlogssshd.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 Мб).

  1. Распакуйте содержимое архива в целевой каталог, к примеру:
    C:OpenSSH-Win
  2. Запустите командную строку PowerShell с правами администратора и перейдите в каталог OpenSSH:
    cd C:OpenSSH-Win
  3. Добавьте путь к каталогу OpenSSH в переменную окружения Path;добавить путь к openssh в переменную окружения path
  4. Установите сервер OpenSSH:
    .install-sshd.ps1
    должно появиться зеленое сообщение “sshd and ssh-agent services successfully installed”).powershell скрипт установки openssh install-sshd.ps1

Настройка 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
Правило файервола для SSHD порт 22Откройте в любом текстовом редакторе конфигурационный файл «C:ProgramDataSSHsshd_config», найдите и проверьте значение директивы Subsystem sftp. Здесь должен быть указан файл sftp-server.exe.

sshd_config файл конфигурации sftp_server

Рассмотрим полезные директивы в конфигурационном файле sshd_config:
# разрешить подключение к OpenSSH только для пользователей из этой группы

AllowGroups corpadmingroup
# включить аутентификацию по паролю (нельзя использовать ключи SSH)
AuthenticationMethods password
ForceCommand internal-sftp
#каталог для SFTP пользователей (по умолчанию пользователь подключается в каталог со своим профилем в папке C:usersusername)
ChrootDirectory C:SFTPRoot

#Для каждого пользователя можно индивидуальную chrootdirectory:

Match User user1
ChrootDirectory c:SFTPRootuser1
ForceCommand internal-sftp
X11Forwarding no
 AllowTcpForwarding no
Match User user2
ChrootDirectory c:SFTPRootuser2
ForceCommand internal-sftp
X11Forwarding no
AllowTcpForwarding no

Подключение к SFTP серверу с помощью PowerShell и WinSCP

Теперь вы может подключиться к вашему SSH серверу на Windows по протоколу SFTP. Ниже мы покажем, как подключиться к SFTP серверу с помощью бесплатного клиента клиент WinSCP, консоли PowerShell и встроенной утилиты sftp.exe.

В окне настройки подключения выберите протокол передачи файлов SFTP, укажите имя сервера и данные учетной записи Windows (в формате
[email protected]
для доменных пользователей), под которой осуществляется подключение (возможно также настроить авторизацию по ключам). При первом подключении появится окно с предупреждением о том, что ключ хоста отсутствует в локальном кеше.

winscp настройки sftp подключенияПри первом подключении появится окно с предупреждением о том, что ключ хоста отсутствует в локальном кеше.

key-warningЕсли все настроено правильно, клиент должен подключиться к SFTP серверу и отобразить список файлов в домашнем каталоге пользователя (по умолчанию каталог с профилем пользователя).

С помощью привычного интерфейса файлового менеджера можно безопасно копировать файлы между сервером и клиентом по защищённому протоколу SFTP.

sftp подключение в winscp

Для подключения к SFTP серверу из PowerShell можно использовать модуль Posh-SSH. Вы можете скачать установить модуль из PowerShell Gallery или офлайн:

Install-Module -Name Posh-SSH

установка модуля powershell 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

powershell вывести список файлов на sftp сервере

Чтобы скачать файл с удаленного SFTP сервера:
Get-SFTPItem -SessionId $SFTPSession.SessionId -Path "desktop/OpenVPNScript.log" -Destination c:temp

Чтобы закачать файл с вашего компьютера на удаленный SFTP хост:

Set-SFTPItem -SessionId $SFTPSession.SessionId -Path C:Tempmytestfile.log -Destination “desktop”

скачать файл с sftp с помощью powershell

Завершить 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.exe в Windows

Настройка SFTP аутентификации по ключам

Вы можете настроить SFTP аутентификацию по ключам. В этом случае при подключении к SFTP серверу вам не нужно будет указывать пароль пользователя.

Подробно настройка SSH аутентификации по ключам описана в этой статье.

Для этого нужно:

  1. Создать на вашем компьютере (SFTP клиент) ключи для пользователя, под которым вы будете подключаться к серверу:
    ssh-keygen -t ed25519
    генерация пары ssh ключей для sftp в windows
  2. Утилита сгенерирует два файла
    id_ed25519
    (закрытый ключ для клиента) и
    id_ed25519.pub
    (открытый ключ для сервера);
  3. Теперь нужно добавить ваш SSH ключ на сервер. Скопируйте файл id_ed25519.pub(или id_rsa.pub в зависимости от типа ключа) в каталог .ssh профиля пользователя, под которым вы будете подключаться к SFTP серверу. Переименуйте файл в authorized_keys (например для пользователя alex путь будет выглядеть так:
    C:Usersalex.sshauthorized_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:Usersalex.sshid_ed25519" -Verbose

Windows Server 2019 and Windows 10 (build 1809) have support for OpenSSH out-of-the-box, so there is no need to use any third-party library to run an SSH server or SFTP. In this post, I will demonstrate how to configure an SFTP server in Windows and use it to transfer files.

Contents

  1. FTPS vs. SFTP
  2. Install and configure the SFTP server.
  3. Custom SSH port [optional]
  4. Allow or deny connections
  5. Connect to OpenSSH server using SFTP
  6. Change the default SFTP directory
  7. Troubleshooting SFTP connections
  • Author
  • Recent Posts

Surender Kumar has more than twelve years of experience in server and network administration. His fields of interest are Windows Servers, Active Directory, PowerShell, web servers, networking, Linux, virtualization, and penetration testing. He loves writing for his blog.

Latest posts by Surender Kumar (see all)

  • Extending LVM space in Ubuntu — Thu, Feb 2 2023
  • Backup in Proxmox VE — Thu, Jan 26 2023
  • Snapshots in Proxmox VE — Wed, Jan 25 2023

FTPS vs. SFTP

The File Transfer Protocol (FTP) is no longer considered safe for use as it lacks the ability to encrypt data while it is in transit. If you still use FTP over a traditional FTP port number (TCP 21), all your data and commands are transmitted in clear text. Anyone can intercept this server–client communication, which is a big security concern as per modern IT standards. Two alternatives to FTP exist:

  • FTPS (FTP over SSL/TLS)—This method is just like the traditional FTP with the added support of a TLS certificate to offer encryption.
  • SFTP (FTP over SSH)—This method uses SSH for transferring files, which encrypts the communication by default.

Although both can serve the purpose of transferring files, they are totally different by design. FTPS is not very firewall friendly and is difficult to configure. Thus, I will focus on SFTP in this post.

I am using two VMs in a lab environment for this demo:

  1. Windows Server 2022—This will work as an OpenSSH server.
  2. Windows 10—This will work as a client.

I have also installed the FileZilla FTP client in a Windows 10 VM, which will connect to the OpenSSH server using the SFTP protocol. Of course, you can use WinSCP or any other FTP client that supports the SFTP protocol.

Install and configure the SFTP server.

First, log in to Windows Server VM and enable the optional OpenSSH feature. To do so, launch an elevated PowerShell console, and run the following command:

Add-WindowsCapability -Online -Name OpenSSH.Server~~~~0.0.1.0

Installing an OpenSSH server in Windows using PowerShell

Installing an OpenSSH server in Windows using PowerShell

The installation was successful if the output includes Online : True. The command will automatically configure the required firewall rule, so there is nothing you need to do manually.

Now use the following command to change the startup mode of the OpenSSH server service (sshd) to automatic and start it at the same time:

Get-Service -Name "sshd" | Set-Service -Startup "Automatic" -PassThru | Start-Service -PassThru 

Change the service start mode and start the service using PowerShell

Change the service start mode and start the service using PowerShell

You can see that the service is now running. The main configuration file of the OpenSSH server on Windows is %ProgramData%sshsshd_config, but Windows can also read the configuration from the user profile (%UserProfile%.sshconfig) if available. Furthermore, it allows you to specify a custom configuration file using the -f switch (e.g., sshd.exe -f «c:usersadministrator.sshcustom_config»).

Custom SSH port [optional]

By default, the OpenSSH server listens on TCP Port 22. But you can change the port to something else by running the following PS command:

(Get-Content "C:ProgramDatasshsshd_config").replace("#Port 22", "Port 2223") | Set-Content "C:ProgramDatasshsshd_config"
Restart-Service "sshd"

Changing the OpenSSH server port on Windows using PowerShell

Changing the OpenSSH server port on Windows using PowerShell

The first command replaces the port number with the one you specify in the system-wide configuration file (%ProgramData%sshsshd_config), and the second command restarts the service. The following command can be used to make sure the server is now listening on a new port number:

Get-NetTCPConnection -LocalPort 2223 | select Local*, State,`
@{n="ProcessName";e={(Get-Process -Id $_.OwningProcess).ProcessName}},`
@{n="ProcessPath";e={(Get-Process -Id $_.OwningProcess).Path}} | ft -Auto

Verify the custom port of the OpenSSH server using PowerShell

Verify the custom port of the OpenSSH server using PowerShell

You can see that the OpenSSH server is now listening on Port 2223.

Allow or deny connections

The OpenSSH server in Windows also lets you control which users or groups are allowed to connect to the server (or denied a connection) using SFTP (and SSH). To do so, you can add the following directives to the configuration file:

  • DenyUsers
  • AllowUsers
  • DenyGroups
  • AllowGroups

Note that these directives are processed in the same order as written. By default, the OpenSSH server will allow every local or domain user to connect, but if you want to allow (or deny) a particular user or group, specify that in the configuration file, as shown in this line of code:

AllowGroups testlabdevelopers testlabssh_admins

Remember, these allow or deny directives must come before the Match Group administrators directive, as pointed out in the screenshot; otherwise, it won’t work as expected.

Using the SSH configuration file to allow or deny users and groups

Using the SSH configuration file to allow or deny users and groups

Adding the above line inside the SSH configuration file will allow the members of the developers and ssh_admins groups in the TestLab domain to connect, while denying everyone else. It is recommended to specify the account names in lowercase only. Furthermore, to specify a domain account in UPN format, you must replace the @ character with ? to avoid any conflicts with regular Linux patterns. For example, to specify user@domain.com with an allow or deny directive, you must type it as user?domain*.

Connect to OpenSSH server using SFTP

The OpenSSH server is now set to accept connections from the client. Head over to your Windows 10 machine, launch FileZilla, and make a connection to the server with the settings shown in the screenshot.

Connecting to the SFTP server using the FileZilla FTP client

Connecting to the SFTP server using the FileZilla FTP client

Make sure the protocol SFTP – SSH File Transfer Protocol and the correct SSH server port are specified. When you connect for the first time, you will see an Unknown host key warning. Click OK to trust the host and continue connecting.

The servers host key is unknown. You have no guarantee that the server is the computer you think it is.

The servers host key is unknown. You have no guarantee that the server is the computer you think it is.

You will now be connected to the server using the SFTP protocol, and you can start transferring files.

Using FileZilla client with the SFTP protocol to transfer files

Using FileZilla client with the SFTP protocol to transfer files

Change the default SFTP directory

By default, you will land in your user profile directory when you connect to the server. However, you can specify a custom directory in the sshd_config file to change the default root directory for SFTP. To do so, open the C:ProgramDatasshsshd_config file on the server in any text editor, and add the following line:

ChrootDirectory "C:inetpubwwwroot"

See the following screenshot for reference:

Change the default SFTP root directory in Windows

Change the default SFTP root directory in Windows

Restart the sshd service after making this change, and reconnect the server. You will now land in the specified directory (C:inetpubwwwroot). This is particularly useful on web servers, where you want users to land directly inside the website’s root directory instead of their home directory.

FileZilla FTP client connecting to a predefined root directory in Windows

FileZilla FTP client connecting to a predefined root directory in Windows

There are many other settings supported by the OpenSSH server, but covering everything is beyond the scope of this article.

Troubleshooting SFTP connections

If you run into any issues while working with OpenSSH server, you can always view the event logs under Applications and Services Logs OpenSSH, as shown in the following screenshot:

Viewing event logs related to OpenSSH in Windows

Viewing event logs related to OpenSSH in Windows

The OpenSSH server also supports file-based logging, so if you’re interested in that, add the following lines to the SSH configuration file and restart the sshd service.

SyslogFacility LOCAL0
LogLevel Debug3

Enabling file based debug logging using the OpenSSH configuration file

Enabling file based debug logging using the OpenSSH configuration file

Once you do this, you will be able to view the debug logs in the %ProgramData%sshlogs directory. As you can see in the following screenshot, the debug log showed that the user testjohn wasn’t able to connect to the server because they are not a member of any group specified in the AllowGroups directive.

Subscribe to 4sysops newsletter!

Viewing OpenSSH debug logs to troubleshoot problems

Viewing OpenSSH debug logs to troubleshoot problems

The procedure described here also allows you to connect to a Windows system using the SSH shell, which means that users who can connect using SFTP can also connect using any SSH client (like putty) and run commands. This is why it is very important to allow only a limited number of groups containing trusted people. I hope this guide helped you get started with SFTP as a safer alternative to an FTP server on Windows.

avatar

Introduction

In this tutorial, we will show you how to set up a SFTP server in Windows. If you have a cloud computer with V2 Cloud and you’re looking to setup a secure FTP server in your cloud computer instead, follow this link. The main difference between FTP and SFTP is the security aspect. Running applications that use SFTP for file transfers is the answer to protecting that data in transit.

This tutorial will provide the steps required to set up an SFTP Server using Windows Server 2019’s OpenSSH Server feature. Our SFTP client computer will be a Windows 10 computer, and we will be using Filezilla as the client application to connect to the server.

You can browse the different sections of this tutorial. This is what you need to setup a SFTP server in Windows:

  1. Configure the SFTP server feature (OpenSSH Server) in Windows Server 2019
  2. Create the root SFTP directory
  3. Create the user account that will be used for file transfers
  4. Install and configure the SFTP client for data transfers
  5. Perform an SFTP transfer between client and server

Note: the terms “directory” and “file folder” refer to the same object. They are used interoperably in this tutorial.

Section 1: Configure the SFTP server feature (OpenSSH Server) in Windows Server 2019

STEP 1

Login to your server. Then type apps and features in the search bar. Under Apps and Features (the section in the middle of the page), click Manage optional features.

mstsc /admin-command

STEP 2

Scroll among the options, find OpenSSH Server, click it, then click Install.

mstsc /admin-command

The installation will now begin in the background. We are going to make some changes to the Windows Services to allow for the newly installed OpenSSH server to be started automatically.

STEP 3

Type services in the search bar. Then click the Services Desktop app. Locate the OpenSSH SSH Server option from the list. Right-click it, then select Properties.

mstsc /admin-command

STEP 4

Change the Startup type to Automatic. Click Start afterward.

mstsc /admin-command

STEP 5

Once the service has started the Service status: will change from Stopped to Running. Click OK to proceed.

mstsc /admin-command

STEP 6

Locate the OpenSSH Authentication Agent service. Right-click it, then select Properties.

mstsc /admin-command

STEP 7

Repeat Steps 3 to 5 where you will make the same changes as you did with the OpenSSH SSH Server with this service (OpenSSH Authentication Agent).

When done, you’ll notice the status of the two services is now set to Running.

mstsc /admin-command

STEP 8

Browse to the following folder, C:\ProgramData\ssh in the address bar. You may have to type the location as the ProgramData folder is normally hidden by default. Click the “drop-down arrow” beside Text documents then select All Files. Select sshd_config from the files list, then click Open.

mstsc /admin-command

mstsc /admin-command

STEP 9

When the sshd_config file opens, click Ctrl+F on your keyboard to launch the Find app. Type “root”, then click Find Next. We are looking for the entry #ChrootDirectory.

mstsc /admin-command

STEP 10

Edit the entry to this ChrootDirectory C:\SFTPRoot. This is the location where our SFTP files will be stored from the server side. Click File then click Save.

mstsc /admin-command

Let’s now create the actual folder/root directory we just referenced as our location to save SFTP files.

Section 2: Create the root SFTP directory

STEP 11

Browse to the C:\ drive on your server. Right-click in any empty space then select New from the drop-down menu then click Folder. Name the folder SFTPRoot. Ensure that it is exactly the same as the folder name referenced in the path in Step 10.

mstsc /admin-command

mstsc /admin-command

Now let us add the user account on this server that will be used to do the SFTP transfers.

Section 3: Create the user account that will be used for file transfers

STEP 11

Open the Server Manager, then select Tools and click Computer Management.

mstsc /admin-command

STEP 12

Click the drop-down arrow beside Local Users and Groups. Click the Users folder. In the middle pane, right-click on any white space and select New User from the drop-down menu.

mstsc /admin-command

STEP 13

Create the user account by entering your username and password. Record these credentials as we will be using them for our SFTP transfers. Uncheck the option User must change password at next logon and check the options User cannot change password and Password never expires. Click Create once finished.

mstsc /admin-command

Now let us find and record the IP address of our SFTP server. This will be needed along with the username and password we just created for our SFTP connection.

STEP 14

Type cmd at the search bar. Select Command Prompt. Type ipconfig at the prompt then hit the Enter key on your keyboard.

mstsc /admin-command

The Ip address of our server is 192.168.50.4.

Our server-side configuration is now complete. We now need to configure our client computer to connect to this newly configured SFTP server and transfer data to it.

Section 4: Install and configure the SFTP client for data transfers

In this example, we will be using Filezilla as our SFTP client. To continue, download the Filezilla client application and install it on your computer. Let’s now create our SFTP site.

STEP 15

Launch the Filezilla app. Click the File option from the menu bar then click Site Manager.

mstsc /admin-command

STEP 16

Select the My Sites folder under the left section under Select entry: Then click the New site button.

mstsc /admin-command

STEP 17

Name the site, we’ll call it SFTP-Site1. On the General tab in the left section of the Site Manager window, configure the following; Protocol: SFTP – SSH File Transfer Protocol, Host:

192.168.50.4, Port: 22, Logon Type: Normal, User: the User/username that will be used to connect to the SFTP site/server, Password: password for the user. When done click Connect.

mstsc /admin-command

STEP 18

Save the password and click OK. Click OK at the Unknown host key pop-up box. Note, you can check the checkbox Always trust the host, add this key to the cache.

mstsc /admin-command

Once connected successfully the following will be what you’ll see.

mstsc /admin-command

We’ll now proceed to create and configure the remote SFTP directory.

STEP 19

Right-click in any white space in the bottom-right-hand quadrant of the Filezilla GUI window. Then select Create Directory. This will create a file folder in the root SFTP folder on the SFTP server.

mstsc /admin-command

STEP 20

Create a name for the new directory, then click OK.

mstsc /admin-command

You’ll now see that our newly created directory has been created successfully on our client computer.

mstsc /admin-command

If we browse to the SFTPRoot folder on the SFTP server, we’ll see that our directory has been automatically created.

mstsc /admin-command

Now that our two sites have been configured. Let’s move on to the final step to perform a secure file transfer.

STEP 21

Select the “source file folder”, from the top left-hand file folder listing with the label Local site: that has the file/files that you want to transfer to your server. Our folder is C:UsersKurwinDownloads. On the Remote site: select your destination file folder. Locate your file under the bottom-left hand file listings then right-click it and select Upload.

mstsc /admin-command

You’ll now see that your file has been transferred successfully.

mstsc /admin-command

SFTP server verifies our successful transfer. We see our file in our target directory within our root directory.

mstsc /admin-command

That’s it. We have now successfully set up a SFTP server in a Windows environment.

There is a better way to do IT with V2 Cloud

By using V2 Cloud, you get access to a fully-integrated virtual desktop solution, without the traditional complexity of other cloud providers.
There is an easier way to enable secure remote access to employees without sacrificing end-user experience and performance.

V2 Cloud offers a cloud desktop infrastructure with

  • No hidden fees
  • No complicated setup
  • No contracts
  • Flat-rate pricing model

We’re the #1 virtualization solution for small businesses. Create virtual desktops, servers, and applications to improve productivity and significantly reduce your IT costs.

Learn more about V2 Cloud and our cloud VDI solution. Get started with a risk-free 7-day trial, and experience the simplicity, scalability and power of V2 Cloud.

В этой статье мы покажем, как использовать Win32-OpenSSH для запуска SFTP-сервера в Windows 10 или Windows Server 2016 / 2012R2.

Что такое SFTP?

SFTP ( Secure File Transfer Protocol , Secure FTP или SSH FTP ) является расширением протокола SSH, являющегося стандартом в мире систем UNIX / Linux. С точки зрения пользователя, он похож на FTP, но на самом деле это совершенно другой протокол, не имеющий ничего общего с FTP . Данные передаются между клиентом и сервером через туннель SSH (TCP-порт 22).

Основные преимущества SFTP:

  1. Файлы и команды передаются в безопасном сеансе SSH;
  2. Одно соединение используется для отправки файлов и команд;
  3. Поддерживаются символические ссылки, передача прерываний / возобновлений, функции удаления файлов и т. Д .;
  4. Как правило, в каналах, где FTP работает медленно или не работает, SFTP-соединение работает быстрее и надежнее;
  5. Возможность аутентификации с использованием ключей SSH.

Не путайте протоколы SFTP и FTPS. По сути, FTPS — это простой FTP с сертификатом SSL, а SFTP — это протокол для отправки данных и команд FTP внутри сеанса SSH.

Реализация SFTP в Windows

Исторически операционные системы Windows не предоставляют никаких встроенных инструментов для запуска защищенного SFTP-сервера. Для этих целей использовались открытые или проприетарные решения, такие как Core FTP, FileZilla, CYGWIN, OpenSSH, FTP Shell, IPSwitch и т. Д. Однако несколько лет назад Microsoft выпустила свою версию порта OpenSSH для Win32. Этот проект называется Win32-OpenSSH .

Рассмотрим конфигурацию SFTP-сервера под управлением Windows 10 или Windows Server 2019/2016/2012 R2 с использованием пакета Win32 OpenSSH .

Установка Win32 OpenSSH на Windows 10 1803+ / Windows Server 2019

В Windows 10 build 1803 и новее, а также в Windows Server 2019 пакет OpenSSH уже включен в операционную систему в форме Feature on Demand (FoD), такой как RSAT .

Вы можете установить сервер OpenSSH в Windows 10 и Windows Server 2019, используя следующий командлет PowerShell:

Add-WindowsCapability -Online -Name OpenSSH.Server*

Или используя DISM:
dism /Online /Add-Capability /CapabilityName:OpenSSH.Server~~~~0.0.1.0

Также вы можете добавить OpenSSH сервер из Windows 10 GUI ( Настройки -> Приложения -> Дополнительные функции -> Добавить функцию -> Открыть SSH Server -> Установить ).

1-install-opensshserver-feature-on-windows-10 Установка SFTP (SSH FTP) сервера в Windows с помощью OpenSSH

  • Исполняемые файлы OpenSSH находятся в каталоге c:windowssystem32OpenSSH:;
  • Sshd_config файл конфигурации находится в каталоге: C:ProgramDatassh(этот каталог создается после первого запуска службы Sshd);
  • Лог — файл: c:windowssystem32OpenSSHlogssshd.log;
  • Файл и ключи authorized_keys хранятся в директории: %USERPROFILE%.ssh.

Установите Win32 OpenSSH на Windows Server 2016/2012 R2

В предыдущих версиях Windows 10 и Windows Server 2016/2012 R2 необходимо загрузить и установить OpenSSH с GitHub. Вам необходимо скачать версию пакета для Windows x64: OpenSSH-Win64.zip (3,5 МБ).

  • Распакуйте архив в целевой каталог: C: OpenSSH-Win;
  • Запустите привилегированный клиент PowerShell и перейдите в папку OpenSSH: Cd C:OpenSSH-Win
  • Добавьте путь к каталогу OpenSSH в переменную среды Path (Свойства системы -> вкладка «Дополнительно» -> Переменные среды -> Выберите и измените системную переменную Path -> Добавить путь к папке OpenSSH);

2-openssh-folder-in-path-system-variable Установка SFTP (SSH FTP) сервера в Windows с помощью OpenSSH

  • Установите сервер OpenSSH: .install-sshd.ps1(должно появиться зеленое сообщение « Службы sshd и ssh-agent успешно установлены »);

3-install-sshd-powershell-script-in-openssh Установка SFTP (SSH FTP) сервера в Windows с помощью OpenSSH

  • Сгенерируйте ключи SSH для сервера (необходим для запуска службы sshd):
    ssh-keygen.exe –Assh-keygen: generating new host keys: RSA DSA ECDSA ED25519

4-generate-ssh-key-ssh-keygen.exe_ Установка SFTP (SSH FTP) сервера в Windows с помощью OpenSSH

  • Включите автозапуск для службы SSHD и запустите его, используя следующие команды управления службой PowerShell:
    Set-Service -Name sshd -StartupType ‘Automatic’
    Start-Service sshd
  • Перезагрузите компьютер:
    Restart-Computer
  • Используйте PowerShell, чтобы открыть TCP-порт 22 в брандмауэре Windows для входящего трафика SSH: New-NetFirewallRule -Protocol TCP -LocalPort 22 -Direction Inbound -Action Allow -DisplayName SSH

5-new-netfirewallrule-port-22-600x208-1 Установка SFTP (SSH FTP) сервера в Windows с помощью OpenSSH

Примечание . Предыдущая команда не будет работать в старых версиях Windows для настольных компьютеров. В этом случае используется другая команда: netsh advfirewall firewall add rule name='SSH Port' dir=in action=allow protocol=TCP localport=22

  • Откройте файл конфигурации SSHD (C: ProgramData SSH sshd_config) в любом текстовом редакторе. Найдите и проверьте значение директивы Subsystem sftp . SFTP-server.exe файл должен быть указан здесь.

6-openssh-sshd-config-file Установка SFTP (SSH FTP) сервера в Windows с помощью OpenSSH

Вы можете дополнительно настроить следующие параметры в файле конфигурации sshd_config:

AllowGroups corpsftp_users # разрешить подключение к OpenSSH только пользователям этой доменной группы

AuthenticationMethods password # включить аутентификацию по паролю (ключи SSH не могут быть использованы)
ForceCommand internal-sftp
ChrootDirectory C:inetpubwwwrootftpfolder #каталог по умолчанию для пользователей SFTP

Тестирование SFTP-соединения с использованием WinSCP

Попробуем подключиться к созданному SSH-серверу по протоколу SFTP. Для этого используйте бесплатный клиент WinSCP .

В окне конфигурации подключения выберите SFTP в качестве протокола передачи файлов, укажите имя сервера и учетные данные учетной записи Windows, которая используется для подключения (также можно настроить проверку подлинности ключа).

7-winscp-test-sftp-server-600x402-1 Установка SFTP (SSH FTP) сервера в Windows с помощью OpenSSH

При первой попытке подключения появляется следующее уведомление о ключе хоста, не найденном в локальном кэше.

8-rsa2-key-warning Установка SFTP (SSH FTP) сервера в Windows с помощью OpenSSH

Если все настроено правильно, клиент подключится к SFTP-серверу и отобразит список файлов в домашнем каталоге пользователя (по умолчанию это каталог с профилем пользователя).

Используя знакомый интерфейс файлового менеджера ( например, Total Commander ), вы можете копировать файлы между сервером и клиентом. Файлы передаются с использованием безопасного SFTP.

9-connect-openssh-on-windows-using-winscp-1024x695-1 Установка SFTP (SSH FTP) сервера в Windows с помощью OpenSSH

Как удалить Win32 OpenSSH?

Чтобы правильно удалить Win32 OpenSSH из вашей системы:

  1. Запустите сеанс PowerShell с повышенными правами;
  2. Остановите службу SSHD:
    Stop-Service sshd
  3. Удалите службу sshd: .uninstall-sshlsa.ps1

    <span>sshd успешно удален</span><span>

    sshagent успешно удален</span>

— Advertisement —

Hello, how are you? Windows Server users want the ability to install servers with secure protocols. This in order to be able to exchange data and keep it safe from possible intrusions. As a matter of fact, Here at googez.com, we show you how to install an FTP server on Windows Server 2019. But this server is criticized for its lack of security, as the communication is not encrypted. On the other hand, Secure File Transfer Protocol (SFTP) is a secure version of File Transfer Protocol (FTP), which facilitates data access and data transfer over a Secure Shell (SSH) data stream. In other words, it allows you to upload or download files with a server. However, SFTP is considered secure. It protects file transfers through data-in-motion encryption and secure authentication methods. For that reason, in this post, we will see how to install an SFTP/SSH server on Windows Server 2019.

Prerequisites. Installing OpenSSH server.

To achieve better stability on our server, it is imperative to assign a static IP address. If you do not know how to do it, please look here. Furthermore, we are going to install the OpenSSH server, which will allow us to configure access to the SFTP server. Thereupon, it is necessary to enter the settings menu. And once there, select Apps.

Windows Settings>Apps

Windows Settings>Apps

Next, the menu corresponding to Apps and features will be displayed. In this window, click on manage optional features.

On apps and features menu, you need to select manage optional features

On apps and features menu, you need to select manage optional features

In the following window, please scroll down through the different options until you find OpenSSH Server. Check if the service is already installed, if it is not, click on Add a feature

Entering on Add a feature in order to install OpenSSH Server

Entering on Add a feature in order to install OpenSSH Server

A list of functions will appear, please navigate until you find OpenSSH Server and select it. Wait until the installation is completed.

Installing OpenSSH Server.

Installing OpenSSH Server.

Configuring the Ssh server to start at Windows startup.

All right, we have already installed both the agent and the OpenSSH server. Now, let is configure the services to be activated every time Windows starts. In order to do that, please press Windows +R, and type services.msc.

Running services

Running services

The service window will then open. Locate OpenSSH Authentication Agent and OpenSSH Server

Locating both OpenSSH services

Locating both OpenSSH services

In the column to the right of the service description, you can see the startup type. In my case, the authentication agent is disabled and the OpenSSH server is manual. What we are going to do is to automatically set the startup. With this in mind, do right-click over the service to enter properties.

Righ-click over the OpnSSH server and select properties

Righ-click over the OpnSSH server and select properties

In the next window, we have to select automatic in startup type and then click on apply. Finally, press Start to begin the service.

Setting automatic on startup type

Setting automatic on startup type

Please do the same procedure with the OpenSSH Authentication Agent.

Check server and client status.

After installing the services and setting up the autostart, we need to check their status. For that, we’ll open a PowerShell with administrator privileges and write the following:

 Get-Service -Name *ssh* 

A powershell showing OpenSSH server is running

A powershell showing OpenSSH server is running

If we have done everything right, we should see this message.

Connect to an SFTP server installed on Windows Server 2019, through OpenSSH.

We can connect to the SFTP server using a client like WinSCP, FTP Rush, in my case I will use FileZilla. Just go to the download page and select download client.

Downloading FileZilla, am SFTP client

Downloading FileZilla, an SFTP client

Run the file, and start the program. In the main window of the program, there are some boxes that we must fill with the credentials of the serve. In host type, the server name, in username adds the name of the user, type the password in the next box and finally type 22 on the Port box. Please note that at the time of installing the OpenSSH server, a firewall rule is automatically created. This rule opens port 22 to allow network access. For that reason, we have to set that number.

Filezilla client running

Filezilla client running

Finally, we have installed and configured the access to an SFTP server in Windows Server 2019. As can be seen, the procedure has been simplified since Microsoft included OpenSSH server in Windows 10 and later versions as Server 2019. Please visit our post about the expiration of accounts in Windows 10. And if you want to keep up with the latest technology, subscribe to our Telegram channel.

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.

Contents:

  • How to Install OpenSSH on Windows?
  • How to Configure SFTP Server on Windows Using OpenSSH?
  • Connecting to SFTP Server Using WinSCP or PowerShell
  • Configuring SFTP Public Key Authentication

SFTP (Secure File Transfer Protocol, Secure FTP, or SSH FTP) is the extension of SSH protocol, which is the standard in the world of UNIX/Linux systems. From the user’s point of view, it is similar to FTP, but in fact, it is a completely different protocol, having nothing in common with FTP. Data between the client and the server is transmitted on port 22 through an SSH tunnel (TCP port 22).

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.

Do not confuse SFTP and FTPS protocols. FTPS is essentially just a simple FTP with an SSL certificate, and SFTP is the protocol to transfer the FTP data and commands inside the SSH session.

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).

On these versions of Windows, you can install the OpenSSH server using PowerShell:

Add-WindowsCapability -Online -Name OpenSSH.Server*

Or using DISM:
dism /Online /Add-Capability /CapabilityName:OpenSSH.Server~~~~0.0.1.0

Also, you can install OpenSSH server from Windows 10 GUI (Settings -> Apps -> Optional Features -> Add a feature -> Open SSH Server -> Install).

install openssh server on windows 10

To check if a package is installed:

Get-WindowsCapability -Online | ? Name -like 'OpenSSH*'

  • OpenSSH executables are located in the directory: c:windowssystem32OpenSSH;
  • The sshd_config configuration file is located in  C:ProgramDatassh (this directory is created after the first start of the sshd service);
  • Log file: c:windowssystem32OpenSSHlogssshd.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).

  1. Extract the archive to the target folder: C:OpenSSH-Win;
  2. Open an elevated PowerShell prompt and switch to the OpenSSH folder: Cd C:OpenSSH-Win
  3. 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); add openssh folder to the system variable path
  4. Install the OpenSSH server: .install-sshd.ps1 (a green message should appear “sshd and ssh-agent services successfully installed”);

    If running PowerShell scripts on your computer is blocked by your PowerShell Execution Policy, you can run the script with this command: powershell.exe -ExecutionPolicy Bypass -File install-sshd.ps1

    install openssh (sshd service) with powershell script

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 SSHNew-NetFirewallRule - add incoming rule port 22

Note. The previous command won’t work in old desktop Windows versions. In this case, another command is used: netsh advfirewall firewall add rule name='SSH Port' dir=in action=allow protocol=TCP localport=22

Open the SSHD configuration file (C:ProgramDataSSHsshd_config) in any text editor.  Find and check the value of the Subsystem sftp directive. The sftp-server.exe file should be specified here.openssh sshd_config file in windows

You can additionally configure the following parameters in the sshd_config configuration file:

# only allow users in this domain group to connect to OpenSSH
AllowGroups corpsftp_users
# enable password authentication (SSH keys cannot be used)
AuthenticationMethods password
#default (chrooot) directory for SFTP users  (by default, the user connects to the directory with his profile in the C:usersusername folder)
ChrootDirectory C:SFTP
ForceCommand internal-sftp
#You can set an individual chrootdirectory for each user:
Match User abrown
ChrootDirectory c:SFTPabrown
ForceCommand internal-sftp
X11Forwarding no
AllowTcpForwarding no

Match User jsmith
ChrootDirectory c:SFTPjsmith
ForceCommand internal-sftp
X11Forwarding no
AllowTcpForwarding no

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).

WinSCP test sftp connection

When you try to connect for the first time, the following notification of the host key not found in the local cache appears.

rsa2 key warning

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.

connect openssh on windows server using winscp

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

install posh-ssh module in windows

To connect to the SFTP server using a password, you need to get the username and password via Get-Credential:

$usrCreds= 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

powershell: list files in sftp folder

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:PSmytestfile.log -Destination "desktop"

upload files to sftp with powershell

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.

sftp.exe tool in windows

Connect to sftp server:

sftp user1@192.168.3.20

Connect using ssh private key:

sftp -i .ssh/id_rsa user1@192.168.3.20

List files in a remote directory:

pwd

Download the file from SFTP to a local directory on your computer:

get download_this_file_from_sftp.txt

Upload a file from your computer to an SFTP server:

put file_to_uplodad.txt

Close session:

exit

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.

  1. Create SSH keys on your computer (SFTP client) for the user under which you will connect to the server: ssh-keygen -t ed25519 generate ssh keys for sftp connections
  2. 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);
  3. 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:Usersmax1.sshauthorized_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:Usersmax1.sshid_ed25519" -Verbose

Содержание

  1. Установка SFTP (SSH FTP) сервера в Windows с помощью OpenSSH
  2. Вы можете использовать официальный пакет OpenSSH для Windows, чтобы легко организовать безопасную передачу файлов между клиентом и сервером Windows, используя протокол SFTP ( Secure FTP ).
  3. Что такое SFTP?
  4. Реализация SFTP в Windows
  5. Установка Win32 OpenSSH на Windows 10 1803+ / Windows Server 2019
  6. Установите Win32 OpenSSH на Windows Server 2016/2012 R2
  7. Тестирование SFTP-соединения с использованием WinSCP
  8. Как удалить Win32 OpenSSH?
  9. Installing SFTP/SSH Server on Windows using OpenSSH
  10. Installing SFTP/SSH Server
  11. On Windows 11 and Windows 10
  12. On earlier versions of Windows
  13. Configuring SSH server
  14. Setting up SSH public key authentication
  15. Connecting to the server
  16. Finding Host Key
  17. Connecting
  18. Configuring SFTP (SSH FTP) Server on Windows
  19. How to Install OpenSSH on Windows?
  20. How to Configure SFTP Server on Windows Using OpenSSH?
  21. Connecting to SFTP Server Using WinSCP or PowerShell
  22. Configuring SFTP Public Key Authentication

Установка 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 . Данные передаются между клиентом и сервером через туннель SSH (TCP-порт 22).

Основные преимущества SFTP:

  1. Файлы и команды передаются в безопасном сеансе SSH;
  2. Одно соединение используется для отправки файлов и команд;
  3. Поддерживаются символические ссылки, передача прерываний / возобновлений, функции удаления файлов и т. Д .;
  4. Как правило, в каналах, где FTP работает медленно или не работает, SFTP-соединение работает быстрее и надежнее;
  5. Возможность аутентификации с использованием ключей SSH.

Не путайте протоколы SFTP и FTPS. По сути, FTPS — это простой FTP с сертификатом SSL, а SFTP — это протокол для отправки данных и команд FTP внутри сеанса SSH.

Реализация SFTP в Windows

Исторически операционные системы Windows не предоставляют никаких встроенных инструментов для запуска защищенного SFTP-сервера. Для этих целей использовались открытые или проприетарные решения, такие как Core FTP, FileZilla, CYGWIN, OpenSSH, FTP Shell, IPSwitch и т. Д. Однако несколько лет назад Microsoft выпустила свою версию порта OpenSSH для Win32. Этот проект называется Win32-OpenSSH .

Рассмотрим конфигурацию SFTP-сервера под управлением Windows 10 или Windows Server 2019/2016/2012 R2 с использованием пакета Win32 OpenSSH .

Установка Win32 OpenSSH на Windows 10 1803+ / Windows Server 2019

В Windows 10 build 1803 и новее, а также в Windows Server 2019 пакет OpenSSH уже включен в операционную систему в форме Feature on Demand (FoD), такой как RSAT .

Вы можете установить сервер OpenSSH в Windows 10 и Windows Server 2019, используя следующий командлет PowerShell:

Add-WindowsCapability -Online -Name OpenSSH.Server*

Или используя DISM:
dism /Online /Add-Capability /CapabilityName:OpenSSH.Server

Также вы можете добавить OpenSSH сервер из Windows 10 GUI ( Настройки -> Приложения -> Дополнительные функции -> Добавить функцию -> Открыть SSH Server -> Установить ).

  • Исполняемые файлы OpenSSH находятся в каталоге c:windowssystem32OpenSSH :;
  • Sshd_config файл конфигурации находится в каталоге: C:ProgramDatassh (этот каталог создается после первого запуска службы Sshd);
  • Лог — файл: c:windowssystem32OpenSSHlogssshd.log ;
  • Файл и ключи authorized_keys хранятся в директории: %USERPROFILE%.ssh .

Установите Win32 OpenSSH на Windows Server 2016/2012 R2

В предыдущих версиях Windows 10 и Windows Server 2016/2012 R2 необходимо загрузить и установить OpenSSH с GitHub . Вам необходимо скачать версию пакета для Windows x64: OpenSSH-Win64.zip (3,5 МБ).

  • Распакуйте архив в целевой каталог: C: OpenSSH-Win;
  • Запустите привилегированный клиент PowerShell и перейдите в папку OpenSSH: Cd C:OpenSSH-Win
  • Добавьте путь к каталогу OpenSSH в переменную среды Path (Свойства системы -> вкладка «Дополнительно» -> Переменные среды -> Выберите и измените системную переменную Path -> Добавить путь к папке OpenSSH);

  • Установите сервер OpenSSH: .install-sshd.ps1 (должно появиться зеленое сообщение « Службы sshd и ssh-agent успешно установлены »);

  • Сгенерируйте ключи SSH для сервера (необходим для запуска службы sshd):
    ssh-keygen.exe –A ssh-keygen: generating new host keys: RSA DSA ECDSA ED25519

  • Включите автозапуск для службы SSHD и запустите его, используя следующие команды управления службой PowerShell:
    Set-Service -Name sshd -StartupType ‘Automatic’
    Start-Service sshd
  • Перезагрузите компьютер:
    Restart-Computer
  • Используйте PowerShell, чтобы открыть TCP-порт 22 в брандмауэре Windows для входящего трафика SSH: New-NetFirewallRule -Protocol TCP -LocalPort 22 -Direction Inbound -Action Allow -DisplayName SSH

Примечание . Предыдущая команда не будет работать в старых версиях Windows для настольных компьютеров. В этом случае используется другая команда: netsh advfirewall firewall add rule name=’SSH Port’ dir=in action=allow protocol=TCP localport=22

  • Откройте файл конфигурации SSHD (C: ProgramData SSH sshd_config) в любом текстовом редакторе. Найдите и проверьте значение директивы Subsystem sftp . SFTP-server.exe файл должен быть указан здесь.

Вы можете дополнительно настроить следующие параметры в файле конфигурации sshd_config:

AllowGroups corpsftp_users # разрешить подключение к OpenSSH только пользователям этой доменной группы

AuthenticationMethods password # включить аутентификацию по паролю (ключи SSH не могут быть использованы)
ForceCommand internal-sftp
ChrootDirectory C:inetpubwwwrootftpfolder # каталог по умолчанию для пользователей SFTP

Тестирование SFTP-соединения с использованием WinSCP

Попробуем подключиться к созданному SSH-серверу по протоколу SFTP. Для этого используйте бесплатный клиент WinSCP .

В окне конфигурации подключения выберите SFTP в качестве протокола передачи файлов, укажите имя сервера и учетные данные учетной записи Windows, которая используется для подключения (также можно настроить проверку подлинности ключа).

При первой попытке подключения появляется следующее уведомление о ключе хоста, не найденном в локальном кэше.

Если все настроено правильно, клиент подключится к SFTP-серверу и отобразит список файлов в домашнем каталоге пользователя (по умолчанию это каталог с профилем пользователя).

Используя знакомый интерфейс файлового менеджера ( например, Total Commander ), вы можете копировать файлы между сервером и клиентом. Файлы передаются с использованием безопасного SFTP.

Как удалить Win32 OpenSSH?

Чтобы правильно удалить Win32 OpenSSH из вашей системы:

Источник

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 11 and Windows 10

  • On Windows 11:
    • Go to Settings > Apps > Optional features and click on View features.
    • Locate “OpenSSH server” feature, select it, click Next, and then click Install.
  • On Windows 10 (version 1803 and newer):
    • Go to Settings > Apps > Apps & features > Optional features and click on Add a feature.
    • Locate “OpenSSH server” feature, expand it, and select Install.

Binaries are installed to %WINDIR%System32OpenSSH . 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.

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 FilesOpenSSH
  • 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:WindowsSystem32OpenSSHsshd.exe with the actual path to the sshd.exe ( C:Program FilesOpenSSHssh.exe , had you followed the manual installation instructions above).
    • or go to Windows Security > Firewall & network protection1> 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 (or just double-click the service). In the Properties dialog, change Startup type to Automatic and confirm.
    • Start the OpenSSH SSH Server service by clicking the Start the service link or Action > Start in the menu.

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 the 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:WINDIRSystem32 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 your 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 fingerprints with those collected before (see above).

If you cannot authenticate to the server and use 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.

Источник

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:windowssystem32OpenSSH ;
  • The sshd_config configuration file is located in C:ProgramDatassh (this directory is created after the first start of the sshd service);
  • Log file: c:windowssystem32OpenSSHlogssshd.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).

  1. Extract the archive to the target folder: C:OpenSSH-Win;
  2. Open an elevated PowerShell prompt and switch to the OpenSSH folder: Cd C:OpenSSH-Win
  3. 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);
  4. 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:ProgramDataSSHsshd_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:PSmytestfile.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.

  1. Create SSH keys on your computer (SFTP client) for the user under which you will connect to the server: ssh-keygen -t ed25519
  2. 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);
  3. 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:Usersmax1.sshauthorized_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:Usersmax1.sshid_ed25519″ -Verbose

Источник

SFTP – FTP Server for Windows Server 2019 is a perfect solution to transfer files securely over encrypted network layers (using SSH2 protocol). SFTP is not just a simple “FTP over SSH” wrapper – it is a newer protocol, supported by all SSH2 servers.

This is a quick deployment and ready-to-run image.
Simple and rapid installation. Easy to maintain.

Configuration and connection to SFTP – FTP Server for Windows Server 2019 OpenSSH

First you need to open TCP port 22 in the network properties of the Azure Firewall.

The c:sftp folder is created on the VM. Subfolders with user names are creating automatically when they enter first time on SFTP.

To authenticate a local user on the server, add the user by opening “Users” shortcuts.

image2

After creating the user in Windows, you need:

1. Stop the SFTP server service by running the “stop ftp” shortcut on the desktop.

2. Create the necessary users in the server admin panel.

To add a user to the server, you need to click the shortcut on the desktop “freeFTPd”. When launched, the main window will not open, but immediately gets into the tray:

image6

To open the main application window, click right mouse button on the icon in the tray and select “Configure”. When opened, the following will displayed:

image7

To add SFTP users, go to the “Users” tab and click the “Add” button:

image4

In the user registration window, enter “Login”.

Select “Password stored as SHA1 hash” in the drop-down list of the “Authorization” field,

Next, in the “Password” field, enter any user-friendly password and confirm it in the “Password (again)” field.

Disable the use of “FTP serverand click Apply.

image3

3. After creating the necessary users, you need to:

  • go to the SFTP tab and make sure that “Server status: Stopped!”
  • start the service by clicking the “Start” button (“Server status” will become “Running…”)
  • click the “Apply & Save” button
  • click “Stop” (“Server status” will become “Stopped!”)
  • close the application window by clicking on the cross (the application minimizes to tray)
  • open the Windows tray, click right mouse button on the freeFTPd icon and select “Quit”.

4. Start the SFTP server service using the “start ftp” shortcut on the desktop.

To connect to ftp, it is recommended to use the “FileZilla Client” application (you can download it following the link: https://filezilla-project.org/download.php?platform=win64).

When launched, the application looks like this:

image1

In the “Host” field enter: sftp://SFTP, where SFTP is the address of your machine in the personal account in Azure.

In the “Username” field enter the user’s login of the virtual machine.

In the “Password” type the user’s password of the virtual machine.

When the data is entered click on “Quickconnect.

Then you will see the next window which asks if you can trust the host and its signatures, in this window you need to click “OK”:

image5

SFTP user folder is automatically created in the “C:sftp” folder, when the a user connects to SFTP first time. You can transfer files in this folder, so a user can view them.

FAQ:

Question: I get the error “The specified address is already in use”

Answer: This error occurs because of freeFTPd instance background running. To resolve this, you need to cancel all other instances of freeFTPd in the task manager, and then open it again. Also you can just stop freeFTPService and restart it.

Caio Cesar

Caio Cesar

Posted on Jan 15, 2021

• Updated on Jan 19, 2021

Requirements

Windows Server 2019 or Windows 10 version 1809+

Install OpenSSH

Press the Win + I keys to open the settings. Navigate to Apps -> Apps and Features -> Optional Features.

O the Installed features search for «OpenSSH» you will have the option to install the OpenSSH client or OpenSSH server.

Alt Text

Configuring the SSH Server

Press Win + R and type powershell; Run powershell as administrator, the following commands is responsible for having minimum consistency in the SSHD service:

To start the SSHD service automatically, use the command:

Set-Service -Name sshd -StartupType 'Automatic'

Enter fullscreen mode

Exit fullscreen mode

To setup the SFTP firewall port 22 Inbound, use the command:

New-NetFirewallRule -Name sshd -DisplayName 'OpenSSH Server (sshd)' -Enabled True -Direction Inbound -Protocol TCP -Action Allow -LocalPort 22

Enter fullscreen mode

Exit fullscreen mode

SSH (RSA) Key Generation

Two keys will ne generated for the client(private) and server(public).

Run powershell as administrator, to generate a pair of RSA 2048 keys use the command:

ssh-keygen

Enter fullscreen mode

Exit fullscreen mode

Select a key file location and enter the password for the new private key. The password will be required for SSH authentication.

Alt Text

The keys will be created in the specified directory:

  • id_rsa(private key)[client]
  • id_rsa.pub(public key)[server]

SSH-Agent Service

The ssh-agent is a key manager for SSH. It holds your keys and certificates in memory, unencrypted, and ready for use by ssh.

Run powershell as administrator, to startup the ssh-agent service use the command:

Set-Service -Name ssh-agent -StartupType 'Automatic'
Start-Service ssh-agent

Enter fullscreen mode

Exit fullscreen mode

Run powershell as administrator, to include the private key to the ssh-agent database:

ssh-add "{path}.sshid_rsa"

Enter fullscreen mode

Exit fullscreen mode

Check available ports for SFTP

Run powershell as administrator, use the command:

netstat -na | Select-String "22"

Enter fullscreen mode

Exit fullscreen mode

Uninstall the SSH Server

Run powershell as administrator, use the command:

Stop-Service sshd

Enter fullscreen mode

Exit fullscreen mode

Remove-NetFirewallRule -DisplayName "OpenSSH Server (sshd)"

Enter fullscreen mode

Exit fullscreen mode

Stop-Service ssh-agent

Enter fullscreen mode

Exit fullscreen mode

В статье я покажу, как настроить настроить SFTP-сервер в Windows с помощью OpenSSH.

Беспроводная передача данных в локальной сети — это не ноу-хау. Уже многие таким образом обмениваются файлами во внутренней сети. Часто для этого используется подключение по протоколу FTP.

Настраивается FTP-сервер и с помощью FTP-клиента другие компьютеры сети могут к нему подключиться. Но поскольку протокол FTP небезопасен, вам следует подумать об отказе от него в пользу чего-то лучшего. Для тех, кто не вкурсе, существует более безопасный протокол передачи файлов, который называется SFTP. Он шифрует передаваемые данные. Использование безопасного протокола SFTP может гарантировать, что никто не сможет подключиться и перехватить данные.

Содержание

  1. SFTP-сервер в Windows
  2. Настройка SFTP-сервера в Windows с помощью OpenSSH
  3. Установка OpenSSH (и активация необходимых сервисов)
  4. Открытие порта SSH в брандмауэре Windows
  5. Тестирование SFTP-сервера
  6. Тестирование SFTP-сервера в Windows
  7. Тестирование SFTP-сервера в Android
  8. Заключение

Все хорошо, но есть одна проблема чтобы настроить SFTP-сервер нужен SSH, а его во всех версиях Windows — нет. Если вам нужен SFTP-сервер придется использовать OpenSSH.

OpenSSH — это реализация SSH с открытым исходным кодом, и рекомендует использовать сам Microsoft. OpenSSH по умолчанию включен в Windows 10 и Windows Server 2019. Но вы можете использовать рассмотренный в статье метод с любой версией Windows.

Настройка SFTP-сервера в Windows с помощью OpenSSH

Настройка SFTP-сервер в Windows состоит из двух частей:

  • Установка OpenSSH
  • Открытие порта SSH для работы SFTP

Установка OpenSSH (и активация необходимых сервисов)

  1. Загрузите OpenSSH с GitHub.
  2. Распакуйте архив в папку Program Files.
  3. Откройте PowerShell от имени администратора и вставьте следующую команду в окно, чтобы перейти к папке:

    <strong>cd «C:Program FilesOpenSSHWin64</strong>».

  4. Для работы SSH требуются две службы: sshd и ssh-agent. Чтобы установить их, введите следующую команду в окно PowerShell:

    <strong>powershell.exe ExecutionPolicy Bypass File installsshd.ps1</strong>.
    Вы должны увидеть сообщение «Службы sshd и ssh-agent успешно установлены».

  5. Закройте окно PowerShell.
  6. Вы можете запустить службы вручную или настроить их автоматическое открытие с помощью Services.msc. Это создаст папку
    <strong>C:ProgramDatassh</strong> с вашим ключом хоста, который имеет важное значение для работы службы.

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

Открытие порта SSH в брандмауэре Windows

  1. SSH использует порт 22 для передачи / аутентификации, который закрыт в Windows, потому что SSH не включен по умолчанию. Чтобы открыть его, откройте брандмауэр Windows из панели управления.
  2. Нажмите на Входящие правила (на левой панели).
  3. На правой панели нажмите новое правило, выберите Порт и нажмите Далее.
  4. Введите число 22 в поле «Определенные локальные порты» и нажмите «Далее».
  5. Выберите «Разрешить подключение», нажмите «Далее» и выберите «Частный» для опции сети.
  6. Дайте правилу имя. Например, SSH или OpenSSH.
  7. Нажмите на Готово.

Как настроить порт SFTP брандмауэр Windows

Тестирование SFTP-сервера

Давайте проверим, работает ли SFTP-сервер. Для этого вам нужен SFTP-клиент. Я буду испоьзовать бесплатный SFTP-клиент WinSCP, но вы можете использовать любой другой, поддерживающий SFTP, например, FileZilla, FTP Rush или файловый менеджер с поддержкой SFTP, такой как Altap Salamander.

Для Android есть много вариантов; Total Commander и Ghost Commander имеют плагины SFTP, в то время как некоторые приложения, такие как Amaze File Manager или X-plore File Manager, имеют встроенную функцию SFTP.

Тестирование SFTP-сервера в Windows

Запустите WinSCP и выберите «SFTP» в качестве протокола. В поле имени хоста введите «localhost» (если вы тестируете компьютер, на котором вы установили OpenSSH). Вам нужно будет ввести имя пользователя и пароль Windows, чтобы программа могла подключаться к серверу. Нажмите сохранить и выберите логин.

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

SFTP сервер в Windows WINSCP

SFTP сервер в Windows WINSCP

Примечание. Если ваша учетная запись пользователя Windows не имеет пароля, вам потребуется использовать открытый ключ для аутентификации SFTP-сервера, который включает отдельный процесс. Вы можете создать другую учетную запись в системе для доступа к SFTP, но, возможно, потребуется сделать файлы доступными вне пользовательского каталога.

Тестирование SFTP-сервера в Android

Давайте использовать Amaze File Manager с открытым исходным кодом. Нажмите кнопку + и выберите «Облачное соединение». Выберите соединение SCP / SFTP, и должно появиться всплывающее окно. Найдите IP-адрес вашего компьютера с помощью командной строки и команды IP-конфигурации. Например, мой компьютер имеет адрес 192.168.1.9

SFTP сервер Android

Введите его в поле сервера, оставьте номер порта как 22 и введите имя пользователя и пароль Windows в соответствующих полях. Он должен подключиться к вашему компьютеру, и вы сможете получить доступ ко всему содержимому, доступ к которому может получить учетная запись Windows.

Заключение

Одним из основных преимуществ SFTP-сервера является то, что вы сможете легко получать доступ или передавать файлы по сети. Это не единственный способ делиться файлами, есть также небезопасный SMB и т.д., о которых мы рассказывали в этой статье.

Звёзд: 1Звёзд: 2Звёзд: 3Звёзд: 4Звёзд: 5 (4 оценок, среднее: 4,00 из 5)

Загрузка…

Понравилась статья? Поделить с друзьями:
  • Настройка nlb в windows server 2012
  • Настройка rdp windows 10 в локальной сети
  • Настройка sftp сервера на windows server 2016
  • Настройка nic teaming в windows server 2019
  • Настройка rambler почты на windows 10