Cari di RHE Linux 
    RHE Linux User Manual
Daftar Isi
(Sebelumnya) 24 : Chapter 14. Managing gues ...24 : Chapter 17. Virtual Networking (Berikutnya)

Virtualization Administration Guide

Chapter 16. Guest disk access with offline tools

16.1. Introduction

Red Hat Enterprise Linux 6 comes with tools to access, edit and create guest disks or other disk images. There are several uses for these tools, including:
  • Viewing or downloading files located on a guest disk.
  • Editing or uploading files onto a guest disk.
  • Reading or writing guest configuration.
  • Reading or writing the Windows Registry in Windows guests.
  • Preparing new disk images containing files, directories, file systems, partitions, logical volumes and other options.
  • Rescuing and repairing guests that fail to boot or those that need boot configuration changes.
  • Monitoring disk usage of guests.
  • Auditing compliance of guests, for example to organizational security standards.
  • Deploying guests by cloning and modifying templates.
  • Reading CD and DVD ISO and floppy disk images.

Warning

You must never use these tools to write to a guest or disk image which is attached to a running virtual machine, not even to open such a disk image in write mode. Doing so will result in disk corruption of the guest. The tools try to prevent you from doing this, however do not catch all cases. If there is any suspicion that a guest might be running, it is strongly recommended that the tools not be used, or at least always use the tools in read-only mode.

16.2. Terminology

This section explains the terms used throughout this chapter.
  • libguestfs (GUEST FileSystem LIBrary) - the underlying C library that provides the basic functionality for opening disk images, reading and writing files and so on. You can write C programs directly to this API, but it is quite low level.
  • guestfish (GUEST Filesystem Interactive SHell) is an interactive shell that you can use from the command line or from shell scripts. It exposes all of the functionality of the libguestfs API.
  • Various virt tools are built on top of libguestfs, and these provide a way to perform specific single tasks from the command line. Tools include virt-df, virt-rescue, virt-resize and virt-edit.
  • hivex and Augeas are libraries for editing the Windows Registry and Linux configuration files respectively. Although these are separate from libguestfs, much of the value of libguestfs comes from the combination of these tools.
  • guestmount is an interface between libguestfs and FUSE. It is primarily used to mount file systems from disk images on your host. This functionality is not necessary, but can be useful.

16.3. Installation

To install libguestfs, guestfish, the libguestfs tools, guestmount and support for Windows guests, subscribe to the RHEL V2WIN channel, go to the Red Hat Website and run the following command:
# yum install libguestfs guestfish libguestfs-tools libguestfs-mount libguestfs-winsupport
To install every libguestfs-related package including the language bindings, run the following command:
# yum install '*guestf*'

16.4. The guestfish shell

guestfish is an interactive shell that you can use from the command line or from shell scripts to access guest file systems. All of the functionality of the libguestfs API is available from the shell.
To begin viewing or editing a virtual machine disk image, run the following command, substituting the path to your desired disk image:
guestfish --ro -a /path/to/disk/image
--ro means that the disk image is opened read-only. This mode is always safe but does not allow write access. Only omit this option when you are certain that the guest is not running, or the disk image is not attached to a live guest. It is not possible to use libguestfs to edit a live guest, and attempting to will assuredly result in irreversible disk corruption.
/path/to/disk/image is the path to the disk. This can be a file, a host logical volume (such as /dev/VG/LV), a host device (/dev/cdrom) or a SAN LUN (/dev/sdf3).

Note

libguestfs and guestfish do not require root privileges. You only need to run them as root if the disk image being accessed needs root to read and/or write.
When you start guestfish interactively, it will display this prompt:
 guestfish --ro -a /path/to/disk/imageWelcome to guestfish, the libguestfs filesystem interactive shell for editing virtual machine filesystems.  Type: 'help' for help on commands   'man' to read the manual   'quit' to quit the shell ><fs>
At the prompt, type run to initiate the library and attach the disk image. This can take up to 30 seconds the first time it is done. Subsequent starts will complete much faster.

Note

libguestfs will use hardware virtualization acceleration such as KVM (if available) to speed up this process.
Once the run command has been entered, other commands can be used, as the following section demonstrates.

16.4.1. Viewing file systems with guestfish

16.4.1.1. Manual listing and viewing

