Mount linux directory to windows

Для подключения файловой системы удаленного сервера в качестве сетевого диска в Windows можно использовать защищенный протокол SSH (вместо стандартного SMB/samba). Это удобно, когда нужно сделать файлы на удаленном SSH сервере доступными для локальной работы без использования дополнительных FTP/SFTP подключений. Для монтирования удаленных файловых систем в Windows можно использовать клиент SSHFS-Win. Этот клиент позволяет прозрачно подключать каталоги с удаленных компьютеров по протоколу SSHFS (основан на протоколе передачи SFTP, SSH File Transfer Protocol).

Можно скачать MSI установщик SSHFS-Win вручную или установить его через встроенный пакетный менеджер WinGet:

winget install SSHFS-Win.SSHFS-Win

Установка клиента SSHFS-Win.SSHFS-Win

Теперь можно смонтировать удаленную папку в виде сетевого диска прямо из проводника File Windows. Щелкните правой мышкой по значку Этот компьютер и выберите Подключить сетевой диск. Здесь нужно выбрать букву диска, которую нужно назначить и указать UNC путь к удаленной директории в формате:

\\prefix\\user@host[!PORT][\\PATH]

User
– учетная запись для аутентификации на удаленном SSH хосте

Host
– имя/IP адрес хоста

В качестве префикса нужно указать один из следующих значений:

  • sshfs
    – подключиться в домашний каталог пользователя (в случае Windows это каталог профиля пользователя). Дополнительно указать относительный путь к людому каталогу в профиле пользователя.
  • sshfs.r
    – подключиться к корневой папке системы (в случае Windows это будет корень системного диска)
  • sshfs.k
    – подключиться в домашний каталог пользователя. Для аутентификации использовать SSH ключ в %USERPROFILE%/.ssh/id_rsa
  • sshfs.kr
    – подключиться к корневой директории с SSH ключом

Например, для монтирования каталога
C:\PS
с удаленного Windows хоста (на котором настроен SSH сервер), введите такой UNC путь:

\\sshfs.r\[email protected]\ps

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

Подключение сетевого диска из проводника Windows с помощью USNC пути sshfs

После этого в проводнике Windows появится отдельной сетевой диск, подключенный по SSHFS.

Сетевой диск подключен по SSH в Windows 11

Также можно подключить сетевой диск из командной строки с помощью стандартной команды
net use
.

Следующая команда смонтирует каталог
/var/www
на Linux сервере в качестве сетевого диска Windows:

net use W: \\sshfs.r\[email protected]\var\www /user:sysops

Смонтировать локальную папку с Windows хоста:

net use m: \\sshfs.r\[email protected]\ps /user:administrator

При подключении нужно будет ввести пароль пользователя.

net use подключение sshfs диска

Подключенный таким образом сетевой диск будет существовать только до следующей перезагрузки компьютера. Чтобы автоматически переподключать диск при входе пользователя, в команду нужно добавить опцию
/persistent:yes

Чтобы не вводить пароль пользователя для подключения, можно сохранить пароль в Windows Credential Manager с помощью:

cmdkey /add:192.168.158.13 /user:sysops /pass:Passw0rdd1

Одновременно через провайдера WinFsp.Np может быть подключено несколько сетевых папок. Вывести список подключенных дисков:

net use

net use - список дисков подключённых по SSH/ WinFsp.Np

Удалить один из дисков:

net use M: /delete

В команде net use можно указывать пароль и в открытом виде, но безопаснее будет настроить монтирование удаленной папки с помощью аутентификации по SSH ключу.

Сгенерируйте SSH ключи в Windows с помощью утилиты
ssh-keygen
согласно мануалу по ссылке (не указывайте пароль для защиты закрытого ключа). Добавьте открытый ключ из файла .pub в файл
authorized_keys
(или
administrators_authorized_keys
) на удаленном SSH сервере.

Для автоматического подключения сетевого диска по SSH с аутентификацией по ключу при входе в Windows, можно создать задание планировщика которое будет запускать такой PowerShell скрипт:

