- UUID, FSTAB, ФС, монтирование устройств
- How To Use UUID To Mount Partitions / Volumes Under Ubuntu Linux
- UUID and Partitions
- UUID benefits
- How do I find out UUID for /dev/sdb2?
- List all UUIDs
- How do I use UUID to update /etc/fstab file?
- Further readings:
- ru fstab
- Пример
- Определения полей
- Определение файловых систем
- Имена данные ядром
- Label
UUID, FSTAB, ФС, монтирование устройств
Как использование UUID при монтировании разделов.
Как-то столкнулся с одной проблемкой. У меня есть IDE-карман, который я редко, но использую. Так вот, когда в этот карман вставляешь диск, а комп при этом потушен, то при загрузке мои жесткие диски меняли свои названия в каталоге /dev. Из-за этого, некоторые монтировались ни туда, куда надо, а некоторые вообще не монтировались.
Как выяснилось, дело было в том, что я по старинке монтировал свои диски указывая название жесткого диска (например: /dev/sda1 ) и папку куда он должен монтироваться (например: /mnt/D ). Все бы ничего, но когда я вставлял жесткий в карман, то добавлялось еще одно устройство и названия жестких дисков в каталоге /dev — менялись.
Решение такой проблемы очень простое. Вы наверное замечали, как монтируются по умолчанию ваша домашняя директория и корневая система в Убунту. Монтируются они с помощью стандарта идентификации — UUID (Universally Unique Identifier). Смысл системы в том, что каждый ваш диск идентифицируется специальным номером, который не меняется даже тогда, когда диски меняются местами в каталоге /dev. И с помощью этого идентификатора, вы можете монтировать все свои диски не задумываясь о том, что будет если вы добавите еще один диск в вашу систему и т.д.
1. Применять идентификаторы дисков, будем в файле /etc/fstab, который отвечает за монтирование устройств при загрузке системы.
1.1. Вот так вот, выглядела раньше запись монтирования двух моих дисков:
Источник
How To Use UUID To Mount Partitions / Volumes Under Ubuntu Linux
Q. Can you explain UUID concept related to Linux ext3 partitions and storage devices? How do I update /etc/fstab using UUID under Ubuntu Linux or any other Linux distro?
A. A Universally Unique Identifier (UUID) is an identifier standard used in software construction, standardized by the Open Software Foundation (OSF) as part of the Distributed Computing Environment (DCE). The intent of UUIDs is to enable distributed systems to uniquely identify information without significant central coordination. Thus, anyone can create a UUID and use it to identify something with reasonable confidence that the identifier will never be unintentionally used by anyone for anything else. Information labeled with UUIDs can therefore be later combined into a single database without needing to resolve name conflicts.
UUID and Partitions
Linux’s ext2/ext3 filesystem uses UUID to identify partitions.
UUID benefits
As a sesonded UNIX admin I have to deal with various data storage technologies such as SAN, iSCSI, DAS, scsi disks volumes. Sometime you may need to move storage from one device to another and updating /etc/fstab can be pain in a$$. With UUID Linux kernel should automatically find and map (read as mount to exact location) volumes to storage device. This saves lots of time and avoid /etc/fstab breaks.
However, UUID may be not very useful for single desktop computer at home as you do not have enterprise grade storage and requirements.
How do I find out UUID for /dev/sdb2?
To probe filesystem type and read label and uuid for /dev/sdb2 (or any other device) use vol_id command:
# vol_id —uuid < /dev/device >
# vol_id —uuid /dev/sdb2
$ sudo vol_id —uuid /dev/sdb2
Sample output:
List all UUIDs
Use blkid command-line utility to locate/print block device attributes:
$ sudo blkid
Sample output:
How do I use UUID to update /etc/fstab file?
Simply use following syntax:
Open /etc/fstab:
$ sudo vi /etc/fstab
Append line as follows:
- No ads and tracking
- In-depth guides for developers and sysadmins at Opensourceflare✨
- Join my Patreon to support independent content creators and start reading latest guides:
- How to set up Redis sentinel cluster on Ubuntu or Debian Linux
- How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
- How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
- A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
- How to protect Linux against rogue USB devices using USBGuard
Join Patreon ➔
Save and close the file. To mount new partition immediately using /etc/fstab type:
$ sudo mount -a
Further readings:
🐧 Get the latest tutorials on Linux, Open Source & DevOps via
Category | List of Unix and Linux commands |
---|---|
Documentation | help • mandb • man • pinfo |
Disk space analyzers | df • duf • ncdu • pydf |
File Management | cat • cp • less • mkdir • more • tree |
Firewall | Alpine Awall • CentOS 8 • OpenSUSE • RHEL 8 • Ubuntu 16.04 • Ubuntu 18.04 • Ubuntu 20.04 |
Linux Desktop Apps | Skype • Spotify • VLC 3 |
Modern utilities | bat • exa |
Network Utilities | NetHogs • dig • host • ip • nmap |
OpenVPN | CentOS 7 • CentOS 8 • Debian 10 • Debian 8/9 • Ubuntu 18.04 • Ubuntu 20.04 |
Package Manager | apk • apt |
Processes Management | bg • chroot • cron • disown • fg • glances • gtop • jobs • killall • kill • pidof • pstree • pwdx • time • vtop |
Searching | ag • grep • whereis • which |
Shell builtins | compgen • echo • printf |
Text processing | cut • rev |
User Information | groups • id • lastcomm • last • lid/libuser-lid • logname • members • users • whoami • who • w |
WireGuard VPN | Alpine • CentOS 8 • Debian 10 • Firewall • Ubuntu 20.04 |
Comments on this entry are closed.
I have been trying to figure out what happen to my UUID’s on my server, thanks a lot for the help. Now I can change everything to ext4 on my laptop.
Thats a good description.
Thankyou
I have a UBUNTU server, recently i cloned the disk using dd and kept the second disk in box itself. yesterday i realized that because of UUID features it generated same UUID to my /dev/sdb partitions and it looks like it is using the mix of first disk and second disk.
now “blkid” should be used instead.
ls -l /dev/disk/by-uuid/
Forgive my ignorance with the whole UUID thing. I understand it is superior in many ways, hence the switch.
However does this mean that anything to do with hard-drives / flash drives / CD & DVD bays involving the terminal is going to be a complete pain in the arse?
For instance, to write an image to disk, I can currently use something like:
# dd if= of=sdb1
But now I must type:
# dd if= of=8c2da865-13f4-47a2-9c92-2**FNA**&%#$**34 .
Or is there something to this whole “upgrade” process that I’m not understanding?
Thanks
Paul,
The main importance of UUID is for mounting a specific device to a specific mount-point reliably. In a terminal to use your example you would still type: # dd if= of= where you mount sdb1.
During the boot process, you have much more accurate mounting if you use:
UUID=8c2da865-13f4-47a2-9c92-2**FNA**&%#$**34 ext4 /office-docs rw,defaults 0 2 .
This will ALWAYS mount that device at /office-docs. If you use a line in etc/fstab like:
/dev/sdd1 /office-docs ext4 /office-docs defaults,rw 0 2 there is a possibility that another hdd may be recognized as /dev/sdd1 and therefore be mounted at /office-docs.
Once boot-up is complete, you will still use the same commands as always (always referencing mounted devices just like you have been doing).
HTH,
Decaffienated46
I didn’t understand the rational behind the change. However, I was recently given an old tablet that won’t boot off anything but its internal drive. I installed Linux by booting my desktop from install media, installed to the tablet’s drive connected as an external. Once tucked back into the target machine, it booted flawlessly, thanks to UUIDs. No mucking about with the fstab.
I find it convenient to use UUID for drives at home. For instance if I set fstab mounts based on drive number such as /dev/sda1 it might break next time I add or remove a drive because drive numbers might change. however, this is solved by using uuids because they identify drives uniquely not their order on controller.
dumpe2fs -h |grep UUID
Hi,
i’m trying to install RHEL 6.2 in VMware on an external Hard drive. I have tried a few times in no of ways 1. When creating the VM i tried custom and identified by EXT4 partition on my hard drive. When i wanted to an install, went past the boot screen but that’s it. 2. I thrashed the VM and created another on the Laptop hard drive. whilst installing RHEL, i tried the 2nd option besides basic storage devices. Can’t find the my external ext4 partition or my hard drive.
Any help is welcome
Thanks
Cheers
N
I suspect that UUIDs change if you repartition a drive? (I’m almost sure that has to be true, but I was looking for confirmation.)
I have created Ghost Image of my Server but when i installed that Image on another server in LAN, i am getting conflict of UUID at Central Server.
Why it is so and how to get rid of this?
Please help me
Duplicate UUIDs occur only in rare cases. In your case, you cloned the disk using some utility. (E.g. dd). This caused the conflict.
The steps to solve this are:
1) type “blkid” on the main server and the other server as root. And identify the partitions and their corresponding numbers in /dev E.g. /dev/sda1, dev/sda2 .. /dev/sdX etc.. Now we need to change only those partitions whose UUIDs match the UUIDs of partitions on the server.
2) generate as many random UUIDs as needed for the partitions. Using the “uuidgen” command. Running “uuidgen” in terminal will generate a random UUID e.g. “4ae70274-5b0f-4384-a7fd-15fcbdbd0b58” do this twice or thrice or as many times as needed.
4) Assign these randomly generate UUID’s to the partitions. This needs root privileges the command is “tune2fs /dev/sdX -U ”
E.g.: sudo tune2fs /dev/sda2 -U 73c6756e-aad2-41f6-8dff-597fe076cd07
Hmm seems WordPress has issues with formatting. It bit off some of my wording.
Correct “This needs root privileges the command is tune2fs /dev/sdX -U ” to
“This needs root privileges the command is “tune2fs /dev/sdX -U UUID_Value”
Источник
- ru
- fstab
fstab (/etc/fstab) (или file systems table) — один из конфигурационных файлов в Debian, содержащий инструкции по монтированию блочных устройств, NFS-ресурсов и псевдо-файловых систем в пространство файловых имен и как областей подкачки страниц.
Пример
Не стоит добавлять в fstab /proc и /sys если не нужны какие-то специальные опции. При загрузки системы они всегда будут смонтированы.
Определения полей
/etc/fstab содержит следующие поля разделённые пробелами или tab:
— название накопителя (например: /dev/sda1).
— точка монтирования, куда монтировать .
— тип файловой системы монтируемого устройства или раздела. Поддерживает много различных файловых систем, например: ext2, ext3, reiserfs, xfs, jfs, smbfs, iso9660, vfat, ntfs, swap и auto. Тип ‘auto’ позволяет команде монтирования определить тип используемой файловой системы, полезно для съёмных устройств, таких как CD и DVD.
— специальные опции для файловых систем. Некоторые опции относятся только к определённой файловой системе, наиболее распространённые варианты:
auto — файловая системы будет смонтирована автоматически при загрузке или после выполнения команды ‘mount -a’.
noauto — файловая система может быть смонтирована только вручную.
exec — разрешить исполнять бинарных файлов с этого раздела (по умолчанию).
noexec — запретить исполнять бинарные файлы с этой файловой системы.
ro — монтировать файловую систему только для чтения.
rw — монтировать файловую систему для чтения и записи.
sync — операции ввода/вывода должны выполняться синхронно.
async — операции ввода/вывода должны выполняться асинхронно.
flush — опция специфичная для FAT. To flush data more often, thus making copy dialogs or progress bars to stays up until things are on the disk.
discard — включает поддержку команды TRIM для SSD дисков.
user — разрешить любому пользователю монтировать файловую систему (с опциями noexec,nosuid,nodev если не указано иное).
nouser — только root может монтировать файловую систему (по умолчанию).
defaults — использовать настройки по умолчанию (эквивалентно rw,suid,dev,exec,auto,nouser,async).
suid — разрешать операции с битами suid и sgid. Восновном используемые, чтобы позволить пользователям выполнять бинарные файлы со временно повышенными привилегиями для выполнения определённой задачи.
nosuid — запретить операции с битами suid и sgid.
noatime — не обновлять информацию о времени доступа к файловой системе. Может повысить производительность.
nodiratime — не обновлять информацию о времени доступа к каталогам файловой системе. Может повысить производительность.
relatime — обновлять информацию о времени доступа по сравнению с временем последнего изменения. Время доступа обновляется только если предыдущее было больше текущего времени изменения (аналог noatime, только не создаёт проблемы для приложений которым нужно знать, если файл был прочитан с момента последнего изменения). Может повысить производительность.
— используется утилитой dump для того чтобы определить, когда делать резервную копию. После установки, dump проверяет эту запись и использует значение, чтобы решить, подключать ли файловую систему. Возможные значения 0 или 1. Если 0, dump игнорирует файловую систему, если 1, dump сделает резервную копию. У большинства пользователей dump не установлен, поэтому в поле следует задать 0.
fsck читает значение
и определяет, в каком порядке должны быть проверены файловые системы. Возможные значения 0, 1, или 2. Файловая система root должна иметь наивысший приоритет, 1, все остальные файловые системы которые будут проверятся должны получить 2. Файловые систему с значением 0 в
не будут проверяться утилитой fsck.
Определение файловых систем
Файловые систему в /etc/fstab могут быть определены тремя различными способами: по имени данному ядром, по UUID или по labels. Преимущество использования UUID или labels в том, что они не зависят от порядка дисков, полезно когда изменяется порядок накопителей в BIOS (это может быть сделано пользователем или некоторые BIOS могут иногда изменять порядок устройств), или при переключении кабеля устройства.
Имена данные ядром
Узнать имена данные ядром можно используя fdisk:
Пример /etc/fstab с использованием имён данных ядром:
UUID генерируется утилитами mkfs.* при создании файловой системы. blkid показывает UUIDs устройств и разделов:
Пример /etc/fstab с использованием UUID-идентификаторов:
Label
В первую очередь нужно задать label для устройства или раздела, для этого можно использовать приложения такие как gparted или e2label для разделов ext2, ext3 и ext4. Имейте ввиду, что не все файловые системы поддерживают label (например FAT). Каждый lable должен быть уникальным, (чтобы избежать конфликтов) и содержать не более 16 символов.
Устройство или раздел не должны быть смонтированы перед получением label. Initially you will need to boot from a Live(CD/DVD/USB) before you can label with a gparted-like application or for ext partitions you can use e2label:
Пример /etc/fstab с использованием label:
Источник