The list-filesystems command will list file systems found by libguestfs. This output shows a Red Hat Enterprise Linux 4 disk image:
><fs> run><fs> list-filesystems/dev/vda1: ext3/dev/VolGroup00/LogVol00: ext3/dev/VolGroup00/LogVol01: swap
This output shows a Windows disk image:
><fs> run><fs> list-filesystems/dev/vda1: ntfs/dev/vda2: ntfs
Other useful commands are list-devices, list-partitions, lvs, pvs, vfs-type and file. You can get more information and help on any command by typing help command, as shown in the following output:
><fs> help vfs-type NAME vfs-type - get the Linux VFS type corresponding to a mounted device  SYNOPSIS vfs-type device  DESCRIPTION This command gets the filesystem type corresponding to the filesystem on "device". For most filesystems, the result is the name of the Linux VFS module which would be used to mount this filesystem if you mounted it without specifying the filesystem type. For example a string such as "ext3" or "ntfs".
To view the actual contents of a file system, it must first be mounted. This example uses one of the Windows partitions shown in the previous output (/dev/vda2), which in this case is known to correspond to the C:\ drive:
><fs> mount-ro /dev/vda2 /><fs> ll /total 1834753 drwxrwxrwx  1 root root   4096 Nov  1 11:40 . drwxr-xr-x 21 root root   4096 Nov 16 21:45 .. lrwxrwxrwx  2 root root 60 Jul 14  2009 Documents and Settings drwxrwxrwx  1 root root   4096 Nov 15 18:00 Program Files drwxrwxrwx  1 root root   4096 Sep 19 10:34 Users drwxrwxrwx  1 root root  16384 Sep 19 10:34 Windows
You can use guestfish commands such as ls, ll, cat, more, download and tar-out to view and download files and directories.

Note

There is no concept of a current working directory in this shell. Unlike ordinary shells, you cannot for example use the cd command to change directories. All paths must be fully qualified starting at the top with a forward slash (/) character. Use the Tab key to complete paths.
To exit from the guestfish shell, type exit or enter Ctrl+d.

16.4.1.2. Via guestfish inspection

Instead of listing and mounting file systems by hand, it is possible to let guestfish itself inspect the image and mount the file systems as they would be in the guest. To do this, add the -i option on the command line:
guestfish --ro -a /path/to/disk/image -iWelcome to guestfish, the libguestfs filesystem interactive shell for editing virtual machine filesystems.  Type: 'help' for help on commands   'man' to read the manual   'quit' to quit the shell  Operating system: Red Hat Enterprise Linux AS release 4 (Nahant Update 8) /dev/VolGroup00/LogVol00 mounted on / /dev/vda1 mounted on /boot  ><fs> ll / total 210 drwxr-xr-x. 24 root root  4096 Oct 28 09:09 . drwxr-xr-x  21 root root  4096 Nov 17 15:10 .. drwxr-xr-x.  2 root root  4096 Oct 27 22:37 bin drwxr-xr-x.  4 root root  1024 Oct 27 21:52 boot drwxr-xr-x.  4 root root  4096 Oct 27 21:21 dev drwxr-xr-x. 86 root root 12288 Oct 28 09:09 etc [etc]
Because guestfish needs to start up the libguestfs back end in order to perform the inspection and mounting, the run command is not necessary when using the -i option. The -i option works for many common Linux and Windows guests.

16.4.1.3. Accessing a guest by name

A guest can be accessed from the command line when you specify its name as known to libvirt (in other words, as it appears in virsh list --all). Use the -d option to access a guest by its name, with or without the -i option:
guestfish --ro -d GuestName -i

16.4.2. Modifying files with guestfish

To modify files, create directories or make other changes to a guest, first heed the warning at the beginning of this section: your guest must be shut down. Editing or changing a running disk with guestfish will result in disk corruption. This section gives an example of editing the /boot/grub/grub.conf file. When you are sure the guest is shut down you can omit the --ro flag in order to get write access via a command such as:
guestfish -d RHEL3 -iWelcome to guestfish, the libguestfs filesystem interactive shell for editing virtual machine filesystems.  Type: 'help' for help on commands   'man' to read the manual   'quit' to quit the shell  Operating system: Red Hat Enterprise Linux AS release 3 (Taroon Update 9) /dev/vda2 mounted on / /dev/vda1 mounted on /boot ><fs> edit /boot/grub/grub.conf
Commands to edit files include edit, vi and emacs. Many commands also exist for creating files and directories, such as write, mkdir, upload and tar-in.