$rUser = "administator"
$rHost = "m-fs01.winitpro.ru"
$remoteDir = "\Install"
$Drive = "M:"
$privSSHKey = "C:\secret\m-fs01-id_rsa"
cd  'C:\Program Files\SSHFS-Win\bin\'
$mountcmd = ".\sshfs-win.exe svc \sshfs.k\$rUser@$rHost$remoteDir $Drive -IdentityFile=$privSSHKey"
Invoke-Expression $mountcmd

Можно использовать графический клиент для создания подключений сетевых дисков по SSH. Самым простым и удобным является SSHFS-Win-Manager. Клиент
SSHFS-Win-Manager
позволяет создать несколько SSHFS подключений к удаленным файловым системам. Поддерживает аутентификацию, как по паролю так и ключу.

SSHFS-Win-Manager - графический клиент для подключения дисков по SSH

SSHFS на Windows 10 для монтирования папки из Linux Debian 10

Сегодня расскажу как смонтировать папку (например, с сайтами) из Debian в Windows 10 по SSH (SFTP) с удобным включением/выключением. Под нужным пользователем (www-data) с нужными правами.

Ниже длинное вступление о том как и зачем мне это нужно. Его можно промотать.

Те кто читал мои посты в блоге и видел видосики на канале знают что в основном я занимаюсь разработкой своих сайтов на WordPress, Yii, Laravel. Основной инструмент — PhpStorm. Боевые проекты хостятся на разных вдсках в основном это FastVPS и RuWEB. Везде Debian + Nginx и везде более менее стандартный конфиг (с поправкой на версии и нагрузку кажого из проектов). Всего порядка десяка вдсок.

Разработка и бэкапы на локальной машине под Windows 10, где крутится усредненный аналог боевой конфиги в VirtualBox. Т.е. дев сервер сейчас это Debian 10 + Nginx 1.15.

Разработка и деплой на rsync

Со всех вдсок sh скрипт с помощью

ssh + rsync + mysqldump  собирает текущие версии проектов и в итоге на дев инстансте всегда актуальные данные любого из проектов. На деве ведется разработка, тестирование, минификация, обфускация и т.д.После чего тем же скриптом изменения деплоятся на прод, на конкретную вдску. Git используется только на деве.

Я знаю про Docker :)

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

Проблема на самом деле в PhpStorm

SSHFS на Windows 10 для монтирования папки из Linux Debian 10

В PhpStorm когда вы создаете проект из ранее созданных файлов ( Create New Project from Existing Files ) у вас есть по сути два выбора — файлы проекта расположены локально или удаленно. Если создать проект из удаленных файлов, то PhpStorm будет скачивать их все на локальный диск для индексации. А при изменении закачивать их обратно на удаленный сервер (например по SFTP). Это не проблема, когда разработка идет на одном компьютере.

Разработка на разных компах, в разных сетях

Однако я работаю сразу на 3х — стационарный десктоп под Windows 10, два ноутбука. Один ноут используется дома (нравится мне менять места и позы во время работы), второй используется реже — вне дома. И в этом случае возникает сложность синхронизации локальных проектов одного и того же удаленного проекта. Особенно если это проекты с множеством мелких файлов. Например Laravel c Laravel Mix. Короче жуткая головная боль.

Монтирование папки из Debian все бы решило

Куда проще если бы можно было подмонтировать удаленную папку сайта и создавать проект в PhpStorm как с локальными файлами. В Ubuntu это делается элементарно, а вот под виндой все на порядок сложнее.

Вариант с Samba

В принципе дома у меня работала схема с Samba сервером на дев виртуалке под юзером www-data. Но если работать с дев сервером с улицы (через проброс портов через роутер) и если домашний ip динамический, то возникает несколько сложностей — нужно каждый раз менять ip, пробрасывать порт в роутере ещё и на самбу (лишняя уязвимость), перемонтировать диски. Короче хотелось так чтобы как в Ubuntu. И выход нашелся.

Монтирование папки из Linux (Debian) в Windows по SFTP

Для монтирования папки из Linux в Window 10 по SFTP я использую связку billziss-gh/winfsp  + billziss-gh/sshfs-win . WinFSP — это порт https://github.com/libfuse/sshfs под винду. А sshfs — это как раз та сетевая файловая система что используется в Ubuntu для монтирования по SFTP. Как я и хотел.

Итак ставим сначала WinFSP, затем SSHFS-Win. Сразу после перезагрузки диски папки можно будет легко монтировать прямо из проводника Windows 10. См. картинку.

