Remote file system in linux

How to Mount Remote File System over SSH in Linux

Working with remote servers is a common practice in the world of Linux. To manage files and directories on remote systems, you often need to access their file systems. One secure and efficient method for accomplishing this is by mounting the remote file system over SSH (Secure Shell). This guide will walk you through the process of mounting a remote file system over SSH in Linux, enabling you to access and manipulate remote files as if they were on your local machine.

Prerequisites

Before we begin, you will need the following:

  • A Linux-based operating system installed on your local machine.
  • A remote server running Linux with SSH access.
  • SSH keys or a password for authentication.
  • SSHFS (SSH File System) package installed on your local machine.

Step 1: Installing SSHFS

SSHFS is a user-space file system client that allows you to mount remote directories over an SSH connection. To install SSHFS, use the package manager for your distribution:

    For Debian-based distributions (e.g., Ubuntu), use the following command:

sudo apt-get install sshfs 

Step 2: Creating a Mount Point

Before mounting the remote file system, you need to create a mount point on your local machine. This is the directory where the remote file system will be mounted. To create a mount point, use the “mkdir” command:

Источник

How to Mount a Remote Linux Filesystem Using SSHFS

We use the SSHFS command in Linux to mount a remote file system using SFTP (SSH File Transfer Protocol).

SSHFS is a filesystem client used to mount and interact with files and directories on a remote server. SSH protocol is used to encrypt data exchange between the two hosts.

FTP (File Transfer Protocol) is a networking protocol used to transfer files between two computers over a network, SFTP on the other hand in addition to performing a similar function to FTP, it incorporates a security layer used to encrypt the data being sent and received between the two machines over the internet.

Читайте также:  Vmware horizon client linux certificate

Now, how do the two tools work together? Well, SSHFS is just a file system in the user space, for it to perform the function of mounting a remote file system, it utilizes SFTP.

Installing SSHFS in Linux

SSHFS is a Linux-based software tool that is available to install from the standard repositories in most distributions using the default package manager.

$ sudo apt install sshfs [On Debian, Ubuntu and Mint] $ sudo yum install fuse-sshfs [On RHEL/CentOS/Fedora and Rocky Linux/AlmaLinux] $ sudo emerge -a net-fs/sshfs [On Gentoo Linux] $ sudo pacman -S sshfs [On Arch Linux] $ sudo zypper install sshfs [On OpenSUSE]

Mounting the Remote Linux File System

For this to work, the remote server needs to be reachable therefore perform some ping requests. We should also make sure that we have the server credentials e.g password.
SSH also needs to be configured on both the server and client machines.

The syntax for the command is:

$ sshfs [user@]host:[dir] mountpoint [options]
  • user – This specifies the username on the server. When connected via SSH, we are prompted for a password for the remote user account with the specified username.
  • host – We specify the hostname of the remote server, we could specify a domain name e.g www.example.com which is easier to recall or an IP address.
  • dir – This specifies the path of the remote directory.
  • mountpoint: This specifies the location in which we want our file system to be mounted, Note that this is in our local system. Normally file systems are mounted in the /mnt directory.

The image below shows the IP address and file system of the remote server we want to mount to our local system.

Remote Linux Filesystem

On our local system, let’s create a directory preferably in the /mnt directory where we will mount the remote file system:

Now to mount the remote Linux file system that is located at 192.168.100.62 at /home/user directory, we write:

When we execute the above command we are prompted for a password for the remote system user account which we have specified within the command.

Mount Remote Linux Filesystem

After the password is accepted the remote file system is mounted on our local system on the selected mount point /mnt/remoteFS. Note that we have used the -o allow_other option to allow other users to read and write to the mounted file system.

Читайте также:  How to 32 or 64 bit linux

To verify that the remote Linux file system is mounted, run:

Check Remote Linux Filesystem

From the above image, we list the remote file system which is now mounted on our local machine. You can also check its mount point in our local system by using.

Check Remote Linux Filesystem Mounts

Caution: DON’T DELETE THE FILE SYSTEM!! – We should not delete the mounted file system as it will also be deleted on the remote server and we don’t want this.

Permanently Mounting the Remote Linux File System

The mounting we have seen thus far is only temporary, to mount the remote file system permanently, we edit the fstab file located in the /etc directory as follows:

After the file is open, paste the following line, remember to use details specific to your setup.

sshfs#[email protected]:/home/user/ /mnt/remoteFS fuse.sshfs defaults 0 0

Mounting Remote Linux File System Permanently

To mount the file execute the following command:

