Как примонтировать диск в linux навсегда
Перейти к содержимому

Как примонтировать диск в linux навсегда

  • автор:

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

Если Вы устали подключать разделы вручную.

Так уж повелось, что по умолчанию Ubuntu монтирует только свой системный раздел, называя его «файловой системой». Остальные разделы (кроме флэшек и других подключаемых устройств) придется монтировать вручную. Нас такой расклад не устраивает и мы хотим иметь доступ к нашему второму (третьему, четвертому. ) разделу сразу после загрузки ОС.

Каждый раздел имеет свой UUID (Universally Unique Identifier), и мы будем подключать разделы с помощью него.

Шаг 1. Узнаем идентификаторы подключенных разделов

Получаем что-то примерно такое:

/dev/sda1: UUID=»b2098d42-3e3d-470c-8ddb-76f74f0f6d44″ TYPE=»ext4″ /dev/sda3: LABEL=»ntfs» UUID=»6798491F3EB8CFC8″ TYPE=»ntfs» /dev/sda5: LABEL=»FAT32″ UUID=»1D7D-F985″ TYPE=»vfat» /dev/sda6: LABEL=»ext3″ UUID=»a4f6af01-786f-4bdf-9405-d340fded6580″ TYPE=»ext3″ /dev/sda7: LABEL=»ext2″ UUID=»4b2c5e07-97db-4a65-9147-e6b0dceb1353″ TYPE=»ext2″ /dev/sda8: LABEL=»ext4″ UUID=»b74143c3-6679-4a3a-9a20-b608ba085170″ TYPE=»ext4″

Если Вашему разделу задан Label, то всё отлично, поиски необходимого не займут много времени. Например, нам нужен раздел «ntfs» с UUID «6798491F3EB8CFC8». Для определения UUID для раздела без Label придется воспользоваться программами типа gParted или стандартного менеджера дисков, здесь Вам помогут обозначения /dev/sdaX.

gParted информация о разделе

Если же Вам лень искать UUID, то можно воспользоваться порядковым номером: /dev/sda3. Минус такого подхода — порядковый номер может измениться при добавлении или переставлении дисков.

Шаг 2. Оповещаем систему о новом разделе

Вся информация по монтируемым разделам хранится в fstab:

sudo gedit /etc/fstab

Если у Вас не установлен gedit, то можете воспользоваться nano или любым другим текстовым редактором. В этом файле добавляем в конец строку:

UUID=»6798491F3EB8CFC8″ /media/isergium/ntfs ntfs-3g defaults,uid=1000 0 0

