Linux下VirtualBox中运行真实磁盘上的操作系统

虽然各种虚拟机都会说把真实磁盘的分直接给虚拟机用会如何如何有风险,但是好处也是显而易见的:可以选择是直接运行或是在Linux下的虚拟机运行某个操作系统,同时节约了磁盘空间和同步时间。

我这样做已经有一段时间了,除了Windows会发现硬件改变要求重新激活之外,还没有发现问题 :-) 但是周围的同学似乎觉得这样做比较麻烦,很有风险,或者无从下手。其实比较简单也没有这么可怕啦,下面普及一下:

首先要创建一个特殊的虚拟磁盘文件,指向真实磁盘的某个分区,这可以参考VirtualBox用户手册中的9.10章节。简单来说:

注:由于这些命令需要/dev/sda的读写权限,以后虚拟机在使用这些vmdk文件的时候,也需要这样的权限,建议把当前用户加在disk组里解决问题:gpasswd disk -a `whoami`

# 把整个sda映射出去
VBoxManage internalcommands createrawvmdk -filename /path/to/sda.vmdk -rawdisk /dev/sda
# 或者,处于安全考虑,只允许sda1和sda5在虚拟机里用到,虚拟机里仍然可以知道有其他分区存在,但是不能读写
VBoxManage internalcommands createrawvmdk -filename /path/to/sda1_and_sda5.vmdk -rawdisk /dev/sda -partitions 1,5 -relative

这里的relative参数保证了创建出来的虚拟磁盘文件的可移植性,在sda1或者sda5的实际位置和大小变化后也可以用,没有这个参数的话到时候就要重新创建一遍vmdk文件了。
创建好可能会产生多个文件:a.vmdk和a-pt.vmdk,实际在虚拟机里使用前一个文件,后一个需要存在。

这样就基本完成啦,不过如果你打开这样配置的虚拟机后就会发现一个问题,MBR在这种默认情况下是和真实硬盘相同的,GRUB是和主机相同的,如果GRUB配置文件所在分区虚拟机没有访问权限的话,就会引导不能 8-O

当然,虚拟机里的MBR可以设置得和主机不一样,不过操作起来比较麻烦,据说也有一定的危险。安全的做法是使用携带特定配置文件的GRUB的Live CD镜像来引导,下面就开始做这样一张CD镜像(适用于GRUB 1.0):

# 准备一个目录
mkdir -p iso/boot/grub
# 复制必要文件
cp /usr/lib/grub/*-pc/stage2_eltorito /boot/grub/menu.lst iso/boot/grub
# 编辑复制过来的 menu.lst ,去掉其中的 savedefault ,...
vim iso/boot/grub/menu.lst
# 创建iso
mkisofs -R -b boot/grub/stage2_eltorito -no-emul-boot -boot-load-size 4 -boot-info-table -o grub-custom.iso iso

在虚拟机里设置使用这张iso引导之后,就大功告成啦~

host_windows_7_in_virtualbox

3 thoughts on “Linux下VirtualBox中运行真实磁盘上的操作系统

  1. Pingback: 打造高效的工作环境(番外篇1): windows/linux钗黛双收 | Mr.Cpp

  2. Thank you for your entire labor on this web site. My mom take interest in participating in investigations and it is obvious why. My partner and i learn all regarding the lively tactic you produce simple things through your web site and in addition invigorate response from the others on the subject then our favorite princess is truly studying a whole lot. Take advantage of the rest of the year. You have been doing a superb job.

Leave a Reply to ipcjs Cancel reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>