Монтирование папки через проводник в SSHFS-Win

Монтирование папки через проводник в SSHFS-Win

Однако в моем случае это не решило проблему.

Нестандартные порты SSH при монтировании

При монтировании папки через проводник вы можете указать путь до папки на сервере, но не можете указать порт SSH, если ssh висит не на 22. Это можно сделать в командной строке

net use Z: \\sshfs\[LOCUSER=]REMUSER@HOST[!PORT][\PATH]

Но тогда:

  • проводник, а соотв. и PhpStorm не увидит примонтированный диск
  • логин/пароль придется вводить каждый раз.

Есть ощущение что это все можно решить если глубоко погрязнуть в скрипты настройки SSHFS-Win, однако здесь есть и два GUI это SiriKali и SSHFS-Win-Manager  .

SiriKali мне жутко не понравился, а вот SSHFS-Win-Manager прижился. Собственно его использование решает почти все проблемы для монтирования дисков из Linux в Windows 10 по SFTP. Я напишу о его настройке чуть ниже. Однако в моем случае просто монтирования было не достаточно.

SSHFS-Win проблемы с юзером и правами на новые папки и файлы

Я ведь все эту чехарду устроил ради разработки и мне нужно чтобы работа на подмонтированном диске была из под юзера

wwwdata  юзер www-data по умолчанию не имеет доступа к консоли и под ним нельзя примонтировать диск. Также SSHFS-Win создает НОВЫЕ папки и файлы с правами 0700 (для уже созданных не меняет), а мне надо чтобы было 0755 на папки и 0644 на файлы.

Разрешаю монтирование под www-data

Это самое сомнительное решение. Во всей этой схеме. Однако для виртуалки за роутером я решил что сойдет.

sudo passwd wwwdata # задаем пароль для www-data

И в файле

/etc/passwd правлю строку:

wwwdata:x:33:33:wwwdata:/home:/bin/bash

Обрати внимание что я сменил и папку юзера на ту, которую буду монтировать. Перезагружаю виртуалку и все — под www-data можно логиниться и монтировать диски.

Права на вновь создаваемые папки и файлы под SSHFS-Win

Для задания нужных прав у WinFSP есть опции

create_file_umask  и

create_dir_umask . Их можно использовать в командной строке, однако проще в SSHFS-Win-Manager . Смотри картинки ниже.

Настройки SSHFS-Win-Manager

SSHFS на Windows 10 для монтирования папки из Linux Debian 10

Здесь я создал два диска с одной буквой. Все эти маунты ведут на одну и туже виртуалку VirtualBox. Но один на внутренний IP, а второй через внешний динамический IP (через роутер с проброшенными портами на 80, 443 и ssh). Т.е. дома я монтирую верхний вариант и проброс в роутере могу вообще закрыть. А если работаю вне дома, то монтирую нижний. При этом для PhpStorm это всегда один и тотже локальный диск V. Невероятно удобно.

SSHFS на Windows 10 для монтирования папки из Linux Debian 10

SSHFS на Windows 10 для монтирования папки из Linux Debian 10

На этой картинки расширенные настройки, которые позволяют выставить нужные мне права (0755 / 0644). Если тебе нужны другие права гугли “permission umask ”.

На данный момент схема хорошо работает. На 4G Laravel проект под PhpStorm индексируется на 20-30 секунд, что более чем приемлемо.  Если есть что дополнить или вопросы — пиши комменты (могут отлетать в премодерацию — это норма, я одобрю и отвечу). Также я есть в Телеграм.

On Windows 11, the Windows Subsystem for Linux (WSL) ships with a new feature that allows you to attach and mount physical drives to access Linux file systems (for example, ext4) not natively supported on Windows.

The new feature allows users to access Linux files using File Explorer on a dual-boot system running Windows 11 and a Linux distro on a different drive.

In this guide, you will learn the steps to mount and unmount drives using the Windows Subsystem for Linux.

  • Mount Linux file system on Windows 11
  • Mount any Linux file system on Windows 11
  • Access Linux file system on Windows 11
  • Unmount Linux file system on Windows 11

