Thursday, August 07, 2008

Howto mount disk image

如果你今天面對的是disk image而不是一般的partition image,當使用mount -o loop時會無法mount成功。這很容易理解,因為你必須知道disk image中partition的位置後才能mount起來,怎麼做呢?以下將會說明:

需求: mount test.img 並更改第一個partition中的某個檔案

我們先看看如果直接用mount -o loop會如何:
lawrence@lawrence-x24:~/Desktop$ sudo mount -o loop test.img /mnt/test/
mount: you must specify the filesystem type
lawrence@lawrence-x24:~/Desktop$ sudo mount -o loop -t ext3 test.img /mnt/test/
mount: wrong fs type, bad option, bad superblock on /dev/loop0,
missing codepage or helper program, or other error
In some cases useful info is found in syslog - try
dmesg | tail or so

恩,看起來是不work......

所以我必須先知道test.img的磁軌與磁區大小才能算出第一個partition的位置:
lawrence@lawrence-x24:~/Desktop$ fdisk -l test.img
You must set cylinders.
You can do this from the extra functions menu.

Disk test.img: 0 MB, 0 bytes
16 heads, 63 sectors/track, 0 cylinders
Units = cylinders of 1008 * 512 = 516096 bytes
Disk identifier: 0x00000000

所用裝置 Boot Start End Blocks Id System
test.img1 1 32 16096+ 83 Linux

得知每個 track 共 63 sectors, 每個 sector 是 512bytes,故得知第一個partition是在63*512=32256

接下來利用losetup將第一個partition先掛到/dev/loop0,並驗證:
lawrence@lawrence-x24:~/Desktop$ sudo losetup --offset 32256 /dev/loop0 test.img
lawrence@lawrence-x24:~/Desktop$ sudo losetup /dev/loop0
/dev/loop0: [0803]:865823 (test.img), offset 32256

好了,將它mount起來吧!
lawrence@lawrence-x24:~/Desktop$ sudo mount /dev/loop0 /mnt/test/
lawrence@lawrence-x24:~/Desktop$ df -h | grep test
/dev/loop0 16M 7.9M 6.6M 55% /mnt/test

修改完畢後,一樣將他umount掉並detach /dev/loop0
lawrence@lawrence-x24:/mnt/test$ cd
lawrence@lawrence-x24:~$ sudo umount /mnt/test
lawrence@lawrence-x24:~$ df -h | grep test
lawrence@lawrence-x24:~$ sudo losetup -d /dev/loop0
lawrence@lawrence-x24:~$ sudo losetup /dev/loop0
loop: can't get info on device /dev/loop0: 沒有此一裝置或位址

以上希望對大家有幫助。

PS. Redhat中如果要位移,是下達losetup -o 32256而不是losetup --offset 32256

1 comment:

瘋狂帽客 said...

補充一下如果要mount第二個partition可以這樣做:

1. fdisk -lu test.img
-> 得知第二個partition開始的sector, so offset=sector * sector size (512bytes)

fdisk -u When listing partition tables, give sizes in sec­tors instead of cylinders.

PS. 更精簡的mount方法:
mount -o loop,offset=32256 test.img /mnt/test