Now even if we are disconnected from the remote machine, the file system will remain mounted in the specified directory we had mounted it on previously.

Unmounting the Remote Linux File System

Suppose we are done with this filesystem we can unmount it using the umount command as follows:

We have learned how to mount a remote file system to our local machine and perform this over SSH protocol for security purposes. We have also seen how to mount the file system on our local system permanently by editing the /etc/fstab file.

Источник

Подключение и настройка SSHFS в Linux

Файловая система SSHFS (Secure Shell FileSystem) позволяет монтировать файловую систему удалённого сервера с помощью протокола SSH. Это может быть очень удобно, если вам надо передать на удалённый сервер много данных или скачать эти данные оттуда. Конечно, существует утилита scp, но иногда просматривать файловую систему в файловом менеджере намного удобнее.

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

Подключение SSHFS в Linux

Для работы файловой системы достаточно SSH доступа к удалённому серверу. На клиентской машине надо установить пакет sshfs. Если он не установлен, команда установки в Ubuntu будет выглядеть следующим образом:

Монтирование SSHFS выполняется с помощью одноимённой команды. Её синтаксис такой:

$ sshfs опции имя_пользователя @ адрес : /путь /точка/монтирования

Например, чтобы примонтировать удалённую файловую систему по адресу 192.168.56.103 от имени пользователя root достаточно выполнить:

Читайте также:  What is monitoring tools in linux

sudo sshfs root@192.168.56.103:/ /mnt

Теперь вы сможете просмотреть содержимое файловой системы. Но здесь есть одно несколько минусов, во первых — не всегда удобно монтировать файловую систему от имени суперпользователя, а во вторых примонтированная файловая система будет доступна для чтения и записи только суперпользовтелю.

Чтобы получить возможность монтировать от имени обычного пользователя необходимо создать группу fuse:

Затем добавить текущего пользователя в эту группу:

sudo usermod -aG fuse $USER

После этого перелогиньтесь в системе, чтобы изменения применились. От имени обычного пользователя вы не сможете примонтировать sshfs в /mnt потому что у вас нет права записи в эту папку, создайте папку для монтирования в домашней папке:

Далее можно пытаться монтировать:

sshfs root@192.168.56.103:/ ~/mnt

Теперь вы можете использовать эту папку для того чтобы обмениваться файлами с сервером. Если надо чтобы и другие пользователи могли получать доступ к этой папке, надо использовать опцию allow_other. Она будет работать только если в файле /etc/fuse.conf присутствует опция user_allow_other. Добавьте её:

sshfs -o allow_other root@192.168.56.103:/ ~/mnt

Для того чтобы отмонтировать файловую систему используйте привычную команду umount:

Автоматическое монтирование SSHFS

Вы можете настроить автоматическое монтирование SSHFS в файле /etc/fstab. Для этого сначала вам придется создать SSH ключ и отправить его на удалённый сервер. Создайте новый ключ:

Затем передайте его на сервер:

ssh-copy-id -i ~/.ssh/id_dsa.pub root@192.168.56.103

Когда ключ будет загружен, будет достаточно передать утилите в опциях монтирования путь к ключу. Чтобы убедится, что всё работает выполните:

sshfs -o identityfile=~/.ssh/id_dsa.pub root@192.168.56.103:/ ~/mnt

Если всё работает, можно составить сточку конфигурации для /etc/fstab:

root@192.168.56.103:/ /mnt fuse.sshfs noauto,x-systemd.automount,_netdev,follow_symlinks,identityfile=/home/sergiy/.ssh/id_dsa,allow_other,default_permissions,reconnect 0 0

Путь к файлу ключа должен быть полным, поэтому замените имя пользователя на своё. Для того, чтобы не получать ошибок доступа при записи желательно чтобы имя пользователя на локальной машине и на удалённой совпадали. Или же, можно указать ID пользователя и группы владельца во время монтирования. Сначала посмотрите UID и GID текущего пользователя:

В данном случае, это 1000. Первая цифра — это UID, вторая — GID. Затем передайте их в опциях монтирования uid и gid:

root@192.168.56.103:/ /mnt fuse.sshfs uid=1000,gid=1000,noauto,x-systemd.automount,_netdev,follow_symlinks,identityfile=/home/sergiy/.ssh/id_dsa,allow_other,default_permissions,reconnect 0 0

Теперь всё должно работать.

Выводы

Теперь вы знаете как выполняется подключение и настройка SSHFS Linux. Как видите, это не очень сложно, но в то же время удобно для передачи большого количества файлов.

Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.

Источник

Оцените статью
Adblock
detector