To mount a Linux file system using WSL, use these steps:

  1. Open Start on Windows 11.

  2. Search for PowerShell, right-click the top result, and select the Run as administrator option.

  3. Type the following command to list the available physical disks and press Enter:

    wmic diskdrive list brief
  4. Confirm the drive path under the “Device ID” column.

  5. Type the following command to mount the Linux file system and press Enter:

    wsl --mount DISKPATH

    WSL mount Linux partition

    In the command, make sure to replace DISKPATH for the drive path with the Linux distribution you want to mount. For example, wsl --mount \\.\PHYSICALDRIVE2. If you’re going to mount a specific partition, you’ll need to use the --partition option with the partition number. For example, wsl --mount \\.\PHYSICALDRIVE2 --partition 1.

Once you complete the steps, the drive with Linux files will mount, and it’ll be visible from Windows 11.

Mount any Linux file system on Windows 11

The previous steps only attempt to mount a physical drive as ext4. If you want to specify another file system, you will need to use a different command with the Windows Subsystem for Linux 2 (WSL2).

To mount a specific Linux file system on Windows 11, use these steps:

  1. Open Start.

  2. Search for PowerShell, right-click the top result, and select the Run as administrator option.

  3. Type the following command to list the available physical disks on Windows 11 and press Enter:

    wmic diskdrive list brief
  4. Confirm the drive path under the “Device ID” column.

  5. Type the following command to mount a drive and press Enter:

    wsl --mount DISKPATH -t FILESYSTEM

    In the command, make sure to replace DISKPATH and FILESYSTEM for the path of the Linux drive and file system you want to mount. For example, to mount a disk as fat, use this command: wsl --mount DISKPATH -t vfat.

After you complete the steps, the drive with Linux files will mount, and it will be accessible using File Explorer.

Access Linux file system on Windows 11

To access files from a Linux file system on Windows 11, use these steps:

  1. Open File Explorer.

  2. Click the Linux item from the left navigation pane.

  3. In the address bar, navigate to \wsl$ and then access the mount folder. For example, \\wsl$\\DISTRO-NAME\\MOUNT-POINT.

    WSL browse  mounted drive

Once you complete the steps, you should be able to browse the Linux files from a natively unsupported file system on Windows 11. In addition to using File Explorer, you can access file systems like “ext4” from the WSL2 console using command lines once the drive is mounted.

Unmount Linux file system on Windows 11

To unmount the Linux file system on Windows 11, use these steps

  1. Open Start.

  2. Search for PowerShell, right-click the top result, and select the Run as administrator option.

  3. Type the following command to unmount and detach the drive and press Enter:

    wsl --unmount DISKPATH

    WSL unmount partition

    In the command, make sure to replace DISKPATH for the Device ID of the drive you want to unmount.

After you complete the steps, the drive with the Linux file system will unmount and detach from Windows 11.

Why You Can Trust Pureinfotech

The author combines expert insights with user-centric guidance, rigorously researching and testing to ensure you receive trustworthy, easy-to-follow tech guides. Review the publishing process.

Working on a remote directory as if it were a local one is more convenient, don’t you agree? Instead of pushing and pulling files remotely using SCP, SFTP, or FTP, what if you could manage those files directly? Lucky for you, the SSHFS mount is a quick solution to this dilemma.

This tutorial will teach you how to use SSHFS mount so you can access the remote directory contents on your local machine. Whether you’re a Windows or Linux user, this tutorial’s got you covered.

The specific use-case example in this tutorial demonstrates updating a website’s contents on a remote server’s SSHFS mounted directory. But, the general concept should apply to your specific situation and is not limited to web servers only.

Prerequisites

This tutorial will be a hands-on demonstration. If you’d like to follow along, be sure you have the following:

  • A Linux web server – This tutorial will use a Fedora 35 named wbserver with Apache HTTP Server installed. This server contains the remote directory that will be the target of the SSHFS mount.
  • A Linux client – This tutorial will use a Fedora 35 client named fedora.
  • A Windows client (Windows 7 and above) – This tutorial uses a Windows 10 client named win10pc.

Preparing the Remote Directory

This tutorial will be working on the remote directory on the wbserver server called /var/www/html. By default, only the root account has access to this folder. Since you will not be using the server’s root account, you must give the designated user account permission to the directory instead.

