home products tech support contact us

 Linux 技術支援    ⇒   基礎篇    進階篇    補腦篇    指令索引    中⇒ENG
版權所有, 引用請註明出處
 

kpartx - Managing Virtual Device Setups




kpartx serves as an advanced counterpart to losetup. For instance, if you've created an image file with the contents of an entire disk (including multiple partitions) using the dd command, you can use kpartx to access the contents of the original disk without having to restore the image file back to a physical disk.

The usage of kpartx is similar to losetup. The syntax is kpartx [-adv] image-file. The "-a" option associates the image file with loop devices, the "-d" option removes loop device associations, and the "-v" option displays detailed loop device mapping.


# dd if=/dev/zero of=1g-image bs=1G count=1 ←Create a 1GB image file "1g-image"
# losetup /dev/loop0 1g-image ←Associate the image file with a loop device "/dev/loop0"
#
#(The following steps simulate partitioning the virtual device file "/dev/loop0" as a disk)
# parted /dev/loop0 mklabel gpt ←Specify a GPT partition table
# parted /dev/loop0 mkpart par1 0% 40% ←Create a partition of first 40%, labeled "par1"
# parted /dev/loop0 mkpart par2 40% 100% ←Create a partition of last 60%, labeled "par2
#
# mkfs -t ext3 /dev/loop0p1 ←Format the first partition
# mkfs -t ext3 /dev/loop0p2 ←Format the second partition
#
# dd if=/dev/loop0 of=hd_img ← Create a disk image "hd_img" from the loop device "/dev/loop0"

# kpartx -av hd_img ←Associate the image file with a virtual device "/dev/loop1"
add map loop1p1 (253:0): 0 1046528 linear /dev/loop1 2048
add map loop1p2 (253:1): 0 1046528 linear /dev/loop1 1048576

The final step in the above sequence demonstrates how to use kpartx to access the content of the original disk through the image file. After these operations, "/dev/loop1p1" corresponds to the original disk's first partition, and "/dev/loop1p2" corresponds to the second partition.

For more operations, examples, and explanations, you can refer to this link.