- Монтируем удаленную файловую систему через SSH.
- Подключение и настройка SSHFS в Linux
- Подключение SSHFS в Linux
- Автоматическое монтирование SSHFS
- Выводы
- 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:
- Using SSHFS to Mount Remote Directories
- Before You Begin
- Install SSHFS
- Setting Up your Linux Client
- Mounting the Remote File System
- Persistent Mounts
- Set Up Key-Based Authentication for SSH
- Update fstab
- Next Steps
- More Information
Монтируем удаленную файловую систему через SSH.
Во время работы часто приходится работать с удаленными файлами, часто через ssh. Gnome позволяет подключиться и работать с данными с помощью утилиты Places->Connect to Server, но, к сожалению, таким образом могут работать не все программы… Vim, например, а так как это основной мой редактор — я искал способ сделать это. И нашел 🙂
Все, что написано дальше — касается Linux, в частности Ubuntu Linux.
Итак, способ: смонтировать удаленую систему так же, как вы монтируете локальные диски. Сделать такое возможно с поомщью утилиты sshfs.
Для начала надо ее установить вместе с несколькими зависимостями:
$sudo apt-get install sshfs
Потом нужно добавить себя в группу пользователей fuse. Сделать это надо, потому что программа устанавливвается в системные папки, в которые обычным пользователям доступ запрещен. Так, добавляем себя в группу:
$sudo adduser fuse
Потом создаем директорию для монтирования, например, на рабочем столе:
Теперь надо выйти с терминала и зайти вновь. Все, теперь мы в группе fuse. Пробуем соединиться с сервером:
Если соединение идет не по ключу то, скорее всего, у вас появится запрос на введение пароля с удаленной машины.
Если же вы сразу не получили ошибку fusermount: fuse device not found, try ‘modprobe fuse’ first — проверяйте директорию, там должны появиться файлики :). Если же вылезла ошибка — значит модуль ядра fuse не загрузился автоматом, пробуем загрузить вручную:
$sudo modprobe fuse
Пробуем установить соединение еще раз.
Чтобы отмонтировать это все дело, надо выполнить следующее:
Чтобы каждый раз не вводить такую кучу комманд — создаем(если нету) и редактируем файл
/.bash_aliases, добавляя в конец такие строчки:
alias testssh=’sshfs user@example.com:/stuff
/Desktop/test_ssh’
alias testssh_umount=’fusermount -u
Теперь вы сможете монтировать удаленную машину командой testssh, а размонтировать — testssh_umount 🙂
Cпасибо за внимание!
ЗЫ Статью сначала перевел с английского на украинский, добавил немного своего и перевел на русский для Хабра 🙂
Источник
Подключение и настройка SSHFS в Linux
Файловая система SSHFS (Secure Shell FileSystem) позволяет монтировать файловую систему удалённого сервера с помощью протокола SSH. Это может быть очень удобно, если вам надо передать на удалённый сервер много данных или скачать эти данные оттуда. Конечно, существует утилита scp, но иногда просматривать файловую систему в файловом менеджере намного удобнее.
В этой небольшой статье мы рассмотрим как выполняется подключение SSHFS в Linux, а также как настроить автоматическое монтирование этой файловой системы при загрузке.
Подключение SSHFS в Linux
Для работы файловой системы достаточно SSH доступа к удалённому серверу. На клиентской машине надо установить пакет sshfs. Если он не установлен, команда установки в Ubuntu будет выглядеть следующим образом:
sudo apt install sshfs
Монтирование SSHFS выполняется с помощью одноимённой команды. Её синтаксис такой:
$ sshfs опции имя_пользователя @ адрес : /путь /точка/монтирования
Например, чтобы примонтировать удалённую файловую систему по адресу 192.168.56.103 от имени пользователя root достаточно выполнить:
sudo sshfs root@192.168.56.103:/ /mnt
Теперь вы сможете просмотреть содержимое файловой системы. Но здесь есть одно несколько минусов, во первых — не всегда удобно монтировать файловую систему от имени суперпользователя, а во вторых примонтированная файловая система будет доступна для чтения и записи только суперпользовтелю.
Чтобы получить возможность монтировать от имени обычного пользователя необходимо создать группу fuse:
sudo groupadd fuse
Затем добавить текущего пользователя в эту группу:
sudo usermod -aG fuse $USER
После этого перелогиньтесь в системе, чтобы изменения применились. От имени обычного пользователя вы не сможете примонтировать sshfs в /mnt потому что у вас нет права записи в эту папку, создайте папку для монтирования в домашней папке:
Далее можно пытаться монтировать:
Теперь вы можете использовать эту папку для того чтобы обмениваться файлами с сервером. Если надо чтобы и другие пользователи могли получать доступ к этой папке, надо использовать опцию allow_other. Она будет работать только если в файле /etc/fuse.conf присутствует опция user_allow_other. Добавьте её:
sudo vi /etc/fuse.conf
Теперь можно монтировать:
sshfs -o allow_other root@192.168.56.103:/
Для того чтобы отмонтировать файловую систему используйте привычную команду umount:
Автоматическое монтирование SSHFS
Вы можете настроить автоматическое монтирование SSHFS в файле /etc/fstab. Для этого сначала вам придется создать SSH ключ и отправить его на удалённый сервер. Создайте новый ключ:
Затем передайте его на сервер:
Когда ключ будет загружен, будет достаточно передать утилите в опциях монтирования путь к ключу. Чтобы убедится, что всё работает выполните:
sshfs -o identityfile=
Если всё работает, можно составить сточку конфигурации для /etc/fstab:
sudo vi /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 текущего пользователя:
cat /etc/passwd | grep $USER
В данном случае, это 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. Как видите, это не очень сложно, но в то же время удобно для передачи большого количества файлов.
Источник
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.
Источник
Using SSHFS to Mount Remote Directories
SSHFS (Secure Shell FileSystem), is a tool that allows users to securely access remote filesystems over the SSH protocol. This guide will get you started with SSHFS on your Linode. SSHFS can eliminate the need to use FTP/SFTP to transfer files to and from a remote server.
Before You Begin
This guide will assume you have two systems set up:
A remote system running Ubuntu 18.04 which will serve your files over SSH.
A client system which will connect to the remote server using SSHFS. This system also runs Ubuntu 18.04.
Limited Linux users (non- root ) with the same username should also exist on both systems. If you have not already set up a limited user, review the How to Secure your Server guide.
The username for this limited user is assumed to be example_user . Replace all instances of example_user in this guide with your limited user’s name. As well, the IP address of the remote system is assumed to be 192.0.2.4 , so replace all instances of this IP with your remote system’s address.
Install SSHFS
Log in to your client system and update your packages:
Setting Up your Linux Client
In order to mount file systems using SSHFS from a normal user account, you’ll need to add the user to the fuse group first.
To check if the fuse group exists run:
If the group exists, execute the following command with sudo , substituting your user account name in place of example_user :
If the group does not exist it has to be created and the user added to the fuse group:
Log out from the client system and log back in to activate the group membership.
Mounting the Remote File System
You can use the command sshfs to mount a remote filesystem. The syntax for mounting a filesystem with sshfs is:
Create a directory as a destination for the mounted folder.
Mount the home directory of the remote system’s user to the new directory on your client system:
List the contents of the mounted directory. You should see the content of the folder that was mounted on the remote system:
To unmount the filesystem, use the umount command:
Persistent Mounts
To keep your server’s directory mounted on your system through reboots, create a persistent mount. This is accomplished by updating your system’s /etc/fstab file.
Set Up Key-Based Authentication for SSH
When setting up a mount listed in /etc/fstab , your client system will not be able to accept a password for the SSH connection. Instead, you can use public/private keypairs to authenticate with the remote server. This section describes how to create a keypair if you do not already have one.
This command will overwrite an existing RSA key pair, potentially locking you out of other systems.
If you’ve already created a key pair, skip this step. To check for existing keys, run ls
If you accidentally lock yourself out of your Linode, use Lish to update your authorized_keys file and regain SSH access.
Generate a keypair with the ssh-keygen command; accept the default values for the options it presents:
From the client system, copy your new public SSH key to the remote user’s authorized_keys file:
If your system is older, this file may be named authorized_keys2 . Consult your Linode’s /etc/ssh/sshd_config if you are unsure:
At this point, you should be able to log into the remote server as example_user without entering a password. Confirm this:
Update fstab
On a new line, add a mount directive to your /etc/fstab file which matches the following syntax:
Reboot your system. Then, list the contents of the mounted directory. You should see the content of the folder that was mounted on the remote system:
Next Steps
After completing this guide you will be able to transfer files to a remote server from your client machine without using an FTP client. If you still want to learn how to use an FTP client, check out our guide: Transfer Files with FileZilla.
More Information
You may wish to consult the following resources for additional information on this topic. While these are provided in the hope that they will be useful, please note that we cannot vouch for the accuracy or timeliness of externally hosted materials.
This page was originally published on Monday, October 26, 2009.
Источник