In this example, the designated user account for mounting and accessing the SSHFS mount is adm1. Follow the below steps to give adm1 the proper permissions to /var/www/html on wbserver.

1. Log in to wbserver using your preferred SSH client.

2. Next, run the below command to give the adm1 user full access (rwx) permissions to the /var/www/html folder.

sudo setfacl -m u:adm1:rwx /var/www/html

3. Lastly, confirm that the permission is correct by running the below command.

sudo getfacl -a /var/www/html

As you can see below, adm1 now has read/write access to the folder.

Viewing the folder permissions

Viewing the folder permissions

Using SSHFS Mount on Linux

SSHFS is primarily a Linux tool, and you only need to issue a few commands to mount a remote directory to your computer. Installing the packages to enable SSHFS mount is as convenient as installing other packages on Linux through your distro’s package manager.

Installing SSHFS and Mounting a Remote Directory

Follow the below steps to install the SSHFS mount package and mount a remote directory to a local path.

1. Log in to your Linux client via SSH or Desktop, depending on your environment.

2. Run the following command to install the fuse-sshfs package using your package manager.

Note: On Debian-based Linux distros, the package name is sshfs.

sudo dnf install -y fuse-sshfs

The package manager also installs the dependencies not yet present on your computer. And because each package size is below 100KB, the download and installation took only a few seconds to finish.

Installing the SSHFS mount package on Fedora

Installing the SSHFS mount package on Fedora

3. Next, create a new folder under your home directory called mnt. This new folder is the mount point for the remote directory.

4. After creating the mount point, execute the below sshfs command.

This command will mount the web server’s (wbserver) remote directory (/var/www/html) to the local mount point (~/mnt) you created while using adm1’s credentials for access.

sshfs adm1@wbserver:/var/www/html ~/mnt

If the SSH server is not listening to the default port 22, you must specify the -o port <number> switch with the sshfs command. For example, if the remote server listens to port 2222, the command would be sshfs -o port 2222.

5. If you’re connecting to the server for the first time, confirm the connection by pressing Y at the prompt—type in the account’s password and press Enter.

Mounting a remote directory with SSHFS mount

Mounting a remote directory with SSHFS mount

6. Lastly, confirm that you’ve successfully mounted the remote directory by running the below command.

You should see that the remote directory is now mounted to the local directory you specified.

Listing the mounted file systems

Listing the mounted file systems

Enabling Automount on Boot

While you’ve successfully mounted the remote directory, remember that this mount status is not persistent. Restarting the computer will not automount the remote directory.

But, you can make the SSHFS mount survive computer restarts by editing the /etc/fstab file and enabling key-based authentication for the adm1 account. Enabling the SSH key-based authentication ensures that the SSHFS mount will be fully automated (no password prompts).

1. On the Linux client, generate a new SSH key pair by running the below command.

On the Enter file in which to save the key prompt, type in the key filename and press Enter. In this example, the key filename to save is /home/user1/.ssh/adm1@wbserver.

Leave the passphrase empty, and press Enter twice. The below screenshot shows the key pair creation result.

Generating the key pair for the SSHFS mount

Generating the key pair for the SSHFS mount

2. Now, copy the key to the webserver. The command below installs the key you previously generated (/home/user1/.ssh/adm1@wbserver) to the adm1 account on wbserver.

ssh-copy-id -i /home/user1/.ssh/adm1@wbserver adm1@wbserver

Type in the password for adm1@wbserver at the prompt and press Enter. As you can see below, the command successfully installed the key to the server.

Installing the SSH key to the server

Installing the SSH key to the server

3. SSH into wbserver using the key pair to ensure that the key-based login works.

ssh -i /home/user1/.ssh/adm1@wbserver adm1@wbserver

As a result, the login should succeed without asking for a password. Type exit and press Enter to log out of the wbserver.

wbserver

wbserver

4. Now that you’ve configured the SSH key-based authentication for the SSHFS user account, you’re ready to configure the persistent SSHFS mount.

Open the /etc/fstab file in a text editor.

5. Append the below code to the end of the /etc/fstab file. Make sure to change the identityfile= value with the SSH key file path.

adm1@wbserver:/var/www/html /home/user1/mnt fuse.sshfs identityfile=/home/user1/.ssh/adm1@wbserver,allow_other,_netdev 0 0
SSH key file path