16.4.3. Other actions with guestfish

You can also format file systems, create partitions, create and resize LVM logical volumes and much more, with commands such as mkfs, part-add, lvresize, lvcreate, vgcreate and pvcreate.

16.4.4. Shell scripting with guestfish

Once you are familiar with using guestfish interactively, according to your needs, writing shell scripts with it may be useful. The following is a simple shell script to add a new MOTD (message of the day) to a guest:
#!/bin/bash - set -e guestname="$1"  guestfish -d "$guestname" -i <<'EOF'   write /etc/motd "Welcome to Acme Incorporated."   chmod 0644 /etc/motd EOF

16.4.5. Augeas and libguestfs scripting

Combining libguestfs with Augeas can help when writing scripts to manipulate Linux guest configuration. For example, the following script uses Augeas to parse the keyboard configuration of a guest, and to print out the layout. Note that this example only works with guests running Red Hat Enterprise Linux:
#!/bin/bash - set -e guestname="$1"  guestfish -d "$1" -i --ro <<'EOF'   aug-init / 0   aug-get /files/etc/sysconfig/keyboard/LAYOUT EOF
Augeas can also be used to modify configuration files. You can modify the above script to change the keyboard layout:
#!/bin/bash - set -e guestname="$1"  guestfish -d "$1" -i <<'EOF'   aug-init / 0   aug-set /files/etc/sysconfig/keyboard/LAYOUT '"gb"'   aug-save EOF
Note the three changes between the two scripts:
  1. The --ro option has been removed in the second example, giving the ability to write to the guest.
  2. The aug-get command has been changed to aug-set to modify the value instead of fetching it. The new value will be "gb" (including the quotes).
  3. The aug-save command is used here so Augeas will write the changes out to disk.

Note

More information about Augeas can be found on the website http://augeas.net.
guestfish can do much more than we can cover in this introductory document. For example, creating disk images from scratch:
guestfish -N fs
Or copying out whole directories from a disk image:
><fs> copy-out /home /tmp/home
For more information see the man page guestfish(1).

16.5. Other commands

This section describes tools that are simpler equivalents to using guestfish to view and edit guest disk images.
  • virt-cat is similar to the guestfish download command. It downloads and displays a single file to the guest. For example:
    # virt-cat RHEL3 /etc/ntp.conf | grep ^server server 127.127.1.0  # local clock
  • virt-edit is similar to the guestfish edit command. It can be used to interactively edit a single file within a guest. For example, you may need to edit the grub.conf file in a Linux-based guest that will not boot:
    # virt-edit LinuxGuest /boot/grub/grub.conf
    virt-edit has another mode where it can be used to make simple non-interactive changes to a single file. For this, the -e option is used. This command, for example, changes the root password in a Linux guest to having no password:
    # virt-edit LinuxGuest /etc/passwd -e 's/^root:.*?:/root::/'
  • virt-ls is similar to the guestfish ls, ll and find commands. It is used to list a directory or directories (recursively). For example, the following command would recursively list files and directories under /home in a Linux guest:
    # virt-ls -R LinuxGuest /home/ | less

16.6. virt-rescue: The rescue shell

16.6.1. Introduction

This section describes virt-rescue, which can be considered analogous to a rescue CD for virtual machines. It boots a guest into a rescue shell so that maintenance can be performed to correct errors and the guest can be repaired.
There is some overlap between virt-rescue and guestfish. It is important to distinguish their differing uses. virt-rescue is for making interactive, ad-hoc changes using ordinary Linux file system tools. It is particularly suited to rescuing a guest that has gone wrong. virt-rescue cannot be scripted.
In contrast, guestfish is particularly useful for making scripted, structured changes through a formal set of commands (the libguestfs API), although it can also be used interactively.

16.6.2. Running virt-rescue

