1 // Example showing how to inspect a virtual machine disk.
3 import java.util.ArrayList;
4 import java.util.Collections;
5 import java.util.Comparator;
6 import java.util.HashMap;
9 import com.redhat.et.libguestfs.*;
11 public class InspectVM
13 static final Comparator<String> COMPARE_KEYS_LEN =
14 new Comparator<String>() {
15 public int compare (String k1, String k2) {
16 return k1.length() - k2.length();
20 public static void main (String[] argv)
24 throw new Error ("usage: InspectVM disk.img");
26 String disk = argv[0];
28 GuestFS g = new GuestFS ();
30 // Attach the disk image read-only to libguestfs.
31 Map<String, Object> optargs = new HashMap<String, Object>() {
33 //put ("format", "raw");
34 put ("readonly", Boolean.TRUE);
38 g.add_drive_opts (disk, optargs);
40 // Run the libguestfs back-end.
43 // Ask libguestfs to inspect for operating systems.
44 String roots[] = g.inspect_os ();
45 if (roots.length == 0)
46 throw new Error ("inspect_vm: no operating systems found");
48 for (String root : roots) {
49 System.out.println ("Root device: " + root);
51 // Print basic information about the operating system.
52 System.out.println (" Product name: " +
53 g.inspect_get_product_name (root));
54 System.out.println (" Version: " +
55 g.inspect_get_major_version (root) +
57 g.inspect_get_minor_version (root));
58 System.out.println (" Type: " +
59 g.inspect_get_type (root));
60 System.out.println (" Distro: " +
61 g.inspect_get_distro (root));
63 // Mount up the disks, like guestfish -i.
65 // Sort keys by length, shortest first, so that we end up
66 // mounting the filesystems in the correct order.
67 Map<String,String> mps = g.inspect_get_mountpoints (root);
68 List<String> mps_keys = new ArrayList (mps.keySet ());
69 Collections.sort (mps_keys, COMPARE_KEYS_LEN);
71 for (String mp : mps_keys) {
72 String dev = mps.get (mp);
76 catch (Exception exn) {
77 System.err.println (exn + " (ignored)");
81 // If /etc/issue.net file exists, print up to 3 lines.
82 String filename = "/etc/issue.net";
83 if (g.is_file (filename)) {
84 System.out.println ("--- " + filename + " ---");
85 String[] lines = g.head_n (3, filename);
86 for (String line : lines)
87 System.out.println (line);
90 // Unmount everything.
94 catch (Exception exn) {
95 System.err.println (exn);