SSH key file path

6. After editing, save the file, close the text editor, and reboot the computer. As you can see below, the SSHFS mount is available again after the reboot.

Checking the SSHFS mount after reboot

Checking the SSHFS mount after reboot

Testing the SSHFS Mount

So you’ve mounted the remote directory to your local computer. The question now is, “does it work?”. The quickest test to confirm is creating a new file and saving it to the SSHFS mount point. The file you created should then appear on the server.

By default, the /var/www/html folder on the webserver is empty. When you access the website hosted on https://wbserver, you’ll only see the default test page, like the screenshot below.

Viewing the default test page

Viewing the default test page

In this example, you’ll create a new home page and confirm that the webserver displays that new page.

1. Switch the working directory to ~/mnt, the SSHFS mount point.

2. Execute the touch command to create an index.html file and open it in the text editor.

touch index.html && nano index.html

3. Now, populate the index.html file with the below HTML code, save the file, and exit the editor.

<h1>Welcome</h1>
<h2>I was put here over SSH by SSHFS</h2>

The screenshot below shows the expected content of the index.html file.

Creating the new home page

Creating the new home page

4. Lastly, open the website URL in your web browser again. The web server should pick up and display the new home page, as you can see below.

Updating the home page of a remote server via SSHFS mount

Updating the home page of a remote server via SSHFS mount

Congratulations! You’ve now successfully implemented the SSHFS mount on your Linux computer. You do not need to upload or download remote files to make changes manually.

Unmounting the Remote Directory

Suppose that you no longer need access to the remote directory via SSHFS mount and want to unmount it, run either the one of the below commands.

Run the command below if you mounted the remote directory interactively using the sshfs tool.

fusermount -u /home/user1/mnt

If you automounted the remote directory in fstab, run the command below instead. Additionally, you must remove the SSHFS automount entry in fstab. If not, the remote directory will automount again following a reboot.

sudo umount /home/user1/mnt

Using SSHFS Mount on Windows

Windows computers can map network locations as local drives, such as FTP sites, network shares, and SharePoint libraries. You’ll be glad to know that you can also add SSHFS mount drives in Windows by installing a program called SSHFS-Win — a port of SSHFS on Linux.

Installing WinFsp and SSHFS-Win

SSHFS-Win requires WinFsp to work as it provides the underlying FUSE functionality. Follow the below instructions to install both WinSfp and SSHFS-Win.

1. Open the browser on your Windows client and download the latest release of WinSfp (v1.10) and SSHFS-Win (v3.5.20357).

2. Locate the installers you downloaded and run the WinSfp installer first.

Starting the WinFsp installer

Starting the WinFsp installer

3. Click Next on the Welcome to the WinFsp 2022 Setup Wizard page.

Click Next on the Welcome page

Click Next on the Welcome page

4. Select all features and click Next.

Selecting the WinFsp features to install

Selecting the WinFsp features to install

5. Click Install on the Ready to install WinFsp 2022 page.

Install WinFsp

Install WinFsp

6. After the WinFsp installation, click Finish.

Finishing the WinFsp installation

Finishing the WinFsp installation

7. Next, start the SSHFS-Win installer.

Starting the WinSSHFS-Win installation

Starting the WinSSHFS-Win installation

8. Click Next on the first screen, as shown below, to start the installation process.

Starting the SSHFS-Win Setup program

Starting the SSHFS-Win Setup program

9. Click Next on the Custom Setup page.

Confirming installation settings

Confirming installation settings

10. On the Ready to install SSHFS-Win page, click Install.

Installing SSHFS-Win

Installing SSHFS-Win

11. Finally, click Finish to complete to exit the Setup Wizard.

Finishing the SSHFS-Win installation

Finishing the SSHFS-Win installation

Understanding the SSHFS Path Syntax

Before mapping a remote directory via SSHFS mount, review the list below to understand how SSHFS-Win interprets the remote paths.

