51

How can I attach a VHDX or VHD file in Linux?

I mean attach the virtual hard disk as a block device, and use external tools to read these devices.

The filesystem inside is not mountable. I do not need to mount the filesystem, but deal with it as if it was on a real hard disk.

I read the manual page of guestfish, but could not find how to do it.

Vlastimil Burián
  • 3,024
  • 2
  • 31
  • 52
Qin Yuhao
  • 519
  • 1
  • 4
  • 4
  • Another ressource: https://www.how2shout.com/linux/mount-virtual-hard-disk-vhd-file-ubuntu-linux/?unapproved=516&moderation-hash=6ecfb4ca6f97ff53d32570f3ba2e28f0#comment-516 – Cadoiz Jan 20 '21 at 00:36

1 Answers1

71

You can use libguestfs-tools to achieve this.


  1. First, you need to install it, on Ubuntu/Debian-like Linux that would be:

    sudo apt-get install libguestfs-tools
    
  2. Then, you can mount almost whatever you wish:

    guestmount --add yourVirtualDisk.vhdx --inspector --ro /mnt/anydirectory
    

    This is just an example of read-only extraction point.


Hints:

  1. Run it as normal user, i.e.:

    guestmount ...
    

    Instead of:

    sudo guestmount ...
    
  2. Switches; citations from man page:

    --add
    

    Add a block device or virtual machine image.

    --inspector
    

    Using virt-inspector(1) code, inspect the disks looking for an operating system and mount filesystems as they would be mounted on the real virtual machine.

    --ro
    

    Add devices and mount everything read-only. Also disallow writes and make the disk appear read-only to FUSE.

Vlastimil Burián
  • 3,024
  • 2
  • 31
  • 52
  • 2
    When the `vhd` file is too big (say 1TB with millions of files), `guestmount` could successfully mount it but fail in reading files (you can't even `ls -1f` to see the files). This must be an unsolved bug. Anyone who encounters this problem can try [qemu](https://askubuntu.com/a/359852/768041). – Stan Dec 11 '17 at 06:44
  • And `guestmount` (with no args at all) just segfaults on me (after newly installed here on a Raspbian Jessie). – Sz. Jul 29 '18 at 17:07
  • 2
    Thanks for bringing up `guestmount` which I hoped would allow me to mount my .vhd containing a single partition with a exFAT-volume inside. Sadly, `guestmount` (v1.38.4) did not accept my specification of the volume within the `.vhd` and asking me `Did you mean to mount one of these filesystems?` ... `/dev/sda1 (exfat)`. What I had specified was `-m "/dev/sda1"` as this was what `virt-filesystems` had returned. When the volume is NTFS, mounting works. And yes, I've got `exfat-utils.x86_64` (v1.2.8, a fuse-fs-driver) installed. – antiplex Aug 23 '18 at 13:39
  • 1
    I can confirm this works for VHD(x) images downloaded from Azure VMs. – Konrads Sep 28 '20 at 02:08
  • 8
    If anyone is trying to do this on Windows via WSL, this web page has the additional info you need to complete the task: https://blog.codybunch.com/2020/10/16/WSL2-Mount-vhdx-to-WSL2/ – NessDan Mar 01 '21 at 17:14