Before you use virt-rescue on a guest, make sure the guest is not running, otherwise disk corruption will occur. When you are sure the guest is not live, enter:
virt-rescue GuestName
(where GuestName is the guest name as known to libvirt), or:
virt-rescue /path/to/disk/image
(where the path can be any file, any logical volume, LUN, or so on) containing a guest disk.
You will first see output scroll past, as virt-rescue boots the rescue VM. In the end you will see:
Welcome to virt-rescue, the libguestfs rescue shell.  Note: The contents of / are the rescue appliance. You have to mount the guest's partitions under /sysroot before you can examine them.  bash: cannot set terminal process group (-1): Inappropriate ioctl for device bash: no job control in this shell ><rescue>
The shell prompt here is an ordinary bash shell, and a reduced set of ordinary Red Hat Enterprise Linux commands is available. For example, you can enter:
><rescue> fdisk -l /dev/vda
The previous command will list disk partitions. To mount a file system, it is suggested that you mount it under /sysroot, which is an empty directory in the rescue machine for the user to mount anything you like. Note that the files under / are files from the rescue VM itself:
><rescue> mount /dev/vda1 /sysroot/EXT4-fs (vda1): mounted filesystem with ordered data mode. Opts: (null)><rescue> ls -l /sysroot/grub/ total 324 -rw-r--r--. 1 root root 63 Sep 16 18:14 device.map -rw-r--r--. 1 root root  13200 Sep 16 18:14 e2fs_stage1_5 -rw-r--r--. 1 root root  12512 Sep 16 18:14 fat_stage1_5 -rw-r--r--. 1 root root  11744 Sep 16 18:14 ffs_stage1_5 -rw-------. 1 root root   1503 Oct 15 11:19 grub.conf [...]
When you are finished rescuing the guest, exit the shell by entering exit or Ctrl+d.
virt-rescue has many command line options. The options most often used are:
  • --ro: Operate in read-only mode on the guest. No changes will be saved. You can use this to experiment with the guest. As soon as you exit from the shell, all of your changes are discarded.
  • --network: Enable network access from the rescue shell. Use this if you need to, for example, download RPM or other files into the guest.

16.7. virt-df: Monitoring disk usage

16.7.1. Introduction

This section describes virt-df, which displays file system usage from a disk image or a guest. It is similar to the Linux df command, but for virtual machines.

16.7.2. Running virt-df

To display file system usage for all file systems found in a disk image, enter the following:
# virt-df /dev/vg_guests/RHEL6 Filesystem   1K-blocks   Used  Available  Use% RHEL6:/dev/sda1 101086  10233  85634   11% RHEL6:/dev/VolGroup00/LogVol00 7127864 2272744 4493036   32%
(Where /dev/vg_guests/RHEL6 is a Red Hat Enterprise Linux 4 guest disk image. The path in this case is the host logical volume where this disk image is located.)
You can also use virt-df on its own to list information about all of your guests (ie. those known to libvirt). The virt-df command recognizes some of the same options as the standard df such as -h (human-readable) and -i (show inodes instead of blocks).
virt-df also works on Windows guests:
# virt-df -h Filesystem   Size   Used  Available  Use% F14x64:/dev/sda1   484.2M  66.3M 392.9M   14% F14x64:/dev/vg_f14x64/lv_root 7.4G   3.0G   4.4G   41% RHEL6brewx64:/dev/sda1 484.2M  52.6M 406.6M   11% RHEL6brewx64:/dev/vg_rhel6brewx64/lv_root 13.3G   3.4G   9.2G   26% Win7x32:/dev/sda1  100.0M  24.1M  75.9M   25% Win7x32:/dev/sda2 19.9G 7.4G  12.5G   38%

Note

You can use virt-df safely on live guests, since it only needs read-only access. However, you should not expect the numbers to be precisely the same as those from a df command running inside the guest. This is because what is on disk will be slightly out of synch with the state of the live guest. Nevertheless it should be a good enough approximation for analysis and monitoring purposes.
virt-df is designed to allow you to integrate the statistics into monitoring tools, databases and so on. This allows system administrators to generate reports on trends in disk usage, and alerts if a guest is about to run out of disk space. To do this you should use the --csv option to generate machine-readable Comma-Separated-Values (CSV) output. CSV output is readable by most databases, spreadsheet software and a variety of other tools and programming languages. The raw CSV looks like the following:
# virt-df --csv WindowsGuest Virtual Machine,Filesystem,1K-blocks,Used,Available,Use% Win7x32,/dev/sda1,102396,24712,77684,24.1% Win7x32,/dev/sda2,20866940,7786652,13080288,37.3%
For resources and ideas on how to process this output to produce trends and alerts, refer to the following URL: http://virt-tools.org/learning/advanced-virt-df/.