\\\\PREFIX\\REMUSER@HOST[!PORT][\\PATH]
  • REMUSER is the remote user whose credentials you’ll use to authenticate with the remote server.
  • HOST is the hostname or IP address of the remote server.
  • PORT is the remote server’s SSH listening port. This value is optional, and the default is port 22.
  • PATH is the remote path relative to the PREFIX. The different prefixes are:
    • sshfs – maps to the path relative to the user’s home directory (i.e., HOST:~REMUSER/PATH).
    • sshfs.r – maps to a path relative to the host’s root directory (i.e., HOST:/PATH)
    • sshfs.k – maps to the path relative to the user’s home directory (i.e., HOST:~REMUSER/PATH) and uses SSH key-based authentication. This prefix uses the key in %USERPROFILE%/.ssh/id_rsa for authentication.
    • sshfs.kr – maps to a path relative to the host’s root directory (i.e., HOST:/PATH) and uses the key in %USERPROFILE%/.ssh/id_rsa for authentication.

Mounting and Unmounting the Remote Directory using the Windows File Explorer

One way to map a network drive in Windows is through the Windows File Explorer. With this method, you do not have to run any commands, and you’ll do every step in a wizard-style GUI.

1. Open a File Explorer window, click This PC —> Computer —> Map network drive.

Clicking Map network drive

Clicking Map network drive

2. Choose a Drive letter and type the below path into the Folder box to mount the \var\www\html folder.

\\sshfs.r\adm1@wbserver\var\www\html

Leave the Reconnect at sign-in option checked, and click Finish.

Choosing a drive letter and specifying the remote folder path

Choosing a drive letter and specifying the remote folder path

3. Enter the account password, check the Remember me box, and click OK.

Specifying the remote account credentials

Specifying the remote account credentials

You have now mapped an SSHFS mount with a drive letter. And because you enabled the Reconnect at sign-in and Remember me options, Windows will reconnect the SSHFS mount after restarting the computer.

Viewing the mapped SSHFS mount in Windows File Explorer

Viewing the mapped SSHFS mount in Windows File Explorer

4. At this point, you can now manage the files on the remote directory. But, if you no longer need the mapped drive and want to remove it, right-click the SSHFS mount and click Disconnect.

Removing the mapped drive

Removing the mapped drive

Mounting and Unmounting the Remote Directory using the Command Line

The net use command is another way to map a remote directory in Windows. Mapping SSHFS mount drives via the command line is helpful for scripting and automation.

To mount the remote directory, open the Command Prompt or PowerShell and run the below command to map the \\var\\www\\html remote directory to the local computer’s drive Z. Make sure to change the PASSWORD value with the remote user’s password.

net use Z: \\\\sshfs.r\\adm1@wbserver\\var\\www\\html PASSWORD /user:adm1
Creating the SSHFS mount using the command line

Creating the SSHFS mount using the command line

To remove the SSHFS mount drive using the command line, delete the mapping to drive Z: by running the below command.

Removing the SSHFS mount drive

Testing the SSHFS Mount

Now that you have access to a locally mapped network drive, you can manage the files on the remote directory as you would any other local files. In this example, you will update the website’s home page directly from the mapped SSHFS drive.

1. Open the File Explorer and navigate to the mapped drive.

2. Open the file called index.html in a text editor like notepad. If the file does not exist, create it first.

Opening the file in notepad

Opening the file in notepad

3. Copy the HTML code below, paste it into your index.html and save the file.

<h1>Welcome</h1>
<h2>I was put here over SSH by SSHFS</h2>
<h3>Brought to You from Windows 10</h3>
Updating the HTML code

Updating the HTML code

4. Lastly, open your web browser and navigate to the website URL HTTP://wbserver. You should now see the updated home page you edited, confirming that your SSHFS mount works as intended.

Viewing the updated home page

Viewing the updated home page

Conclusion

You’ve finally reached the end of this tutorial. You’ve learned to use the SSHFS mount to map directories to your local Windows or Linux computer from a remote SSH server. SSHFS is an excellent tool for convenience and remote file access security.

Speaking of security, perhaps you should check out How To Secure SSH with Fail2Ban as a next step? Good luck!

В случае, если вам потребовался доступ из Windows к данным на разделе диска с файловой системой Linux — ext4/ext3/ext2, встроенными средствами системы сделать это не получится. Однако, возможности есть, причем реализовать это можно встроенными средствами системы или с помощью сторонних инструментов.

В этой инструкции подробно о способах подключить раздел диска в файловой системе Linux в Windows 11 и Windows 10 для доступа к данным на этом разделе как для чтения, так и для записи.

