Sftp сервер на windows server

С помощью встроенного пакета OpenSSH для Windows вы можете легко настроить безопасную передачу файлов между клиентом и серверов Windows по защищенному протоколу передачи файлов SFTP (Secure FTP). В этой статье мы покажем, как установить и настроить установить SFTP сервер в Windows 10/11 или Windows Server 2022/2019/2016/2012R2 с помощью встроенных средств (Win32-OpenSSH).

Содержание:

  • Установка OpenSSH в Windows
  • Настройка SFTP сервера на базе OpenSSH в Windows
  • Подключение к SFTP серверу с помощью PowerShell и WinSCP
  • Настройка SFTP аутентификации по ключам

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

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

  • Передача файлов и команд происходит внутри защищенной SSH-сессии;
  • Для передачи файлов и команд используется одно соединение;
  • Поддерживаются символические ссылки, доступны функций прерывания, возобновления передачи, удаления файла и другие;
  • Обычно на каналах, где FTP работает медленно или с перебоями, SFTP-соединение работает более надежно и быстро;
  • Возможность аутентификации с помощью SSH ключей.

Не нужно путать протоколы SFTP и FTPS. FTPS – это по сути обычный FTP с SSL сертификатом, а SFTP – это передача FTP данных и команд внутри SSH сессии.

В современные версии Windows по-умолчанию встроен порт OpenSSH для win32 (Win32-OpenSSH). Вы можете использовать его для организации защищенного SFTP сервера вместо таких сторониих продуктов как Core FTP, FileZilla, CYGWIN, OpenSSH, FTP Shell, IPSwitch и пр.

Установка OpenSSH в Windows

Пакет OpenSSH уже включен в операционную систему в современных билдах Windows 10 (начиная с 1803), Windows 11, Windows Server 2022/2019 в виде Feature on Demand (как и RSAT).

В этих версиях Windows вы можете установить сервер OpenSSH с помощью PowerShell:

Add-WindowsCapability -Online -Name OpenSSH.Server*

Или с помощью DISM:
dism /Online /Add-Capability /CapabilityName:OpenSSH.Server~~~~0.0.1.0

Также можно установить OpenSSH из графического интерфейса Windows 10 (Settings -> Apps -> Optional Features -> Add a feature -> Open SSH Server -> Install).

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

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

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

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

C:\windows\system32\OpenSSH\

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

Лог — c:\windows\system32\OpenSSH\logs\sshd.log

Файл authorized_keys и ключи хранятся в каталоге %USERPROFILE%\.ssh\.

В предыдущих версиях Windows 10, в Windows 8.1 или в Windows Server 2016/2012 R2 вам придется скачать Win32-OpenSSH для Windows с GitHub и установить вручную (https://github.com/PowerShell/Win32-OpenSSH/releases). Нам нужна версия для 64 битной версии Windows: OpenSSH-Win64.zip (4,15 Мб).

  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:\ProgramData\SSH\sshd_config», найдите и проверьте значение директивы Subsystem sftp. Здесь должен быть указан файл sftp-server.exe.

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

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

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

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

Match User user1
ChrootDirectory c:\SFTPRoot\user1
ForceCommand internal-sftp
X11Forwarding no
 AllowTcpForwarding no
Match User user2
ChrootDirectory c:\SFTPRoot\user2
ForceCommand internal-sftp
X11Forwarding no
AllowTcpForwarding no

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

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

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

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:\Temp\mytestfile.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:\Users\alex\.ssh\authorized_keys
    )

Теперь вы можете использоваться файл id_ed25519 для аутентификации на SFTP сервере в настройках WinSCP (настройки подключения Advanced -> to SSH > Authentication page -> Private key file).

Если вы хотите задать SSH ключ при подключении к SFTP из PowerShell, используйте такую команду:

New-SFTPSession -ComputerName 192.168.13.200 -Credential user1 -KeyFile C:\Users\alex\.ssh\id_ed25519" -Verbose

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 Kubernetes. He loves writing for his blog.

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%\ssh\sshd_config, but Windows can also read the configuration from the user profile (%UserProfile%\.ssh\config) if available. Furthermore, it allows you to specify a custom configuration file using the -f switch (e.g., sshd.exe -f «c:\users\administrator\.ssh\custom_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:\ProgramData\ssh\sshd_config").replace("#Port 22", "Port 2223") | Set-Content "C:\ProgramData\ssh\sshd_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%\ssh\sshd_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 testlab\developers testlab\ssh_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:\ProgramData\ssh\sshd_config file on the server in any text editor, and add the following line:

ChrootDirectory "C:\inetpub\wwwroot"

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:\inetpub\wwwroot). 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%\ssh\logs directory. As you can see in the following screenshot, the debug log showed that the user test\john 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

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:\windows\system32\OpenSSH\;
  • The sshd_config configuration file is located in  C:\ProgramData\ssh (this directory is created after the first start of the sshd service);
  • Log file: c:\windows\system32\OpenSSH\logs\sshd.log;
  • The authorized_keys file and keys are stored in a directory: %USERPROFILE%\.ssh\.