Монтировать разделы желательно в /media — так они продолжут распознаваться некоторыми проводниками (например, Nemo) как разделы. Для удобства все разделы можно монтировать в одну папку, например /media/*username*.

Linux Mint - Nautilus - Носители

Приведённый выше формат действителен для NTFS. Обязательно убедитесь что пакет ntfs-3g установлен в Вашей системе. Он даёт много преимуществ перед использованием обычного ntfs, поэтому просто используйте его. Для других файловых систем рекомендованы другие параметры и обозначения:

NTFS ntfs-3g ntfs-3g defaults,uid=1000 0 0
FAT16, FAT32 vfat user,auto,fmask=0111,dmask=0000
Apple HFS hfsplus user,auto,file_umask=0177,dir_umask=0077,uid=1000
ext2 ext2 defaults
ext3 ext3
ext4 ext4

Не забудьте подставить свои значение UUID и путь монтирования.

Шаг 3. Завершаем дело

Осталось перезагрузиться или смонтировать несмонтированные диски:

Шаг 4. Гуляем смело

Вот и всё. Отныне для доступа к необходимым файлам не придется вручную монтировать разделы с ними.

Вариант 2. Gnome Disk Utility

В комментариях был предложен более удобный способ автоматического монтирования с помощью стандартной программы «Диски» (gnome-disks). Вот пример работы с ним на Elementary OS Freya (дистрибутив основан на Ubuntu 14.04):

Gnome Disks Gnome Disks: Automatic Mount Options

Выбрать диск, выбрать раздел, нажать на кнопку с шестерёнками, в появившемся меню выбрать «Изменить параметры монтирования» («Edit Mount Options»). В настройках выключить верхний переключатель «Параметры автоматического подключения» («Automatic Mount Options»), включить «Подключение при запуске» («Mount at startup») и «Показывать в интерфейсе» («Show in user interface»). В «Идентифицировать как» («Identify as») лучше выбрать что-нибудь связанное с UUID. По желанию можно задать Тип файловой системы («Filesystem Type»), Точку подключения («Mount Point») и что-нибудь ещё.

После сохранения соответствующая запись появится в /etc/fstab:

UUID=3C1D4F9C296DA92C /mnt/3C1D4F9C296DA92C auto nosuid,nodev,nofail,x-gvfs-show 0 0

После перезагрузки и каждого следующего включения диск будет примонтирован автоматически:

Elementary OS Диски

Если программа «Диски» не была найдена, то её можно запустить из консоли:

Установить её можно из исходников или командой:

sudo apt-get install gnome-disk-utility

Проблемы с удалением в корзину?

Если при удалении файлов со смонтированных дисков выдаются ошибки вроде «не удалось переместить в корзину», «невозможно удалить в корзину» и подобные, то достаточно добавить в параметры монтирования параметр uid=1000.

UUID=»6798491F3EB8CFC8″ /media/isergium/ntfs ntfs-3g defaults,uid=1000 0 0

Этот параметр устанавливает владельца примонтированного раздела, по умолчанию это (зависит от файловой системы) либо root, либо владелец процесса. Если Ваш UID иной (что маловероятно), то можете поискать свой в /etc/passwd и прописать его.

Вместо uid можно использовать gid — этот параметр установит группу владельцев. Обычно это тоже 1000, проверить можно в /etc/group.

How to mount partition permanently?

karel's user avatar

Unmount is greyed out because the partition isn’t there to be unmounted. You haven’t mounted it yet.

To make the partition auto-mount, first find out the UUID of /dev/sda3 by doing:

I’ll assume you’re using ext4 on /dev/sda3. Open up gedit like so:

(Or, in the command line, sudo vim or sudo nano instead of gksudo gedit .)

Now you want to add a line to the bottom of that file. It should look something like this (UUID will be different):

karel's user avatar

Use Disks utility. Select the disk, then click Additional partition options icon. Choose Edit Mount Options from drop-down menu.

I’m using Ubuntu Server and I made the permanent mount as follows with a disk already formatted in ext4.

I have listed my disks and partitions with

After that, I listed the UUID of the partition I would like to mount permanently with the following command:

To mount the partition I created a target location with

then I rode with

We need to put the mounted partition in the /etc/fstab file Don’t forget to make a backup first. run

To avoid breaking the file system you need to look at the structure that is already in /etc/fstab for the disks that are already automounted. In my case it is like this

On the site Arch Linux Wiki it is presented what this structure means. Below is an excerpt:

unixforum.org

Как примонтировать раздел HDD на постоянной основе?

Модератор: Bizdelnick

Как примонтировать раздел HDD на постоянной основе?

Re: Как примонтировать раздел HDD на постоянной основе?

Re: Как примонтировать раздел HDD на постоянной основе?

C10H15N
Но у меня там кроме Флопика и CD, потом дисков системы ничего не указано.
Я написал следующую строчку для примонтирования одного диска

Re: Как примонтировать раздел HDD на постоянной основе?

C10H15N
Но у меня там кроме Флопика и CD, потом дисков системы ничего не указано.
Я написал следующую строчку для примонтирования одного диска

Re: Как примонтировать раздел HDD на постоянной основе?

Re: Как примонтировать раздел HDD на постоянной основе?

Re: Как примонтировать раздел HDD на постоянной основе?

Сообщение nesk » 21.04.2009 21:45

да навалом
не знаю что там у Вас по умолчанию в ubuntu есть, но вот например http://pysdm.sourceforge.net/

(даже на этот форуме один молодой программист писал подобную программку. найдете?)

Внимание: У меня под рукой нет машины с Linux. Я не использую эту ОС. Ответы я даю либо по памяти, либо мне помогает гугл. Тщательно читайте маны по тем командам и конфигурационным файлам, которые я упоминаю.

Re: Как примонтировать раздел HDD на постоянной основе?

Re: Как примонтировать раздел HDD на постоянной основе?

Re: Как примонтировать раздел HDD на постоянной основе?

Re: Как примонтировать раздел HDD на постоянной основе?

$ mountmanager
7 records in /etc/fstab were detected.
[G] DBus interface was created
[G] All devices were recieved
[I] Storage device was detected: "/dev/sr0"
[I] Storage device was detected: "/dev/sdc1"
[I] Storage device was detected: "/dev/sdc"
[I] Storage device was detected: "/dev/sr0"
[I] Storage device was detected: "/dev/sdb4"
[I] Storage device was detected: "/dev/sdb3"
[I] Storage device was detected: "/dev/sdb2"
[I] Storage device was detected: "/dev/sdb1"
[I] Storage device was detected: "/dev/sda3"
[I] Storage device was detected: "/dev/sda2"
[I] Storage device was detected: "/dev/sda1"
[I] Storage device was detected: "/dev/sdb"
[I] Storage device was detected: "/dev/sda"
[G] Parsing of "/usr/share/mountmanager/options/common.xml" was successful
[G] Parsing of "/usr/share/mountmanager/options/ntfs-3g.xml" was successful
Segmentation fault

Re: Как примонтировать раздел HDD на постоянной основе?

$ mountmanager
7 records in /etc/fstab were detected.
[G] DBus interface was created
[G] All devices were recieved
[I] Storage device was detected: "/dev/sr0"
[I] Storage device was detected: "/dev/sdc1"
[I] Storage device was detected: "/dev/sdc"
[I] Storage device was detected: "/dev/sr0"
[I] Storage device was detected: "/dev/sdb4"
[I] Storage device was detected: "/dev/sdb3"
[I] Storage device was detected: "/dev/sdb2"
[I] Storage device was detected: "/dev/sdb1"
[I] Storage device was detected: "/dev/sda3"
[I] Storage device was detected: "/dev/sda2"
[I] Storage device was detected: "/dev/sda1"
[I] Storage device was detected: "/dev/sdb"
[I] Storage device was detected: "/dev/sda"
[G] Parsing of "/usr/share/mountmanager/options/common.xml" was successful
[G] Parsing of "/usr/share/mountmanager/options/ntfs-3g.xml" was successful
Segmentation fault

Re: Как примонтировать раздел HDD на постоянной основе?

Re: Как примонтировать раздел HDD на постоянной основе?

по моему куда проще использовть fdisk -l и отредактировать /etc/fstab (примерно как писал C10H15N)

Mounting Partitions Automatically

Per-user mounting does not require root access, it’s just automating the desktop interface. Systemwide mounts (/etc/fstab) can allow access from before login, and are therefore much more suitable for access through a network, or by system services.

Commands should be entered on a terminal (Type terminal in the program launcher of recent unity based Ubuntu releases, or select Applications -> Accessories -> Terminal from the menus on older releases).

Per-User Mounts

udisks

This is the modern replacement for gnome-mount. It’s not gnome specific.

When you mount a disc normally with the file browser (nautilus etc) it mounts disks by interacting with udisks behind the scenes.

You can do the same thing on the command line with the udisks tool. For example:

The bit after —mount is the device name of the partition you want to mount. (/dev/something). The command will mount /dev/sdb1 in /media/<uuid> where <uuid> is the identifier of the particular partition. Read below to find the uuid of your partition.

Finding the device name of your Partition

    Open your partition in nautilus (this makes sure it’s mounted)

Finding the UUID of your partition

A device name like /dev/sdb1 is based on where your physical drive is plugged in and the order the drives were made available to the computer, so if your computer changes the same command could mount a different partition. It’s possible for this to happen just from a software upgrade.

The UUID in the example is 1313-F422

You can now determine the command you need for mounting the device by UUID. For our example it would be

Of course you need to replace 1313-F422 with the UUID of the device you want to mount.

Again, this will mount your partition in /media/<uuid> which is not consistent with how nautilus mounts partitions. The partitions mounted by nautilus can be found in /media/<user>/<uuid> with <user> being the current logged-in user.

To keep the folder structure consistent an alternative command can be used that takes care of the correct mountpoint automatically:

Of course, <uuid> needs to be adjusted to the correct UUID of your partition, e.g., 1313-F422 in this example.

Adding to startup

Systemwide Mounts

    The first method is manually editing Ubuntu’s filesystem table. This sounds more complex than it really is.

Manual Setup Help

To mount hard disk partitions, you should have a basic understanding of the information below.

Once installed you can browse to System > Network and File Systems >

Basic understanding is still required.

Viewing the system’s physical information

To read the layout of the physical disks in the system, the ‘fdisk’ command is used. Before panicking, realize that fdisk will be used with only non-destructive options; specifically, it will be used with ‘l’ (lower-case ‘L’, not ‘1’), which lists the partition table of the specified disk.

As an example, here is what the output would be if one had a laptop with one internal drive, and usb drive plugged in:

If the system has multiple hard disk drives, multiple lists will be displayed.

Deciding which partitions to mount

Most systems only have /dev/hda, which is the hard disk drive, and /dev/hdc, which is the CD-ROM, or optical, drive. If more were listed when the command above was run, they can be identified as follows: hda is the first drive on the first IDE channel (0:0), hdb is the second drive (0:1), hdc is the third drive (1:0), and hdd is the fourth (1:1). SCSI and S-ATA disks have names like sda and sdb.

Look through the list generated above to identify the partition(s) to be mounted. The following table lists some common ‘System’ types, which may help this process.

A list of the form ‘/dev/hda1: /media/windows/ (vfat)’, where ‘/dev/hda1’ is the device, ‘/media/windows’ is the arbitrary location where the partition will appear when mounted, and ‘vfat’ is the Linux type, should be created on paper, containing all partitions to be added.

Preparing the system

Look through the list which was just created. For every location (‘/media/windows’), run the following command.

If a response like ls: /media/windows: No such file of directory is returned, the location is open. If a list of files or nothing is returned, the location exists already, and the planned location will need to be altered.

Once every location has been confirmed as free, run the following command for each entry, replacing ‘/media/windows’ with the chosen location.

Editing Ubuntu’s filesystem table

It is possible to break Ubuntu if some of the earlier lines in the file opened during this step are modified, so be sure to read this section carefully.

Ubuntu’s filesystem table is located at ‘/etc/fstab’. Open this file for editing by running the following command for Ubuntu

or this command for Kubuntu

or command line

The file opened contains lines of the form <device> <location> <Linux type> <options> <dump> <pass>. Every element in this line is separated by whitespace (spaces and tabs):

<file system>

The first field, (fs_spec), describes the block special device or remote filesystem to be mounted.

For ordinary mounts it will hold (a link to) a block special device node (as created by mknod(8)) for the device to be mounted, like /dev/cdrom or /dev/sdb7. For NFS mounts one will have <host>:<dir>, e.g., knuth.aeb.nl:/. For procfs, use proc.

Instead of giving the device explicitly, one may indicate the (ext2 or xfs) filesystem that is to be mounted by its UUID or volume label (cf. e2label(8) or xfs_admin(8)), writing LABEL=<label> or UUID=<uuid>, e.g., LABEL=Boot or UUID=3e6be9de-8139-11d1-9106-a43f08d823a6. This will make the system more robust: adding or removing a SCSI disk changes the disk device name but not the filesystem volume label. The UUID of a drive can be determined by typing ls -l /dev/disk/by-uuid/ in a shell.

<mount point>

The second field, (fs_file), describes the mount point for the filesystem. For swap partitions, this field should be specified as none. If the name of the mount point contains spaces these can be escaped as \040.

The third field, (fs_vfstype), describes the type of the filesystem. Linux supports lots of filesystem types, such as adfs, affs, autofs, coda, coherent, cramfs, devpts, efs, ext2, ext3, hfs, hpfs, iso9660, jfs, minix, msdos, ncpfs, nfs, ntfs, proc, qnx4, reiserfs, romfs, smbfs, sysv, tmpfs, udf, ufs, umsdos, vfat, xenix, xfs, and possibly others. For more details, see mount(8). For the filesystems currently supported by the running kernel, see /proc/filesystems. An entry swap denotes a file or partition to be used for swapping, cf. swapon(8). An entry ignore causes the line to be ignored. This is useful to show disk partitions which are currently unused.

<options>

The fourth field, (fs_mntops), describes the mount options associated with the filesystem.

It is formatted as a comma separated list of options. It contains at least the type of mount plus any additional options appropriate to the filesystem type. For documentation on the available options for non-nfs file systems, see mount(8). For documention on all nfs-specific options have a look at nfs(5). Common for all types of file system are the options noauto (do not mount when "mount -a" is given, e.g., at boot time), user (allow a user to mount), and owner (allow device owner to mount), and comment (e.g., for use by fstab-maintaining programs). The owner and comment options are Linux-specific. For more details, see mount(8).

The fifth field, (fs_freq), is used for these filesystems by the dump(8) command to determine which filesystems need to be dumped. If the fifth field is not present, a value of zero is returned and dump will assume that the filesystem does not need to be dumped.

The sixth field, (fs_passno), is used by the fsck(8) program to determine the order in which filesystem checks are done at reboot time. The root filesystem should be specified with a fs_passno of 1, and other filesystems should have a fs_passno of 2. Filesystems within a drive will be checked sequentially, but filesystems on different drives will be checked at the same time to utilize parallelism available in the hardware. If the sixth field is not present or zero, a value of zero is returned and fsck will assume that the filesystem does not need to be checked.

<options> example

To learn more about options, type ‘man mount’.

*If you want write access to your file system, you should set the filesystem type to ‘ntfs-3g’ instead of ‘ntfs’. You may need to install the package ‘ntfs-3g’ for this to work, so make sure it is installed before you use ntfs-3g.

**uid=1000 restricts access to the user created while installing Ubuntu. 1001 is the user created after that, and so forth. gid=# may be used with or in place of uid to grant access to a group. However, group and user enumeration is beyond the scope of this article.

<type> example

Note for international users: if your filesystem contains funny symbols, you may need to add an option for utf-8 support.

fstab example

So, to grant all users access to ‘/dev/hda1’, which will be located at ‘/media/windows’, and is of type ‘vfat’, the line added would be.

This entry is case-sensitive. In general, lower-case letters are used to avoid confusion.

‘dump’ and ‘pass’ are only of use to native filesystems. They can be set to ‘0’ for all additional partitions.

For every item in the list of partitions to be mounted, add one line of the form above to the end of the fstab file.

Mounting Fakeraid

Its assumed you have formated you raid set using dmraid command with instructions found at FakeRaidHowto.

You need to know the name of your raid set

Edit fstab as per instructions above :

An example line to add

Make sure you create the directory /media/raid

Mounting and checking the partitions

In the terminal, type the following command:

To verify that the partitions were mounted properly, open Gnome’s file browser and direct it to the locations at which the partitions were mounted. Click the ‘File System’ button to access ‘/’, and navigate from there. If the partition being examined contains files, the modifications were successful, and the partitions will be automatically mounted every time the system is restarted. If no files are found, please see XChatHowto and join #ubuntu on irc.freenode.net.

Using pysdm in Precise

Pysdm is a program to automatically setup partitions every time Ubuntu starts.

Installation

Usage

Select each partition you want to change in the list. Note the type. Often it is ext3 (Linus) or NTFS (Windows). Use assistant and press OK. By default the partition is mounted at boottime. You can also mount the partition now. Press Apply. Done.

Hints, Tips, and Technical Information

Adding a bookmark

Bookmarks may be added to help speed access to commonly used files and locations, such as mounted partitions.

While browsing the filesystem using Gnome’s file browser, click ‘Bookmarks’, then ‘Add Bookmark’. A new entry will be placed in the bar on the left, and the location will appear under the ‘Places menu’.

Alternatively, bookmarks may be added while opening or saving a file by clicking the ‘Add’ button.

To remove a bookmark, click either ‘Edit Bookmarks’, or the ‘Remove’ button, either of which is the counterpart of the two addition methods stated above.

More technical tips

Symlinking for greater convenience

If navigating to a partition’s mount point seems inconvenient, even with the links on the left of Gnome’s file browser, a link can be placed on the desktop, or anywhere else, for that matter.

Try the following command:

A link to the directory ‘/media/windows’ will be placed on the desktop. Files may be dragged into it, it may be opened, it can be renamed and moved, and if it proves to be annoying, it can be deleted like any other file without risking damage to its contents.

This process is called symlinking because the link created is symbolic. It merely points to the location being referenced.

Unmounting a partition to prevent unwanted access

While it’s easy and effective to set permissions on partitions, there may be times when setting permissions won’t be enough. Sometimes, people who can’t be trusted with important information, such as a term paper, may need access to a system, and modifying the filesystem table may be impractical. When things like this happen, it’s easy to archive data to preserve permissions and stick it on a mounted partition or device, then unmount the device, preventing "accidental" access. (The potentially jokingly malicious user would need to know the filesystem table, and while that information isn’t well hidden, it’s hard to access without drawing attention).

Try the following command to unmount a partition:

The partition mounted at ‘/media/windows’ will be unmounted, and attempts to access it will yeild only an empty directory. To bring it back later, either reboot, or simply run the following command.

Technical background information

How Linux manages partitions

Linux uses a virtual filesystem (VFS) to maintain a single tree of files, all spread from ‘/’. When a partition is mounted, it is added to the tree at its mount point.

When a FAT32 partition is mounted at ‘/media/windows’, all access to ‘/media/windows’ and everything below it is transparently handled by the Linux kernel using the ‘vfat’ module. Applications need not know they’re dealing with anything else. However, mounting a partition at a location inside of another mounted partition is unpredictable, unstable, and generally a bad idea.

Every partiton maintains its own free space and internal filesystem, so they can be mounted on other systems and behave properly. (If you have two operating systems or a removable hard disk drive, feel free to test this — it’s hard to break anything, and sharing /home (provided no usernames overlap) and swap between two Linux installations is very convenient)

To see what’s going on behind the scenes, try the ‘df’ and ‘mount’ commands.

AutomaticallyMountPartitions (последним исправлял пользователь hrishikesh-kadam 2021-02-25 14:40:29)

The material on this wiki is available under a free license, see Copyright / License for details
You can contribute to this wiki, see Wiki Guide for details

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *