- Как использовать SSHFS для монтирования удаленных каталогов через SSH
- Установка SSHFS
- Установка SSHFS в Ubuntu и Debian
- Установка SSHFS на CentOS
- Установка SSHFS на macOS
- Установка SSHFS в Windows
- Монтирование удаленной файловой системы
- Монтирование удаленной файловой системы в Windows
- Размонтирование удаленной файловой системы
- Заключение
- Best way to mount remote folder
- 4 Answers 4
- Mount remote directory using SSH
- 7 Answers 7
- Not the answer you’re looking for? Browse other questions tagged mount ssh sshfs or ask your own question.
- Linked
- Related
- Hot Network Questions
- Subscribe to RSS
- How to Mount Remote Linux Filesystem or Directory Using SSHFS Over SSH
- What Is SSHFS?
- Step 1: Install SSHFS Client in Linux Systems
- Step 2: Creating SSHFS Mount Directory
- Step 3: Mounting Remote Filesystem with SSHFS
- Step 4: Verifying Remote Filesystem is Mounted
- Step 5: Checking Mount Point with df -hT Command
- Step 6: Mounting Remote Filesystem Permanently
- Step 7: Unmounting Remote Filesystem
- If You Appreciate What We Do Here On TecMint, You Should Consider:
Как использовать SSHFS для монтирования удаленных каталогов через SSH
Главное меню » Операционная система Linux » Как использовать SSHFS для монтирования удаленных каталогов через SSH
По сравнению с другими протоколами сетевой файловой системы, такими как NFS и Samba, преимущество SSHFS заключается в том, что он не требует какой-либо дополнительной настройки на стороне сервера. Для использования SSHFS вам нужен только SSH-доступ к удаленному серверу.
Поскольку SSHFS использует SFTP, все передаваемые данные между сервером и клиентом должны быть зашифрованы и расшифрованы. Это приводит к слегка ухудшенной производительности по сравнению с NFS и более высокой загрузке ЦП на клиенте и сервере.
Из этой статьи вы узнаете, как установить клиент SSHFS в Linux, macOS и Windows и как смонтировать удаленный каталог.
Установка SSHFS
Пакеты SSHFS доступны для всех основных операционных систем, и установка довольно проста.
Установка SSHFS в Ubuntu и Debian
SSHFS доступен из репозиториев Ubuntu и Debian по умолчанию. Обновите индекс пакетов и установите клиент sshfs, набрав:
Установка SSHFS на CentOS
В CentOS и других производных Red Hat для установки sshfs выполните следующую команду:
Установка SSHFS на macOS
Пользователи macOS могут установить клиент SSHFS, загрузив пакеты FUSE и SSHFS с сайта osxfuse или через Homebrew:
Установка SSHFS в Windows
Пользователям Windows необходимо установить два пакета, WinFsp и SSHFS-Win.
Монтирование удаленной файловой системы
Следующие инструкции применимы для всех дистрибутивов Linux и macOS.
Чтобы смонтировать удаленный каталог, пользователь SSH должен иметь доступ к нему. Команда монтирования SSHFS имеет следующий вид:
Команда sshfs прочитает файл конфигурации SSH и будет использовать настройки для каждого хоста. Если удаленный каталог не указан, по умолчанию используется домашний каталог удаленного пользователя.
Например, чтобы смонтировать домашний каталог пользователя с именем «andreyex» на удаленном хосте с IP-адресом «192.168.111.011», сначала создайте каталог, который будет служить точкой монтирования, это может быть любое местоположение:
Затем используйте команду sshfs для монтирования удаленного каталога:
Вам будет предложено ввести пароль пользователя. Чтобы избежать ввода пароля каждый раз, когда вы монтируете удаленный каталог, генерируйте SSH-ключи и настраивайте Passwordless SSH Login.
Теперь вы можете взаимодействовать с каталогами и файлами, расположенными на удаленном сервере, так же, как и с локальными файлами. Например, вы можете редактировать, удалять, переименовывать или создавать новые файлы и каталоги.
Если вы хотите автоматически монтировать удаленный каталог, вам нужно отредактировать файл /etc/fstab локального компьютера и добавить новую запись о монтировании. Таким образом, когда ваша система загружается, она автоматически монтирует удаленный каталог.
Чтобы смонтировать удаленный каталог через SSHFS /etc/fstab, используйте fuse.sshfs в качестве типа файловой системы.
При создании постоянного монтирования убедитесь, что вы можете подключить удаленный хост с использованием аутентификации на основе ключа SSH.
Монтирование удаленной файловой системы в Windows
Пользователи Windows могут использовать проводник Windows для сопоставления сетевого диска с удаленным каталогом на сервере SSH.
Откройте проводник Windows, щелкните правой кнопкой мыши «Мой компьютер» и выберите «Подключить сетевой диск». Выберите диск для монтирования и в поле «Папка» введите удаленного пользователя, сервер и путь в следующем формате:
На момент написания этой статьи SSHFS-Win не поддерживает аутентификацию на основе ключей, поэтому необходимо настроить удаленный ssh-сервер для принятия аутентификации на основе пароля.
Размонтирование удаленной файловой системы
Чтобы отсоединить смонтированную файловую систему, используйте команду umount или, fusermount а затем каталог, в котором она была смонтирована (точка монтирования):
Заключение
Из этой статьи вы узнали, как использовать SSHFS для монтирования удаленного каталога через SSH. Это может быть полезно, когда вы хотите взаимодействовать с удаленными файлами с помощью приложений на локальном компьютере.
Для получения полного списка опций sshfs введите man sshfs в свой терминал.
Возможно, вы также захотите ограничить доступ пользователей к их домашнему каталогу, настроив среду SFTP Chroot Jail и изменив порт SSH по умолчанию, чтобы добавить дополнительный уровень безопасности вашему серверу.
Если у вас есть какие-либо вопросы или отзывы, не стесняйтесь оставлять комментарии.
Если вы нашли ошибку, пожалуйста, выделите фрагмент текста и нажмите Ctrl+Enter.
Best way to mount remote folder
I have two RasberryPi running debian wheezy and I would like to mount a folder from computer A on computer B.
What is the best (as in most efficient) way to do this?
I can do it via SMB, but that is for windows, I think there must be a better way to share across linux.
4 Answers 4
You can use plenty of things, among which, popular options are:
By ease-of-setup I think they would have to be put in this order (top: easiest)
SSHFS
Through FUSE, you can mount remote filesystems via ssh. I won’t cover how, as Cristopher has already very well explained that. Just note that, in order to mount the file automatically it will need a bit more of work.
Samba
It will allow you to use Windows and Unix machines to access the remote folder. If it’s not a big deal for you, then you won’t probably benefit from it. However, it’s easy to automount it on init (just input the apropriate values at /etc/fstab , including username= ,password= in the options column.
NFS
It will let you authenticate just via IP (no usernames thing = faster, only of use inside your non-hostile LAN) or via Kerberos Tickets (too painful for just two Raspberries; but useful in corporate environments).
As it has kernel mode support, it will run faster than sshfs. Besides, as there’s no encryption performed it will have a better throughput, and in the case of the tiny Raspberry ARM, it may make a difference.
Besides, it’s not so painful to setup simply you trust your network. You have automount support in /etc/fstab too, and you don’t have to put sensitive data (such as usernames or passwords), and if you have your usernames syncrhronized (same /etc/passwd and /etc/group files) you can use the usual POSIX permissions toolset ( chown , chgrp and chmod ).
SSHFS is wonderful. It can mount remote directories in a local directory with FUSE. The commands below use # to indicate that a command was executed as root , while $ indicates execution as a regular user. Because FUSE software is required, first make sure that it is available and running.
One of the lsmod and grep commands, below, can reveal if the software is loaded and ready for use. A result from either command indicates that fuse is available.
If there is no result from either command, try to load the kernel module without a reboot using modprobe and check again.
If loading the module fails, install the software with apt-get .
Check again after installation.
FUSE must be installed and running before continuing.
Check the permissions of /dev/fuse . The permissions should provide your regular user account with read and write access. Skip this part if you have determined that your regular user account already has read and write permission on /dev/fuse .
The output might be something like one of the following.
In 2013, my Debian created /dev/fuse with 0600 permissions, owner root , group owner fuse . I needed to let the fuse group use the device and to add my regular user account to the group, as shown below.
If the new group membership was required, log out and in again to become a member of the group.
Next, install ssh on both sides as follows.
This answer was written for Debian, but on Ubuntu 18.x at least, openssh-client , fuse , and a few other packages are a part of the Ubuntu sshfs package. The sshfs software is required on the client side, but it can be installed on both sides if desired. One of the package dependencies is fuse , but the installer skips over software that has already been installed.
With fuse and ssh available, and with permission to use the device, /dev/fuse , create a mount point for the remote file system; and, mount that remote filesystem locally as follows.
To mount a directory other than home, specify it after the colon.
To unmount, use fusermount .
If you have a Windows machine, it too can use SSHFS with win-sshfs. This software will «map a drive» with SSHFS, so that you can have a Windows drive letter that contains the remote directory.
Mount remote directory using SSH
How to mount a remote directory using SSH to be available same as if it is a local directory?
7 Answers 7
First install the module:
Load it to kernel:
Setting permissions (Ubuntu versions remoteDir .
Now I ran the command to mount it (mount on home):
Now it should be mounted:
Configure ssh key-based authentication
Generate key pair on the local host.
Accept all sugestions with enter key.
Copy public key to the remote host:
Install sshfs
Mount remote directory
Don’t try to add remote fs to /etc/fstab
Or don’t try to mount shares via /etc/rc.local .
In both cases it won’t work as the network is not available when init reads /etc/fstab.
Install AutoFS
Edit /etc/auto.master
Comment out the following lines
Edit /etc/auto.sshfs
Remote user name is obligatory.
Start autofs in debug mode
Observe logs of the remote ssh server
Check content of the local directory
You should see contents of the remote directory
Start autofs in normal mode
Stop AutoFS running in debug mode with CTRL-C .
Start AutoFS in normal mode
Enjoy
(Tested on Ubuntu 14.04)
Based on my experiments, explicitly creating the fuse group and adding your user to it is NOT required to mount ssh file system.
To summarize, here are the steps copied from this page:
$ sudo apt-get install sshfs
2.Create local mount point
3.Mount remote folder /remote/path to /home/johndoe/sshfs-path/
$ sshfs remoteuser@111.222.333.444:/remote/path /home/johndoe/sshfs-path/
$ fusermount -u /home/johndoe/sshfs-path/
sudo apt-get install sshfs
Although it is not answering your question exactly but I just wanted to mention that you can achieve the same goal using «sftp» as well. Just inside your file manager address bar type this command:
I would like to warn that, it seems that by default only the user which set up the mount can access the remote directory.
I set up a remote directory, and create a crontab with sudo crontab -e . Later I found out the backup file didn’t write the remote directory at all. Then I found out that I could not cd into the remote disk as root ! So eventually I create the same task with crontab -e and everything works as I expected.
An easy way to run sshfs mounts at startup is also by adding it to the root (or another user’s) crontab, like this:
And if you need to add a delay, you can use:
Not the answer you’re looking for? Browse other questions tagged mount ssh sshfs or ask your own question.
Linked
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.4.16.39093
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
How to Mount Remote Linux Filesystem or Directory Using SSHFS Over SSH
The main purpose of writing this article is to provide a step-by-step guide on how to mount remote Linux file system using SSHFS client over SSH.
This article is useful for those users and system administrators who want to mount remote file system on their local systems for whatever purposes. We have practically tested by installing SSHFS client on one of our Linux system and successfully mounted remote file systems.
Before we go further installation let’s understand about SSHFS and how it works.
Sshfs Mount Remote Linux Filesystem or Directory
What Is SSHFS?
SSHFS stands for (Secure SHell FileSystem) client that enable us to mount remote filesystem and interact with remote directories and files on a local machine using SSH File Transfer Protocol (SFTP).
SFTP is a secure file transfer protocol that provides file access, file transfer and file management features over Secure Shell protocol. Because SSH uses encryption while transferring files over the network from one computer to another computer and SSHFS comes with built-in FUSE (Filesystem in Userspace) kernel module that allows any non-privileged users to create their file system without modifying kernel code.
In this article, we will show you how to install and use SSHFS client on any Linux distribution to mount remote Linux filesystem or directory on a local Linux machine.
Step 1: Install SSHFS Client in Linux Systems
By default sshfs packages does not exists on all major Linux distributions, you need to enable epel repository under your Linux systems to install sshfs with the help of Yum command with their dependencies.
Step 2: Creating SSHFS Mount Directory
Once the sshfs package installed, you need to create a mount point directory where you will mount your remote file system. For example, we have created mount directory under /mnt/tecmint .
Step 3: Mounting Remote Filesystem with SSHFS
Once you have created your mount point directory, now run the following command as a root user to mount remote file system under /mnt/tecmint . In your case the mount directory would be anything.
The following command will mount remote directory called /home/tecmint under /mnt/tecmint in local system. (Don’t forget replace x.x.x.x with your IP Address and mount point).
If your Linux server is configured with SSH key based authorization, then you will need to specify the path to your public keys as shown in the following command.
Step 4: Verifying Remote Filesystem is Mounted
If you have run the above command successfully without any errors, you will see the list of remote files and directories mounted under /mnt/tecmint .
Step 5: Checking Mount Point with df -hT Command
If you run df -hT command you will see the remote file system mount point.
Sample Output
Step 6: Mounting Remote Filesystem Permanently
To mount remote filesystem permanently, you need to edit the file called /etc/fstab . To do, open the file with your favorite editor.
Go to the bottom of the file and add the following line to it and save the file and exit. The below entry mount remote server file system with default settings.
Make sure you’ve SSH Passwordless Login in place between servers to auto mount filesystem during system reboots..
If your server is configured with SSH key based authorization, then add this line:
Next, you need to update the fstab file to reflect the changes.
Step 7: Unmounting Remote Filesystem
To unmount remote filesystem, jun issue the following command it will unmount the remote file system.
That’s all for now, if you’re facing any difficulties or need any help in mounting remote file system, please contact us via comments and if you feel this article is much useful then share it with your friends.
If You Appreciate What We Do Here On TecMint, You Should Consider:
TecMint is the fastest growing and most trusted community site for any kind of Linux Articles, Guides and Books on the web. Millions of people visit TecMint! to search or browse the thousands of published articles available FREELY to all.
If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.
We are thankful for your never ending support.