On the previous earlier builds of Windows 10, Windows 8.1, and on Windows Server 2016/2012 R2, you will have to download Win32-OpenSSH for Windows from GitHub and install it manually (https://github.com/PowerShell/Win32-OpenSSH/releases). We need a version for Windows x64: OpenSSH-Win64.zip (4,15 MB).

  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:\ProgramData\SSH\sshd_config) in any text editor.  Find and check the value of the Subsystem sftp directive. The sftp-server.exe file should be specified here.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 corp\sftp_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:\users\username folder)
ChrootDirectory C:\SFTP
ForceCommand internal-sftp
#You can set an individual chrootdirectory for each user:
Match User abrown
ChrootDirectory c:\SFTP\abrown
ForceCommand internal-sftp
X11Forwarding no
AllowTcpForwarding no

Match User jsmith
ChrootDirectory c:\SFTP\jsmith
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:\PS\mytestfile.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 [email protected]

Connect using ssh private key:

sftp -i .ssh/id_rsa [email protected]

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:\Users\max1\.ssh\authorized_keys )

Now you can use the id_ed25519 file to authenticate on the SFTP server. You can set your key in the WinSCP settings (Advanced -> to SSH connection settings > Authentication page -> Private key file).

If you want to use an SSH key when connecting to SFTP from PowerShell, use the following command:

New-SFTPSession -ComputerName 192.168.3.20 -Credential remoteuser1 -KeyFile C:\Users\max1\.ssh\id_ed25519" -Verbose

Nowadays the process for setting up a SFTP under Windows is fairly simple. But there are still some things that won’t go that easy and will give you strange errors and can cost you a lot of time. Especially when you want to use Active Directory authentication and a network share as the home folder.

First off we have to install OpenSSH. In Windows 10, 11, Windows Server 2019 and Windows 2022 this is just an optional feature that can be selected for installation.

Go to Settings > Apps > Optional features > Add a feature. Select OpenSSH server from the list and click install.

Here you can come across your first hurdle: “Installation failed”.

There is not much to go on here, because “install failed” is all the feedback you’ll get. After checking all kinds of different things, a default GPO was the problem. To solve this you’ll need open gpedit.msc and go to Computer configuration > Administrative Templates > System. And there in the root of System find and open the policy “Specify settings for optional component installation and component repair”.

Enable the setting and also check “Download repair content and optional features directly from Windows Update instead of Windows Server Update Services (WSUS)”.

After this your install of OpenSSH should complete without an error and the binaries will be installed in C:\Windows\System32\OpenSSH.

On older installations you now should make a new rule in Windows Defender Firewall to allow incoming traffic on port 22, but I found that in Windows Server 2022 this is already done.

Now go to the Windows Services and change the OpenSSH Server service from manual to automatic and start the service. When the service is started for the first time the working directory will be created in C:\ProgramData\ssh.

Now that the OpenSSH service is running, you would think that you can connect to it, but when you try, you’ll get an access denied error. This is because you have to specify which accounts have access to the service and by default none are configured.