Ext2 File System Driver (Ext2Fsd) — самый простой способ открыть раздел ext4/ext3/ext2 в Windows

Ext2 File System Driver или Ext2Fsd — сторонний и полностью бесплатный драйвер для подключения разделов Linux во всех версиях Windows начиная с XP. Несмотря на название, поддерживаются не только разделы не только с файловой системой ext2, но и более новые ext4 и ext3.

Порядок использования Ext2 File System Driver для доступа к дискам Linux будет следующим:

  1. Загрузите установщик Ext2Fsd с сайта https://sourceforge.net/projects/ext2fsd/
  2. Установите драйвер, в параметрах установки как правило не требуется ничего изменять.
  3. По завершении установки вам будет предложено запустить Ext2 Volume Manager (менеджер томов), запустите его.
  4. Нажмите правой кнопкой мыши по разделу Linux ext4, ext3, ext2 и выберите пункт «Assign Drive Letter» — назначить букву диска.
    Назначение буквы диска в Ext2Fsd

  5. Для раздела будет автоматически назначена буква диска, и вы увидите раздел в Проводнике Windows с возможностью чтения и записи файлов на нём.
    Раздел Ext4 подключен в Windows с помощью Ext2Fsd

В дальнейшем вы тем же способом сможете удалить букву диска с раздела (опция «Change letter» — «Remove»).

Доступ к разделам Linux средствами Подсистемы Windows для Linux (WSL)

Подсистема Windows для Linux (WSL) также может быть использована для подключения дисков Linux в Windows таким образом, чтобы доступ к ним был возможен из проводника. Шаги будут следующими:

  1. Запустите командную строку, Терминал или PowerShell от имени администратора и по порядку введите команды
    wsl --install
    wsl --set-default-version 2
    dism.exe /online /enable-feature /featurename:VirtualMachinePlatform /all /norestart
    wsl --install -d Ubuntu
    Установка Ubuntu в WSL в Windows

  2. После выполнения последней команды откроется окно консоли Linux (командную строку при этом не закрывайте, она еще пригодится) с предложением настроить имя пользователя и пароль, сделайте это. Если в окне консоли вы увидите сообщение об ошибке, скачайте и установите обновление WSL, перезагрузите компьютер и запустите Ubuntu из меню «Пуск».
  3. В консоли Ubuntu введите команду
    sudo mkdir -p /mnt/ext-drives/

    для создания папки, к которой будут монтироваться диски.

    Создать папку для монтирования дисков в WSL

  4. В консоли Windows (командная строка, терминал, Powershell) введите команду
    wmic diskdrive list brief
  5. Обратите внимание на DeviceID диска, который нужно подключить и введите команду (так же в консоли Windows) указав соответствующий номер в имени PHYSICALDRIVE
    wsl --mount \\.\PHYSICALDRIVE
    Подключить устройство к WSL в Windows

  6. В консоли Ubuntu введите команду lsblk — это отобразит список подключенных дисков, разделов на них и их размер. В следующей команде используем имя нужного раздела для монтирования:
    sudo mount /dev/sdИМЯ /mnt/ext-drives/
    Подключить диск Ext4 в Ubuntu в WSL

  7. После успешного выполнения всех указанных шагов вы можете зайти в Проводник Windows, выбрать пункт «Linux» в панели быстрого доступа, перейти в папку mnt\ext-drives и получить доступ к файлам на подключенном разделе Linux с возможностью записи и чтения.
    Раздел Ext4 из Подсистемы Windows для Linux виден в проводнике

В дальнейшем для отключения диска от WSL можно использовать ту же команду, которая использовалась на 5-м шаге, заменив mount на unmount.

Есть и другие программы (драйверы) для доступа к разделам Linux из Windows, но не полностью бесплатные. Среди них:

  • DiskInternals Linux Reader — в бесплатной версии доступно только чтение данных с разделов.
  • Paragon Linux File Systems for Windows — бесплатная работа в течение пробной версии, затем необходимо приобретать лицензию.

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Назначить учетной записи статус пред windows 2000 компьютера
  • Название службы защитник windows
  • Смена назначения разъемов realtek windows 10 не работает
  • Программная оболочка windows norton commander linux wdm драйвер
  • Windows system32 taskhostw exe