Linux 如何在镜像文件里面创建分区

.
.
.
.
.
有的时候我们会通过dd命令来创建一个镜像文件,并且直接使用mkfs命令将其格式化。但如果镜像文件里面并不直接是文件系统,而是包含分区的,要怎么才能使用里面的分区呢?
接下来我们一步一步操作,创建一个镜像文件,对它进行分区、格式化,最后挂载使用。

  • 创建镜像
>$ dd if=/dev/zero of=test.img bs=1024 count=8192
8192+0 records in
8192+0 records out
8388608 bytes (8.4 MB, 8.0 MiB) copied, 0.0114896 s, 730 MB/s

使用dd命令创建一个 8MB 的 test.img 镜像文件。

  • 对镜像文件进行分区
>$ fdisk test.img 

Welcome to fdisk (util-linux 2.37.4).
Changes will remain in memory only, until you decide to write them.
Be careful before using the write command.

Device does not contain a recognized partition table.
Created a new DOS disklabel with disk identifier 0x2caa228c.

Command (m for help): n
Partition type
   p   primary (0 primary, 0 extended, 4 free)
   e   extended (container for logical partitions)
Select (default p): 

Using default response p.
Partition number (1-4, default 1): 
First sector (2048-16383, default 2048): 
Last sector, +/-sectors or +/-size{K,M,G,T,P} (2048-16383, default 16383): 

Created a new partition 1 of type 'Linux' and of size 7 MiB.

Command (m for help): p
Disk test.img: 8 MiB, 8388608 bytes, 16384 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: dos
Disk identifier: 0x2caa228c

Device     Boot Start   End Sectors Size Id Type
test.img1        2048 16383   14336   7M 83 Linux

Command (m for help): w
The partition table has been altered.
Syncing disks.

使用fdisk命令在 test.img 文件里面创建一个主分区,使用了默认的 Linux 文件系统格式。

  • 将镜像文件虚拟成块设备
>$ sudo losetup -f --show test.img 
/dev/loop0

test.img已经被虚拟为/dev/loop0设备了。

  • 挂载虚拟文件系统
>$ sudo kpartx -av /dev/loop0 
add map loop0p1 (253:0): 0 14336 linear 7:0 2048
>$ ls -l /dev/mapper/
total 0
crw-------. 1 root root 10, 236 Mar 16 09:50 control
lrwxrwxrwx. 1 root root       7 Mar 25 17:01 loop0p1 -> ../dm-0

使用kpartx命令将镜像文件虚拟为块设备,此时可以看到已经在/dev/mapper目录下生成了test.img1分区对应的设备文件loop0p1

  • 格式化分区
$ sudo mkfs.ext4 /dev/mapper/loop0p1 
mke2fs 1.46.3 (27-Jul-2021)
Discarding device blocks: done                            
Creating filesystem with 7168 1k blocks and 1792 inodes

Allocating group tables: done                            
Writing inode tables: done                            
Creating journal (1024 blocks): done
Writing superblocks and filesystem accounting information: done
  • 挂载分区
>$ sudo mount /dev/mapper/loop0p1 /mnt
>$ mount -l | tail -n 1
/dev/mapper/loop0p1 on /mnt type ext4 (rw,relatime,seclabel)
>$ ls -la /mnt
total 17
drwxr-xr-x.  3 root root  1024 Mar 25 17:04 .
dr-xr-xr-x. 18 root root  4096 Nov 11 20:44 ..
drwx------.  2 root root 12288 Mar 25 17:04 lost+found

可以看到,分区已经成功挂载上了,并且可以使用了。
接下来我们将分区卸载掉。

  • 卸载设备
# 卸载挂载点
>$ sudo umount /mnt
# 卸载分区
>$ sudo kpartx -d /dev/loop0
# 卸载虚拟块设备
>$ sudo losetup -d /dev/loop0

posted on 2022-03-25 17:13  0xCAFEBABE  阅读(490)  评论(0编辑  收藏  举报

导航