- Подключение файловых систем. Команда mount в Linux
- Вывод списка смонтированных файловых систем(ФС)
- Монтирование файловой системы
- Примеры использования mount
- Монтирование USB-накопителя/жесткого диска
- Монтирование файлов ISO
- Монтирование NFS
- Размонтирование файловой системы
- Сохранение параметров mount после перезагрузки
- Заключение
- What is a mount point in Linux/Unix?
- So what actually a mount point is?
- What is a partition? What is formatting?
- Still did not get the mount concept?
- The analogy of this story to our disk management is as below.
- Some FAQ’s related to mount in Linux/Unix:
- Q. I lost my mount point,is my data lost in that partition?
- Q. I am M$ windows person and I do not see any mount point stuff, can you explain where is my mount point?
- Q How can I find mounted partitions in my machine?
- Mount point ��� linux
- 3.1.2.3. Mount points
Подключение файловых систем. Команда mount в Linux
В ОС Linux команда mount используется для подключения (монтирования) файловых систем и переносных накопителей (например, USB-флешек) к конкретным точкам монтирования в дереве директорий. Команда umount отключает (размонтирует) смонтированную файловую систему от дерева директорий. В данном руководстве мы рассмотрим основы подключения и отключения различных файловых систем при помощи команд mount и umount.
Вывод списка смонтированных файловых систем(ФС)
При выполнении без аргументов команда mount выведет все подключенные в данный момент ФС:
По умолчанию результат будет содержать все ФС, в том числе виртуальные, такие как cgroup, sysfs и т. д. Каждая строка содержит информацию об имени устройства, директории, в которой оно смонтировано, типе и опциях монтирования в следующей форме:
Для отображения только ФС определенного типа используется опция -t. Например, так можно отобразить только разделы ext4:
Монтирование файловой системы
Для подключения файловой системы к конкретному местоположению (точке монтирования) команда mount используется в следующей форме:
После подключения точка монтирования становится корневой директорией смонтированной ФС. Например, смонтировать жесткий диск /dev/sdb1 в директорию /mnt/media можно следующим образом:
Обычно при монтировании устройства с распространенной ФС, например, ext4 или xfs, команда mount автоматически определяет ее тип. Однако, некоторые ФС не распознаются. Их тип нужно указывать в явном виде. Для этого используется опция -t:
Чтобы указать дополнительные опции монтирования, используется флаг -o:
Можно указать несколько опций, разделенных запятыми (после запятых не должно быть пробелов). Ниже предоставлены основные опции команды
-V — вывести версию утилиты;
-h — вывести справку;
-v — подробный режим;
-a, —all — примонтировать все устройства, описанные в fstab;
-F, —fork — создавать отдельный экземпляр mount для каждого отдельного раздела;
-f, —fake — не выполнять никаких действий, а только посмотреть что собирается делать утилита;
-n, —no-mtab — не записывать данные о монтировании в /etc/mtab;
-l, —show-labels — добавить метку диска к точке монтирования;
-c — использовать только абсолютные пути;
-r, —read-only — монтировать раздел только для чтения;
-w, —rw — монтировать для чтения и записи;
-L, —label — монтировать раздел по метке;
-U, —uuid — монтировать раздел по UUID;
-T, —fstab — использовать альтернативный fstab;
-B, —bind — монтировать локальную папку;
-R, —rbind — перемонтировать локальную папку.
Полный список опций можно получить, выполнив команду man mount.
Примеры использования mount
Давайте рассмотрим несколько примеров использования утилиты. Как правило для монтирования нужно выполнить всего два действия
- Создать точку монтирования
- Примонтировать файловую систему
Монтирование USB-накопителя/жесткого диска
В большинстве современных дистрибутивов Linux, например, Ubuntu, USB-накопители автоматически монтируются при подключении, но иногда может потребоваться ручное монтирование устройства. Чтобы смонтировать USB-накопитель, выполните следующие действия.
Создайте точку монтирования
Если USB-накопитель использует устройство /dev/sdd1, его можно смонтировать в директорию /media/usb следующей командой:
Для поиска устройства и типа файловой системы можно воспользоваться любой из следующих команд:
Монтирование файлов ISO
Для монтирования файла ISO используется петлевое (loop) устройство — специальное виртуальное устройство, которое позволяет осуществлять доступ к файлу как к блочному устройству.
Сначала нужно создать точку монтирования в любой желаемой директории:
Смонтируйте файл ISO следующей командой:
Не забудьте заменить /path/to/image.iso на путь к вашему файлу ISO.
Монтирование NFS
Для монтирования системы NFS требуется установить клиент NFS. Установка клиента NFS в Ubuntu и Debian:
Установка клиента NFS в CentOS и Fedora:
Создайте директорию, которая будет точкой монтирования удаленной файловой системы:
Обычно требуется автоматическое монтирование удаленной директории NFS при загрузке. Для этого нужно изменить файл конфигурации /etc/fstab. Откройте его в любом текстовом редакторе, например:
Добавьте в файл следующую строку, заменив сервер:/директория на имя или IP-адрес сервера NFS и экспортируемую директорию:
Смонтируйте ресурс NFS следующей командой:
Размонтирование файловой системы
Для отключения смонтированной файловой системы используется команда umount, в качестве аргумента которой указывается директория, в которую она была смонтирована (точка монтирования) или имя устройства:
Если файловая система используется, umount не сможет ее отключить. В таких ситуациях можно воспользоваться командой fuser, чтобы выяснить, какие процессы осуществляют доступ к файловой системе:
Определив процессы, можно остановить их и размонтировать файловую систему. Также для отключения занятой файловой системы сразу после завершения ее использования можно воспользоваться опцией -l (—lazy, “ленивое” отключение):
Для принудительного размонтирования применяется опция -f (—force). Обычно она используется для отключения недостижимой системы NFS.
Во всех остальных случаях принудительное отключение нежелательно, так как может привести к повреждению данных в файловой системе.
Сохранение параметров mount после перезагрузки
Для того, что бы устройства при перезагрузки системы монтировались автоматически, необходимо прописать инструкции монтирования в файл /etc/fstab. Файл /etc/fstab содержит список записей в следующем формате:
Подключит устройство /dev/sdb1 (например жесткий диск) в директорию /home
После того как инструкция для mount прописаны в /etc/fstab, что бы проверить правильность написания дайте команду
Если команда отработает без ошибок, то все устройства прописанные в /etc/fstab будут подключены, а также изменения не потеряются после перезагрузки.
Заключение
Мы рассмотрели наиболее распространенные примеры подключения различных файловых систем к дереву директорий при помощи команды mount и их отключения командой umount. Для получения более подробной информации об опциях команд mount и umount можно обратиться к соответствующим man-страницам.
Если вы нашли ошибку, пожалуйста, выделите фрагмент текста и нажмите Ctrl+Enter.
Источник
What is a mount point in Linux/Unix?
Mounting takes place before a computer can use any kind of storage device (such as a hard drive, CD-ROM, or network share). The user or their operating system must make it accessible through the computer’s file system. A user can only access files on mounted media —From Wikipedia.
From the above statement only a geek can understand what a mount point is and for the people who are new to Linux/Unix cannot understand it in one shot and they have to do a bit of research on it to understand. This post is for new people who are just going to learn disk management and Linux. All the advanced users can ignore this post if you people know the meaning of mount point in Linux.
So what actually a mount point is?
In simple words a mount point is a directory to access your data (files and folders) which is stored in your disks.
To understand a mount, we should know two more concepts
What is a partition?
What is formatting?
A partition is a slice of a hard disk to write data into it. There are many advantages in creating partitions such as protection from data corruptions by isolating each partition from one another, systematic writing data to disks, even sometimes writing and reading is fast when we create partitions.
Formatting is a concept on how we write data onto disks. Data can be written in many ways with different meta data added to each chunk of data written to disk for security, reductions in disk space wastage, etc.
Once formatting is done on a partition, we can write data on the partition. To access that partition we link the partition to a directory in our machine so that if we go to that directory we can access all the data stored in that partition. This linking of partition with a directory is called as mounting or mount point.
Still did not get the mount concept?
Let us read a farmer story who distributed his uncultivable land to his children and what they did from it.
There is a former who thought of distributing his whole barren land of 25 Hectares to his three children, he distributed as below.
Child 1 : John got eight hectares of land.
Child 2: Barbie got 13 hectares of land.
Child 3 : Steve got four hectares of land.
Now the former children planned for improving their respective lands and started ploughing depending on the crops they are going to cultivates.
John wants to cultivate Oranges.
Barbi wants to cultivate Mangos.
Steve wants to cultivate corn.
For these crops/fruit tree cultivation they require to plough differently to suite their crops. As shown below diagram for cultivating Mangos ploughing is different from cultivating corn. Once this is done they sow their respective crop plants in their lands.
As crops are grown they should be protected from intruders and they arranged a fence around their lands and created an entry point to each of their lands with a gate.
So if anyone to access their lands they have to enter through these gates and get the fruit’s/corn from the land.
The analogy of this story to our disk management is as below.
Farmers land is equal to entire disk
Slices which farmer given to his children is called as partitions
Ploughing land for cultivating crops is called as formatting.
Planting trees and crops are called as writing data to disks/partitions.
Protecting the grown crops and trees by arranging a gate is called mounting.
Some FAQ’s related to mount in Linux/Unix:
Q. I lost my mount point,is my data lost in that partition?
You just lost your access point not the data. To access your partition mount your partition on other directory.
Q. I am M$ windows person and I do not see any mount point stuff, can you explain where is my mount point?
M$ hidden the concept of mounting. The drives in windows is called as mount points and it starts from C drive and ends with Z drive. And, why we do not have A and B drives have all different story.
Q How can I find mounted partitions in my machine?
Hope this helps new commers to Linux will understand this.
Источник
Mount point ��� linux
3.1.2.3. Mount pointsAll partitions are attached to the system via a mount point. The mount point defines the place of a particular data set in the file system. Usually, all partitions are connected through the root partition. On this partition, which is indicated with the slash (/), directories are created. These empty directories will be the starting point of the partitions that are attached to them. An example: given a partition that holds the following directories: We want to attach this partition in the filesystem in a directory called /opt/media. In order to do this, the system administrator has to make sure that the directory /opt/media exists on the system. Preferably, it should be an empty directory. How this is done is explained later on in this chapter. Then, using the mount command, the administrator can attach the partition to the system. When you look at the content of the formerly empty directory /opt/media, it will contain the files and directories that are on the mounted medium (hard disk or partition of a hard disk, CD, DVD, flash card, USB or other storage device). During system startup, all the partitions are thus mounted, as described in the file /etc/fstab. Some partitions are not mounted by default, for instance if they are not constantly connected to the system, such like the storage used by your digital camera. If well configured, the device will be mounted as soon as the system notices that it is connected, or it can be user-mountable, i.e. you don’t need to be system administrator to attach and detach the device to and from the system. There is an example in Section 9.3. On a running system, information about the partitions and their mount points can be displayed using the df command (which stands for disk full or disk free). In Linux, df is the GNU version, and supports the -h or human readable option which greatly improves readability. Note that commercial UNIX machines commonly have their own versions of df and many other commands. Their behavior is usually the same, though GNU versions of common tools often have more and better features. The df command only displays information about active non-swap partitions. These can include partitions from other networked systems, like in the example below where the home directories are mounted from a file server on the network, a situation often encountered in corporate environments. Источник |