Mount squashfs in linux

SquashFS

SquashFS is an open source, read only, extremely compressible filesystem. Like other filesystems, SquashFS is capable of de-duplicating the data passed to it, which helps it compress data further. Although not fully necessary to operate correctly, SquashFS is typically paired with some kind of union filesystem when used for Live media (LiveUSBs and LiveCDs).

Installation

Kernel

The following kernel options must be activated for SquashFS support:

File systems ---> [*] Miscellaneous filesystems ---> [*] SquashFS 4.0 - Squashed file system support

Optional SquashFS support

File systems ---> [*] Miscellaneous filesystems ---> File decompression options (Decompress file data into an intermediate buffer) ---> Decompressor parallelisation options (Single threaded compression) ---> [*] Squashfs XATTR support [*] Include support for ZLIB compressed file systems [*] Include support for LZ4 compressed file systems [*] Include support for LZO compressed file systems [*] Include support for XZ compressed file systems [*] Use 4K device block size? [*] Additional option for memory-constrained systems (3) Number of fragments cached

USE flags

Like most filesystems in Linux, the SquashFS filesystem tools come in a separate package. This package is called sys-fs/squashfs-tools. Set the desired support for the package by adjusting USE flags accordingly.

USE flags for sys-fs/squashfs-tools Tools to create and extract Squashfs filesystems

debug Enable extra debug codepaths, like asserts and extra output. If you want to get meaningful backtraces see https://wiki.gentoo.org/wiki/Project:Quality_Assurance/Backtraces
lz4 Enable support for lz4 compression (as implemented in app-arch/lz4)
lzma Support for LZMA (de)compression algorithm
lzo Enable support for lzo compression
xattr Add support for extended attributes (filesystem-stored metadata)
zstd Enable support for ZSTD compression

Emerge

After setting flags as desired, update the system so the changes take effect:

Usage

Filesystem creation

Creation of SquashFS filesystems is performed with the mksquashfs command. To create a SquashFS filesystem of the home directory of a user named larry, the following command could be used:

Depending on what kernel features were selected for SquashFS support, the output of the mksquashfs command will look something like the following:

Parallel mksquashfs: Using 4 processors Creating 4.0 filesystem on /home/larry/home.squashfs, block size 131072. [=========================================================================|] 4/4 100% Exportable Squashfs 4.0 filesystem, gzip compressed, data block size 131072 compressed data, compressed metadata, compressed fragments, compressed xattrs duplicates are removed Filesystem size 0.82 Kbytes (0.00 Mbytes) 58.79% of uncompressed filesystem size (1.39 Kbytes) Inode table size 104 bytes (0.10 Kbytes) 46.02% of uncompressed inode table size (226 bytes) Directory table size 96 bytes (0.09 Kbytes) 77.42% of uncompressed directory table size (124 bytes) Number of duplicate files found 1 Number of inodes 7 Number of files 5 Number of fragments 1 Number of symbolic links 0 Number of device nodes 0 Number of fifo nodes 0 Number of socket nodes 0 Number of directories 2 Number of ids (unique uids + gids) 1 Number of uids 1 larry (1001) Number of gids 1 larry (1001)

Notice the command provides an excellent summary of what went into the newly created home.squashfs file. Information such as filesystem size, inode table, directory table, number of duplicate files, UIDs, and GIDs are easily readable. This information can be very helpful when attempting to gather specific information from the filesystem.

Читайте также:  Linux ifconfig no ip address

Mount

To mount a SquashFS, use the mount command’s -o loop option with escalated privileges:

Note
If the mount command fails, see the related entry in the troubleshooting section below.

Now all the files that are included in home.squashfs are available under the ~/tmp mount point. List the files in the directory using the -la options to see all the files:

total 3 drwxr-xr-x 3 larry larry 125 Mar 31 13:51 . drwxr-xr-x 1 larry larry 130 Mar 31 13:52 .. -rw------- 1 larry larry 10 Mar 31 13:49 .bash_history -rw-r--r-- 1 larry larry 127 Mar 24 13:19 .bash_logout -rw-r--r-- 1 larry larry 193 Mar 24 13:19 .bash_profile -rw-r--r-- 1 larry larry 551 Mar 24 13:19 .bashrc -rw-r--r-- 1 larry larry 0 Mar 31 13:51 home.squashfs drwx------ 2 larry larry 3 Oct 23 06:52 .ssh

Unmount

To unmount the filesystem, use the umount command with escalated privileges:

Extract

SquashFS files can be extracted using unsquashfs . Supposing the ~/tmp directory and the ~/home.squashfs file have been previously created in the steps above:

  • If a filesystem target is not specified ( ~/tmp is the target in the example above) unsquashfs will create a folder called squashfs-root in the current directory and extract the files there. [1]
  • If a directory exists previous to the unsquashfs command being run, then the -d and -f options must be used in order to force SquashFS extraction to the existing directory [1]
  • When extracting to a new directory, the -f option is not needed.

unsquashfs can be used to extract a specific file in the SquashFS. Again, presuming the ~/home.squashfs file has been previously created in the steps above, the .bashrc file can be extracted to the ~/tmp directory:

Parallel unsquashfs: Using 4 processors 1 inodes (1 blocks) to write [===========================|] 1/1 100% created 1 files created 1 directories created 0 symlinks created 0 devices created 0 fifos

View the extract file using the ls command:

total 4 drwxr-xr-x 1 larry larry 14 Mar 31 13:51 . drwxr-xr-x 1 larry larry 156 Mar 31 14:32 .. -rw-r--r-- 1 larry larry 551 Mar 24 13:19 .bashrc

Troubleshooting

mount: only root can use «—options» option