16.8. virt-resize: resizing guests offline

16.8.1. Introduction

This section describes virt-resize, a tool for expanding or shrinking guests. It only works for guests which are offline (shut down). It works by copying the guest image and leaving the original disk image untouched. This is ideal because you can use the original image as a backup, however there is a trade-off as you need twice the amount of disk space.

16.8.2. Expanding a disk image

This section demonstrates a simple case of expanding a disk image:
  1. Locate the disk image to be resized. You can use the command virsh dumpxml GuestName for a libvirt guest.
  2. Decide on how you wish to expand the guest. Run virt-df -h and virt-list-partitions -lh on the guest disk, as shown in the following output:
    # virt-df -h /dev/vg_guests/RHEL6Filesystem  Size   Used  Available  Use%RHEL6:/dev/sda1 98.7M  10.0M  83.6M   11%RHEL6:/dev/VolGroup00/LogVol00  6.8G   2.2G   4.3G   32%# virt-list-partitions -lh /dev/vg_guests/RHEL6/dev/sda1 ext3 101.9M/dev/sda2 pv 7.9G
This example will demonstrate how to:
  • Increase the size of the first (boot) partition, from approximately 100MB to 500MB.
  • Increase the total disk size from 8GB to 16GB.
  • Expand the second partition to fill the remaining space.
  • Expand /dev/VolGroup00/LogVol00 to fill the new space in the second partition.
  1. Make sure the guest is shut down.
  2. Rename the original disk as the backup. How you do this depends on the host storage environment for the original disk. If it is stored as a file, use the mv command. For logical volumes (as demonstrated in this example), use lvrename:
    # lvrename /dev/vg_guests/RHEL6 /dev/vg_guests/RHEL6.backup
  3. Create the new disk. The requirements in this example are to expand the total disk size up to 16GB. Since logical volumes are used here, the following command is used:
    # lvcreate -L 16G -n RHEL6 /dev/vg_guestsLogical volume "RHEL6" created
  4. The requirements from step 2 are expressed by this command:
    # virt-resize \   /dev/vg_guests/RHEL6.backup /dev/vg_guests/RHEL6 \   --resize /dev/sda1=500M \   --expand /dev/sda2 \   --LV-expand /dev/VolGroup00/LogVol00
    The first two arguments are the input disk and output disk. --resize /dev/sda1=500M resizes the first partition up to 500MB. --expand /dev/sda2 expands the second partition to fill all remaining space. --LV-expand /dev/VolGroup00/LogVol00 expands the guest logical volume to fill the extra space in the second partition.
    virt-resize describes what it is doing in the output:
    Summary of changes:   /dev/sda1: partition will be resized from 101.9M to 500.0M   /dev/sda1: content will be expanded using the 'resize2fs' method   /dev/sda2: partition will be resized from 7.9G to 15.5G   /dev/sda2: content will be expanded using the 'pvresize' method   /dev/VolGroup00/LogVol00: LV will be expanded to maximum size   /dev/VolGroup00/LogVol00: content will be expanded using the 'resize2fs' method   Copying /dev/sda1 ...   [#####################################################]   Copying /dev/sda2 ...   [#####################################################]   Expanding /dev/sda1 using the 'resize2fs' method   Expanding /dev/sda2 using the 'pvresize' method   Expanding /dev/VolGroup00/LogVol00 using the 'resize2fs' method
  5. Try to boot the virtual machine. If it works (and after testing it thoroughly) you can delete the backup disk. If it fails, shut down the virtual machine, delete the new disk, and rename the backup disk back to its original name.
  6. Use virt-df and/or virt-list-partitions to show the new size:
    # virt-df -h /dev/vg_pin/RHEL6 Filesystem  Size   Used  Available  Use%   RHEL6:/dev/sda1   484.4M  10.8M 448.6M 3%   RHEL6:/dev/VolGroup00/LogVol00 14.3G   2.2G  11.4G   16%
Resizing guests is not an exact science. If virt-resize fails, there are a number of tips that you can review and attempt in the virt-resize(1) man page. For some older Red Hat Enterprise Linux guests, you may need to pay particular attention to the tip regarding GRUB.

16.9. virt-inspector: inspecting guests

16.9.1. Introduction

virt-inspector is a tool for inspecting a disk image to find out what operating system it contains.

Note

Red Hat Enterprise Linux 6.2 ships with two variations of this progam: virt-inspector is the original program as found in Red Hat Enteprise Linux 6.0 and is now deprecated upstream. virt-inspector2 is the same as the new upstream virt-inspector program.

16.9.2. Installation

To install virt-inspector and the documentation, enter the following command:
# yum install libguestfs-tools libguestfs-devel
To process Windows guests you must also install libguestfs-winsupport. Refer to Section 16.10.2, "Installation" for details. The documentation, including example XML output and a Relax-NG schema for the output, will be installed in /usr/share/doc/libguestfs-devel-*/ where "*" is replaced by the version number of libguestfs.

16.9.3. Running virt-inspector

You can run virt-inspector against any disk image or libvirt guest as shown in the following example:
virt-inspector --xml disk.img > report.xml
Or as shown here:
virt-inspector --xml GuestName > report.xml
The result will be an XML report (report.xml). The main components of the XML file are a top-level <operatingsytems> element containing usually a single <operatingsystem> element, similar to the following:
 <operatingsystems>   <operatingsystem> <!-- the type of operating system and Linux distribution --> <name>linux</name> <distro>rhel</distro> <!-- the name, version and architecture --> <product_name>Red Hat Enterprise Linux Server release 6.4 </product_name> <major_version>6</major_version> <minor_version>4</minor_version> <package_format>rpm</package_format> <package_management>yum</package_management> <root>/dev/VolGroup/lv_root</root>  <!-- how the filesystems would be mounted when live --> <mountpoints>   <mountpoint dev="/dev/VolGroup/lv_root">/</mountpoint>   <mountpoint dev="/dev/sda1">/boot</mountpoint>   <mountpoint dev="/dev/VolGroup/lv_swap">swap</mountpoint> </mountpoints> < !-- filesystems-->  <filesystem dev="/dev/VolGroup/lv_root"> <label></label> <uuid>b24d9161-5613-4ab8-8649-f27a8a8068d3</uuid> <type>ext4</type> <content>linux-root</content> <spec>/dev/mapper/VolGroup-lv_root</spec>  </filesystem>  <filesystem dev="/dev/VolGroup/lv_swap"> <type>swap</type> <spec>/dev/mapper/VolGroup-lv_swap</spec>  </filesystem> <!-- packages installed --> <applications>   <application> <name>firefox</name> <version>3.5.5</version> <release>1.fc12</release>   </application> </applications>   </operatingsystem> </operatingsystems>
Processing these reports is best done using W3C standard XPath queries. Red Hat Enterprise Linux 6 comes with a command line program (xpath) which can be used for simple instances; however, for long-term and advanced usage, you should consider using an XPath library along with your favorite programming language.
As an example, you can list out all file system devices using the following XPath query:
virt-inspector --xml GuestName | xpath //filesystem/@dev Found 3 nodes: -- NODE -- dev="/dev/sda1" -- NODE -- dev="/dev/vg_f12x64/lv_root" -- NODE -- dev="/dev/vg_f12x64/lv_swap"
Or list the names of all applications installed by entering:
 virt-inspector --xml GuestName | xpath //application/name [...long list...]

16.10. virt-win-reg: Reading and editing the Windows Registry

16.10.1. Introduction

virt-win-reg is a tool that manipulates the Registry in Windows guests. It can be used to read out registry keys. You can also use it to make changes to the Registry, but you must never try to do this for live/running guests, as it will result in disk corruption.

16.10.2. Installation

To use virt-win-reg you must run the following:
# yum install libguestfs-tools libguestfs-winsupport

16.10.3. Using virt-win-reg

To read out Registry keys, specify the name of the guest (or its disk image) and the name of the Registry key. You must use single quotes to surround the name of the desired key:
# virt-win-reg WindowsGuest \ 'HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Uninstall' \ | less
The output is in the standard text-based format used by .REG files on Windows.

Note

Hex-quoting is used for strings because the format does not properly define a portable encoding method for strings. This is the only way to ensure fidelity when transporting .REG files from one machine to another.
You can make hex-quoted strings printable by piping the output of virt-win-reg through this simple Perl script:
perl -MEncode -pe's?hex\((\d+)\):(\S+)?$t=$1;$_=$2;s,\,,,g;"str($t):\"".decode(utf16le=>pack("H*",$_))."\""?eg'
To merge changes into the Windows Registry of an offline guest, you must first prepare a .REG file. There is a great deal of documentation about doing this available from MSDN, and there is a good summary in the following Wikipedia page: https://secure.wikimedia.org/wikipedia/en/wiki/Windows_Registry#.REG_files. When you have prepared a .REG file, enter the following:
# virt-win-reg --merge WindowsGuest input.reg
This will update the registry in the guest.

16.11. Using the API from Programming Languages

The libguestfs API can be used directly from the following languages in Red Hat Enterprise Linux 6.2: C, C++, Perl, Python, Java, Ruby and OCaml.
  • To install C and C++ bindings, enter the following command:
    # yum install libguestfs-devel
  • To install Perl bindings:
    # yum install 'perl(Sys::Guestfs)'
  • To install Python bindings:
    # yum install python-libguestfs
  • To install Java bindings:
    # yum install libguestfs-java libguestfs-java-devel libguestfs-javadoc
  • To install Ruby bindings:
    # yum install ruby-libguestfs
  • To install OCaml bindings:
    # yum install ocaml-libguestfs ocaml-libguestfs-devel
The binding for each language is essentially the same, but with minor syntactic changes. A C statement:
guestfs_launch (g);
Would appear like the following in Perl:
$g->launch ()
Or like the following in OCaml:
g#launch ()
Only the API from C is detailed in this section.
In the C and C++ bindings, you must manually check for errors. In the other bindings, errors are converted into exceptions; the additional error checks shown in the examples below are not necessary for other languages, but conversely you may wish to add code to catch exceptions. Refer to the following list for some points of interest regarding the architecture of the libguestfs API:
  • The libguestfs API is synchronous. Each call blocks until it has completed. If you want to make calls asynchronously, you have to create a thread.
  • The libguestfs API is not thread safe: each handle should be used only from a single thread, or if you want to share a handle between threads you should implement your own mutex to ensure that two threads cannot execute commands on one handle at the same time.
  • You should not open multiple handles on the same disk image. It is permissible if all the handles are read-only, but still not recommended.
  • You should not add a disk image for writing if anything else could be using that disk image (eg. a live VM). Doing this will cause disk corruption.
  • Opening a read-only handle on a disk image which is currently in use (eg. by a live VM) is possible; however, the results may be unpredictable or inconsistent particularly if the disk image is being heavily written to at the time you are reading it.

16.11.1. Interaction with the API via a C program

Your C program should start by including the <guestfs.h> header file, and creating a handle:
#include <stdio.h>#include <stdlib.h>#include <guestfs.h>intmain (int argc, char *argv[]){  guestfs_h *g;  g = guestfs_create ();  if (g == NULL) { perror ("failed to create libguestfs handle"); exit (EXIT_FAILURE);   }   /* ... */   guestfs_close (g);   exit (EXIT_SUCCESS); }
Save this program to a file (test.c). Compile this program and run it with the following two commands:
gcc -Wall test.c -o test -lguestfs./test
At this stage it should print no output. The rest of this section demonstrates an example showing how to extend this program to create a new disk image, partition it, format it with an ext4 file system, and create some files in the file system. The disk image will be called disk.img and be created in the current directory.
The outline of the program is:
  • Create the handle.
  • Add disk(s) to the handle.
  • Launch the libguestfs back end.
  • Create the partition, file system and files.
  • Close the handle and exit.
Here is the modified program:
#include <stdio.h>#include <stdlib.h>#include <string.h>#include <fcntl.h>#include <unistd.h>#include <guestfs.h>  int main (int argc, char *argv[]) {   guestfs_h *g;   size_t i; g = guestfs_create ();   if (g == NULL) { perror ("failed to create libguestfs handle"); exit (EXIT_FAILURE);  } /* Create a raw-format sparse disk image, 512 MB in size. */   int fd = open ("disk.img", O_CREAT|O_WRONLY|O_TRUNC|O_NOCTTY, 0666);   if (fd == -1) { perror ("disk.img"); exit (EXIT_FAILURE);   }   if (ftruncate (fd, 512 * 1024 * 1024) == -1) { perror ("disk.img: truncate"); exit (EXIT_FAILURE);   }   if (close (fd) == -1) { perror ("disk.img: close"); exit (EXIT_FAILURE);   } /* Set the trace flag so that we can see each libguestfs call. */   guestfs_set_trace (g, 1); /* Set the autosync flag so that the disk will be synchronized * automatically when the libguestfs handle is closed. */   guestfs_set_autosync (g, 1); /* Add the disk image to libguestfs. */   if (guestfs_add_drive_opts (g, "disk.img", GUESTFS_ADD_DRIVE_OPTS_FORMAT, "raw", /* raw format */ GUESTFS_ADD_DRIVE_OPTS_READONLY, 0,   /* for write */ -1 /* this marks end of optional arguments */ )   == -1) exit (EXIT_FAILURE); /* Run the libguestfs back-end. */   if (guestfs_launch (g) == -1) exit (EXIT_FAILURE); /* Get the list of devices.  Because we only added one drive * above, we expect that this list should contain a single * element. */   char **devices = guestfs_list_devices (g);   if (devices == NULL) exit (EXIT_FAILURE);   if (devices[0] == NULL || devices[1] != NULL) { fprintf (stderr,  "error: expected a single device from list-devices\n"); exit (EXIT_FAILURE);   } /* Partition the disk as one single MBR partition. */   if (guestfs_part_disk (g, devices[0], "mbr") == -1) exit (EXIT_FAILURE); /* Get the list of partitions.  We expect a single element, which * is the partition we have just created. */   char **partitions = guestfs_list_partitions (g);   if (partitions == NULL) exit (EXIT_FAILURE);   if (partitions[0] == NULL || partitions[1] != NULL) { fprintf (stderr,  "error: expected a single partition from list-partitions\n"); exit (EXIT_FAILURE);   } /* Create an ext4 filesystem on the partition. */   if (guestfs_mkfs (g, "ext4", partitions[0]) == -1) exit (EXIT_FAILURE); /* Now mount the filesystem so that we can add files. */   if (guestfs_mount_options (g, "", partitions[0], "/") == -1) exit (EXIT_FAILURE); /* Create some files and directories. */   if (guestfs_touch (g, "/empty") == -1) exit (EXIT_FAILURE); const char *message = "Hello, world\n";   if (guestfs_write (g, "/hello", message, strlen (message)) == -1) exit (EXIT_FAILURE); if (guestfs_mkdir (g, "/foo") == -1) exit (EXIT_FAILURE); /* This uploads the local file /etc/resolv.conf into the disk image. */   if (guestfs_upload (g, "/etc/resolv.conf", "/foo/resolv.conf") == -1) exit (EXIT_FAILURE); /* Because 'autosync' was set (above) we can just close the handle * and the disk contents will be synchronized.  You can also do * this manually by calling guestfs_umount_all and guestfs_sync. */   guestfs_close (g); /* Free up the lists. */   for (i = 0; devices[i] != NULL; ++i) free (devices[i]);   free (devices);   for (i = 0; partitions[i] != NULL; ++i) free (partitions[i]);   free (partitions); exit (EXIT_SUCCESS); }
Compile and run this program with the following two commands:
gcc -Wall test.c -o test -lguestfs./test
If the program runs to completion successfully then you should be left with a disk image called disk.img, which you can examine with guestfish:
guestfish --ro -a disk.img -m /dev/sda1><fs> ll /><fs> cat /foo/resolv.conf
By default (for C and C++ bindings only), libguestfs prints errors to stderr. You can change this behavior by setting an error handler. The guestfs(3) man page discusses this in detail.

16.12. Troubleshooting

A test tool is available to check that libguestfs is working. Run the following command after installing libguestfs (root access not required) to test for normal operation:
$ libguestfs-test-tool
This tool prints a large amount of text to test the operation of libguestfs. If the test is successful, the following text will appear near the end of the output:
===== TEST FINISHED OK =====

16.13. Where to find further documentation

The primary source for documentation for libguestfs and the tools are the Unix man pages. The API is documented in guestfs(3). guestfish is documented in guestfish(1). The virt tools are documented in their own man pages (eg. virt-df(1)).
(Sebelumnya) 24 : Chapter 14. Managing gues ...24 : Chapter 17. Virtual Networking (Berikutnya)