To configure authentication go to C:\ProgramData\ssh and open the file sshd_config with a text editor. According to the Microsoft documentation (https://docs.microsoft.com/en-us/windows-server/administration/openssh/openssh_server_configuration#allowgroups-allowusers-denygroups-denyusers), you’ll simply have to add AllowUsers followed by the users you want to grant access to the config file and it should work.

This is the second hurdle in setting up the SFTP server. I tried many combinations of the allowed user syntax, including:
DNSdomainname.local\Username
DNSdomainname.local\Username
DNSdomainname.local\Username@Servername
DNSdomainname.local\Username@Servername
NetBIOSdomainname\Username
NetBIOSdomainname\Username
NetBIOSdomainname\Username@Servername
NetBIOSdomainname\Username@Servername
NetBIOSdomainname\Username@172.17.22.10
NetBIOSdomainname\Username@172.17.22.10
NetBIOSdomainname\sa_ftpbackup@Servername
Username?NetBIOSdomainname
Username?NetBIOSdomainname*
Username?DNSdomainname.local
Username?DNSdomainname.local*

But all failed miserably and I got “Access denied” in Putty and “Permission denied, please try again.” in PowerShell.

To get more information about why the access was denied, you can stop the OpenSSH service and start it manually from an elevated prompt with the debug parameter, like: sshd.exe -d

In this logging you’ll see that the group can’t be mached.

debug1: get_passwd: LookupAccountName() failed: 1332.
debug1: Can't match group at line 94 because user NetBIOSdomainname\\username@hostname does not exist
Invalid user NetBIOSdomainname\\username@hostname from x.x.x.x port 53784
debug1: userauth-request for user NetBIOSdomainname\\\\username@hostname service ssh-connection method keyboard-interactive [preauth]
debug1: attempt 1 failures 0 [preauth]
debug1: keyboard-interactive devs  [preauth]
debug1: auth2_challenge: user=NetBIOSdomainname\\\\username@hostname devs= [preauth]
debug1: kbdint_alloc: devices '' [preauth]
debug1: userauth-request for user NetBIOSdomainname\\\\username@hostname service ssh-connection method password [preauth]
debug1: attempt 2 failures 1 [preauth]
debug1: Windows authentication failed for user: NOUSER domain: . error: 1326
Failed password for invalid user NetBIOSdomainname\\username@hostname from x.x.x.x port 53784 ssh2
Connection closed by invalid user NetBIOSdomainname\\\\username@hostname x.x.x.x port 53784 [preauth]

Eventually the work-a-round was fairly easy. Create a local group and add your domain users in that local group. Now add that group to the sshd_config file like: AllowGroup SFTPUsers

Now when you try to login, you’ll get a different message “Connection reset by x.x.x.x port 22”. It’s not much, but it is something 😉

Looking at the logging it became clear that the problem had something to do with elevated and privileged processes.

Accepted password for NetBIOSdomainname\\username from x.x.x.x port 53735 ssh2
debug1: monitor_child_preauth: NetBIOSdomainname\\username has been authenticated by privileged process
debug1: monitor_read_log: child log fd closed
debug1: Not running as SYSTEM: skipping loading user profile
CreateProcessAsUserW failed error:1314
fork of unprivileged child failed
debug1: do_cleanup

This can also be solved very easily. Don’t start sshd from the command line, but start the service. The service has to be started under the system account, so it can reach all needed dependencies.

Now that we can access the server over SCP, we only need to alter the default home directory for the users. As long as that is a folder on the server you’re fine, but when you want to use a network location, you’re in for a treat. You can’t use UNC paths.

In the event viewer you’ll see errors like “sshd: error: chroot only support absolute paths”

And “sshd: fatal: chroot (“\\network path”): Operation not supported”

To get around this problem, you could use a symbolic link. Symbolic links or symlinks are “virtual” files or folders which reference a physical file or folder located elsewhere. To create such a symbolic link you have to open an elevated prompt and use the mklink commando. mklink -d <link> <target>

Now you should have a working setup. However, when you get a message stating that permission is denied, you’ll have to add the service account to the local administrators group. This is because of the rights assigned to the symbolic link. By default “Authenticated users”, “System” and “Administrators” are configured, but “Authenticated users only have read rights.

You can’t change these rights. If you try to change them you’ll get enumerating and access denied errors.

So when you add the service account to the local administrators group, you’ll get write rights. So far for the least privileged approach 😉

Daniel de Zoete

Started his working life as a system manager at a health care organization. Is now a dedicated technical consultant at PepperByte. Specialist in virtualization and security.

Core qualities
Eager to learn, punctual, fun, loyal, patient

Hobbies
Socializing, watching television series and sports

Job description
Technical Consultant

How to Setup SFTP Server on Windows Server using OpenSSH Free. While sending data over the internet, people usually suffer from many threats. Malicious attackers are always ready to hamper the data send from one place to another.

You may be aware of what I’m talking about: an FTP connection. With an FTP client you can connect one device to another to transfer your data over a network.

But using FTP protocol could not be safe enough sometimes, so what is better file transfer protocol? The better wireless transfer protocol is called SFTP. The S in SFTP stands for secure. It encrypts the connection’s login information during data transfer. 

If you want to keep your data safe, it is essential to use an SFTP server, a tool that provides security to data in transit.

In this post, we will introduce SFTP with its main advantages and then move on to the installation and configuration phase on the Windows server with OpenSSH.

What Is SFTP Server?

Setup SFTP Server on Windows Server using OpenSSH Free.

Secure File Transfer Protocol or SFTP Server is a protocol that helps you in transferring files securely. Simply put, it is a way of transferring files between a machine over a secure connection.

This transfer can be performed between server to server or client to server configurations. Therefore, with the help of this protocol, you can send confidential files securely over the networks or insecure networks.

Let’s explore how SFTP works in sending files securely from one place to another.  The SFTP uses a secure shell data stream that aids in establishing a secure connection and provides a higher level of protection for data while transferring it.

It also uses different encryptions that ensure the data remains unread while moving the data. However, you need to create SSH keys in advance to ignore fraud people from connecting to the server.

Advantages Of SFTP Server

There are following advantages that the SFTP Server provides: 

Immediate And Effective

With the help of the SFTP server, you can transfer large files easily and effectively. It enables you to transfer multiple files from one server to another in a single go, because of which you tend to save a lot of time. Enterprises using SFTP servers considered it a much better method than emails or cloud. They find exchanging of documents, forms and business critical files to the customer effortless.

Strengthens Data Accessibility

The services that the SFTP or Secure File Transfer Protocol provides are for both client applications and other SFTP servers. It satisfies user to server and server to server facilities. It enables you to foster collaboration and increased productivity of your organization by making data effortlessly accessible.

Improves speed and efficiency in business

Large file transfers are supported by SFTP servers support as well as bulk file transfers. It saves time and leads to better file transfer/sharing methods like email or cloud based solutions.

Fewer Risks

When using SFTP Server you also get encryption, public key authentication, data integrity, and host authentication. It encrypts all the data before transferring, making it non decipherable. It can be decrypted only by the receiver. Authenticating a public key helps you ensure that no imposter is making use of the intended data. For this purpose, you need to provide the receiver with usernames and passwords. This SFTP server also checks whether the data is coming from a trusted source. It verifies both the client and the source before establishing the connection.

SFTP Encryption

Encryption is a strong part of Secure File Transfer Protocol. It secures it from unauthorized access or hackers. Then it converts it into an unreadable format during transmission process, so it’s unreadable. The SSH Encryption is used during the file transfer to secure the process of transfer.

Helps In Achieving Compliance

There are laws that contain provisions that require covered entities to implement secure file transfers. If these protocols fail to comply with the security requirements, that could lead to costly penalties, which can damage your reputation. Not only the SFTP server is built with encryptions but also other security mechanisms, that help in satisfying certain regulatory requirements.

Follow this post to show you how to setup SFTP server on Windows server using OpenSSH free.

What is OpenSSH

The OpenSSH is the open source version of the Secure Shell (SSH) tools for remote login. What it does it encrypts all traffic to prevent attacks. Also the OpenSSH offers a large suite of secure tunnelling capabilities, authentication and configuration options.

Setup SFTP Server on Windows with OpenSSH

Prerequisites

  • A server running Windows Server operating system along with RDP access.
  • A user with administrative privileges.
  • Minimum 4 GB of RAM with 2 Cores CPU.

Install OpenSSH Server

To start, the SFTP uses an SSH protocol to transfer files securely between two machines. So you will need to install an OpenSSH server on your Windows server. You can install an OpenSSH server via PowerShell.

Firstly, open the PowerShell window as an administrator, then run the following command to check whether an OpenSSH is installed or not:

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

You should see the following output:

				
					Name  : OpenSSH.Client~~~~0.0.1.0
State : NotPresent

Name  : OpenSSH.Server~~~~0.0.1.0
State : NotPresent

				
			

As you can see that an OpenSSH server or client is not installed on your server.

Please run the following command to install the OpenSSH server on your machine:

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

Once the OpenSSH server is installed, you will get the following output:

				
					Path          : 
Online        : True
RestartNeeded : False

				
			

At this point, the OpenSSH server is installed on your server. You can now proceed to configure the OpenSSH server.

Configure OpenSSH Server

After the successful installation, you will need to start the OpenSSH service. You can start it using the following command:

Enable the OpenSSH service to start after the system reboot. You can do it using the following command:

				
					Set-Service -Name sshd -StartupType 'Automatic'
				
			

During the OpenSSH installation, the Firewall rule for SSH was configured automatically. You can check it by running the following command:

				
					Get-NetFirewallRule -Name *ssh*
				
			

You should see the following output:

				
					Name                          : OpenSSH-Server-In-TCP
DisplayName                   : OpenSSH SSH Server (sshd)
Description                   : Inbound rule for OpenSSH SSH Server (sshd)
DisplayGroup                  : OpenSSH Server
Group                         : OpenSSH Server
Enabled                       : True
Profile                       : Any
Platform                      : {}
Direction                     : Inbound
Action                        : Allow
EdgeTraversalPolicy           : Block
LooseSourceMapping            : False
LocalOnlyMapping              : False
Owner                         : 
PrimaryStatus                 : OK
Status                        : The rule was parsed successfully from the store. (65536)
EnforcementStatus             : NotApplicable
PolicyStoreSource             : PersistentStore
PolicyStoreSourceType         : Local
RemoteDynamicKeywordAddresses : {}

				
			

Set PowerShell as the default for OpenSSH. You can do it by running the following command:

				
					New-ItemProperty -Path "HKLM:\SOFTWARE\OpenSSH" -Name DefaultShell -Value "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -PropertyType String -Force
				
			

The following output should be like this:

				
					DefaultShell : C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
PSPath       : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOFTWARE\OpenSSH
PSParentPath : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOFTWARE
PSChildName  : OpenSSH
PSDrive      : HKLM
PSProvider   : Microsoft.PowerShell.Core\Registry

				
			

Verify OpenSSH Connection

At this point the OpenSSH server is installed, configured and listens on port 22 on the Windows server. Now, you will need to verify the SSH connection from the remote Linux machine.

On the Linux machine, open your terminal and run the following command to connect to the OpenSSH server:

				
					ssh username@windows-sftp-server-ip
				
			

You will be asked to provide the password of the Windows user:

				
					The authenticity of host '208.117.85.180 (208.117.85.180)' can't be established.
ECDSA key fingerprint is SHA256:V6qNABiAL3Ni5viQWM8FV4eMH7IDuoign8kiXUwJ9LQ.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '208.117.85.180' (ECDSA) to the list of known hosts.
ftpuser@208.117.85.180's password: 

				
			

Provide your password and press the Enter key. Once you are connected to the OpenSSH server. You should get the following shell:

				
					Microsoft Windows [Version 10.0.20348.502]
(c) Microsoft Corporation. All rights reserved.

ftpuser@CLOUD-JET35GPBR C:\Users\ftpuser>

				
			

Verify all files and directories of the Windows user using the following command:

You shall get the following output:

				
					 Volume in drive C has no label.
 Volume Serial Number is 24D4-E65B

 Directory of C:\Users\ftpuser

07/10/2022  07:48 AM              .
07/10/2022  07:48 AM              ..
05/08/2021  08:20 AM              Desktop
07/10/2022  07:48 AM              Documents
05/08/2021  08:20 AM              Downloads
05/08/2021  08:20 AM              Favorites
05/08/2021  08:20 AM              Links
05/08/2021  08:20 AM              Music
05/08/2021  08:20 AM              Pictures
05/08/2021  08:20 AM              Saved Games
05/08/2021  08:20 AM              Videos
               0 File(s)              0 bytes
              11 Dir(s)  71,437,893,632 bytes free

				
			

Test the SFTP Server

To connect to the SFTP server, you will need an SFTP client on the remote PC. There are many SFTP client tools available to connect to the SFTP server. In this tutorial, we will use FileZilla to connect to the SFTP server.

1.First, open the FileZilla client on the remote PC. You should see the FileZilla interface on the following screen:

filezilla dashboard

2.Now, click on the Site Manager to create a new SFTP connection. You should see the following screen:

filezilla sftp connection

3.Provide your SFTP server IP, Port, select SFTP from the dropdown, username, password, and click the OK button. Once you are connected to the SFTP server. You will get the following screen:

Setup SFTP Server on Windows Server using OpenSSH Free.

From here, you can easily download and upload files to and from the SFTP server.

How to Setup SFTP Server on Windows Server using OpenSSH Free Conclusion

In this post, we explained how to set up an SFTP server using the OpenSSH free on Windows server. Compared to an FTP server, an SFTP server is a very secured protocol that uses a secure shell data stream and provides a higher level of protection for data transfer  between machines. I hope you can now easily set up your own SFTP server to upload and download files from the remote machine.

Please read more of our content on FTP server here. I hope you have enjoyed this article and please do not hesitate to contact us for further assistance. 

  • Shader minecraft windows 10 edition
  • Shaders for minecraft windows 10 edition
  • Sfc scannow windows 7 не смог исправить
  • Sfc scannow windows 10 что это
  • Sfc scannow windows 10 права администратора