This error is should be self-explanatory. Log in as the root user or use sudo to mount the filesystem with escalated privileges.

Читайте также:  Линукс создать ярлык через командную

See also

  • Aufs — an advanced multi-layered unification filesystem.
  • OverlayFS — an in-kernel attempt at providing union file system capabilities on Linux.
  • Wikipedia:UnionFS — The original union filesystem.

External resources

  • A SquashFS instructional video on YouTube.
  • Forums thread TIP: Compressing portage using squashfs: initscript method
  • Article/Script using SquashFS to store and update portage tree
  • Portage tree using squashfs and overlayfs
  • GitHub — nrdvana/squash-portage: Script to generate squashfs files of the Gentoo portage tree

References

Источник

Заметки дядюшки Раджи

Всякая всячина, которую дядюшка Раджа находит в интернете и хочет поделиться с читателями.

Об авторе

Архив блога

Мой блог смотрят

26 ноября 2017

Как я squashfs монтировал.

В хранении неизменных данных есть две проблемы: занимаемое место и количество файлов. Второе актуально для всяческих сборников книг и прочих рипов древних сайтов. Хочется, чтобы информация лежала одним куском, занимала минимум места и при этом была доступна без ручного вмешательства.
Для себя я нашел выход в использовании сжатой файловой системы sqashfs.

Эта файловая система удовлетворяет двум из трех требований: данные хранятся в образе одним куском и занимают меньше места, благодаря сжатию. Доступность я пилил уже сам.

Все свои эксперименты я проводил на поддиванном сервере с ОС Debian 9 x64.

  1. Выделить каталог для хранения образов;
  2. Для каждого образа создать подкаталог;
  3. Смонтировать образ в подкаталог с соответствующим именем;
  4. Сделать символическую ссылку в нужном месте.

И по пунктам.
Всё добро я складываю в каталог «/data/squash«, точки монтирования делаю там же, а символические ссылки раскидываю уже руками. Сделать это нужно один раз, поэтому мудрить не надо.

В страшных муках отладки я написал вот такой юнит:

$ systemctl cat squashmount@ # /etc/systemd/system/squashmount@.service [Unit] Description=Mount for /data/squash/%i Wants=local-fs.target After=local-fs.target [Service] # создание каталога ExecStartPre=/bin/mkdir -p /data/squash/%i # изменение владельца для доступа по сети ExecStartPre=/bin/chown share:share /data/squash/%i # монтирование ExecStart=/bin/mount -t squashfs /data/squash/%i.squashfs /data/squash/%i # размонтирование ExecStop=/bin/umount /data/squash/%i # считать юнит запущенным после отработки ExecStart RemainAfterExit=yes [Install] WantedBy=multi-user.target

Из комментариев должна быть понятна его работа. Вместо » %i » будет подставляться строка после » @ » в названии службы.

Для теста можно создать некий образ с мусором командой:

mksquashfs /path/to/trash trash.squashfs -comp xz

Положить получившийся файл в «/data/squash» и запустить сервис:

sudo systemctl start squashmount@trash

Источник

How do you mount SquashFS in Linux?

In the “File systems” section, “Miscellaneous file systems” subsection, enable the “Squashed filesystem” option, whether as module or bundled with the kernel. It is only obligatory to compile SquashFS inside the kernel if you plan using squashed initial RAM disks (initrd).

Читайте также:  Linux get service list

How do I open a SquashFS file in Linux?

  1. Mount the squashfs FILE.SQUASHFS : sudo mount -t squashfs PATH/TO/FILE.SQUASHFS /mnt.
  2. Copy his content to DIRECTORY (must exist) : sudo cp -av /mnt/. PATH/TO/DIRECTORY.
  3. Unmount the squashfs FILE.SQUASHFS : sudo umount /mnt.

What is SquashFS in Linux?

Squashfs is a compressed read-only file system for Linux. Squashfs compresses files, inodes and directories, and supports block sizes from 4 KiB up to 1 MiB for greater compression. Several compression algorithms are supported.

How do I edit filesystem SquashFS?

You can mount a squashfs filesystem, but you cannot edit it. Squashfs is a readonly filesystem, so to edit it you will need to extract it first.

What is initrd used for?

initrd provides the capability to load a RAM disk by the boot loader. This RAM disk can then be mounted as the root file system and programs can be run from it. Afterwards, a new root file system can be mounted from a different device.

What is SquashFS in Ubuntu?

Squashfs is a highly compressed read-only filesystem for Linux. It uses zlib compression to compress both files, inodes and directories. Inodes in the system are very small and all blocks are packed to minimize data overhead. Block sizes greater than 4K are supported up to a maximum of 64K.

Why is SquashFS file system?

For archiving purposes, SquashFS gives you a lot more flexibility and performance speed than a . tar. gz archive. SquashFS is distributed as a Linux kernel source patch (which enables SquashFS read support in your kernel), and the mksquashfs tool, which creates squashed file systems (in a file or on a block device).

What is squashfs in Ubuntu?

What is squashfs IMG?

The squashfs. img is a SquashFS compressed, read-only, file system holding the Fedora operating system root file system inside another /LiveOS folder containing a rootfs.

What is the initrd in Linux?

The initial RAM disk (initrd) is an initial root file system that is mounted prior to when the real root file system is available. The initrd is bound to the kernel and loaded as part of the kernel boot procedure.

What is initrd image in Linux?

LINUX supports what is known as an initrd image ( initial rAM disk image). This is a small, +1.5 megabyte file system that is loaded by LILO and mounted by the kernel instead of the real file system. The kernel mounts this file system as a RAM disk, executes the file /linuxrc, and then only mounts the real file system.

Источник

Оцените статью
Adblock
detector