Mount ssh folder linux

dublado / sshfs.md

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.

# yum install sshfs # dnf install sshfs [On Fedora 22+ releases] $ sudo apt-get install sshfs [On Debian/Ubuntu based systems]

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.

# mkdir /mnt/tecmint $ sudo mkdir /mnt/tecmint [On Debian/Ubuntu based systems]

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

# sshfs tecmint@x.x.x.x:/home/tecmint/ /mnt/tecmint $ sudo sshfs -o allow_other tecmint@x.x.x.x:/home/tecmint/ /mnt/tecmint [On Debian/Ubuntu based systems]

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.

# sshfs -o IdentityFile=~/.ssh/id_rsa tecmint@x.x.x.x:/home/tecmint/ /mnt/tecmint $ sudo sshfs -o allow_other,IdentityFile=~/.ssh/id_rsa tecmint@x.x.x.x:/home/tecmint/ /mnt/tecmint [On Debian/Ubuntu based systems]

Step 4: Verifying Remote Filesystem is Mounted

Читайте также:  Alt linux как установить rpm

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.

[root@ tecmint]# ls 12345.jpg ffmpeg-php-0.6.0.tbz2 Linux news-closeup.xsl s3.jpg cmslogs gmd-latest.sql.tar.bz2 Malware newsletter1.html sshdallow epel-release-6-5.noarch.rpm json-1.2.1 movies_list.php pollbeta.sql ffmpeg-php-0.6.0 json-1.2.1.tgz my_next_artical_v2.php pollbeta.tar.bz2

Step 5: Checking Mount Point with df -hT Command

If you run df -hT command you will see the remote file system mount point.

Filesystem Type Size Used Avail Use% Mounted on udev devtmpfs 730M 0 730M 0% /dev tmpfs tmpfs 150M 4.9M 145M 4% /run /dev/sda1 ext4 31G 5.5G 24G 19% / tmpfs tmpfs 749M 216K 748M 1% /dev/shm tmpfs tmpfs 5.0M 4.0K 5.0M 1% /run/lock tmpfs tmpfs 749M 0 749M 0% /sys/fs/cgroup tmpfs tmpfs 150M 44K 150M 1% /run/user/1000 tecmint@192.168.0.102:/home/tecmint fuse.sshfs 324G 55G 253G 18% /mnt/tecmint

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.

# vi /etc/fstab $ sudo vi /etc/fstab [On Debian/Ubuntu based systems]

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.

sshfs#tecmint@x.x.x.x:/home/tecmint/ /mnt/tecmint fuse.sshfs defaults 0 0

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:

sshfs#tecmint@x.x.x.x:/home/tecmint/ /mnt/tecmint fuse.sshfs IdentityFile=~/.ssh/id_rsa defaults 0 0

Next, you need to update the fstab file to reflect the changes.

# mount -a $ sudo mount -a [On Debian/Ubuntu based systems]

Step 7: Unmounting Remote Filesystem

Читайте также:  Linux application memory usage

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.

Источник

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

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

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

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

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

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

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

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

sudo sshfs root@192.168.56.103:/ /mnt

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

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

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

sudo usermod -aG fuse $USER

Читайте также:  Driver asus touchpad linux

После этого перелогиньтесь в системе, чтобы изменения применились. От имени обычного пользователя вы не сможете примонтировать 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