Sys::Guestfs(3pm)

๐Ÿ’– Sys::Guestfs ๐Ÿ’–

okay bestie, this is the Sys::Guestfs(3pm) page from User Contributed Perl Documentation, and it's literally all about the Perl bindings for libguestfs. buckle up, we're going in ๐Ÿ’…

๐ŸŒธ NAME ๐ŸŒธ

Sys::Guestfs โ€” Perl bindings for libguestfs. no cap, that's the whole name section ๐Ÿซถ

โœจ SYNOPSIS โœจ

use Sys::Guestfs;

my $g = Sys::Guestfs->new ();
$g->add_drive_opts ('guest.img', format => 'raw');
$g->launch ();
$g->mount ('/dev/sda1', '/');
$g->touch ('/hello');
$g->shutdown ();
$g->close ();

๐Ÿฆ‹ DESCRIPTION ๐Ÿฆ‹

The Sys::Guestfs module provides a Perl XS binding to the libguestfs API for examining and modifying virtual machine disk images. it's giving "look inside a VM disk image and also change stuff" energy ๐Ÿ’–

Amongst the things this is good for:

  • making batch configuration changes to guests
  • getting disk used/free statistics (see also: virt-df)
  • migrating between virtualization systems (see also: virt-p2v)
  • performing partial backups
  • performing partial guest clones
  • cloning guests and changing registry/UUID/hostname info
  • and much else besides.

Libguestfs uses Linux kernel and qemu code, and can access any type of guest filesystem that Linux and qemu can, including but not limited to: ext2/3/4, btrfs, FAT and NTFS, LVM, many different disk partition schemes, qcow, qcow2, vmdk. obsessed with the range honestly ๐ŸŒˆ

Libguestfs provides ways to enumerate guest storage (eg. partitions, LVs, what filesystem is in each LV, etc.). It can also run commands in the context of the guest. Also you can access filesystems over FUSE. iconic behavior โœจ

๐Ÿ˜ญ ERRORS ๐Ÿ˜ญ

All errors turn into calls to croak (see Carp(3)).

The error string from libguestfs is directly available from $@. Use the last_errno method if you want to get the errno. that's your little diagnostic bestie ๐ŸŽ€

๐Ÿ’… METHODS ๐Ÿ’…

๐Ÿ’– $g = Sys::Guestfs->new ([environment => 0,] [close_on_exit => 0]); ๐Ÿ’–

Create a new guestfs handle.

  • If the optional argument environment is false, then the GUESTFS_CREATE_NO_ENVIRONMENT flag is set.
  • If the optional argument close_on_exit is false, then the GUESTFS_CREATE_NO_CLOSE_ON_EXIT flag is set.

๐ŸŽ€ $g->close (); ๐ŸŽ€

Explicitly close the guestfs handle.

Note: You should not usually call this function. The handle will be closed implicitly when its reference count goes to zero (eg. when it goes out of scope or the program ends). This call is only required in some exceptional cases, such as where the program may contain cached references to the handle 'somewhere' and you really have to have the close happen right away. After calling close the program must not call any method (including close) on the handle (but the implicit call to DESTROY that happens when the final reference is cleaned up is OK). bestie, do not touch it after close, that's the vibe check ๐Ÿ’€

๐Ÿฆ‹ event constants ๐Ÿฆ‹

  • $Sys::Guestfs::EVENT_CLOSE โ€” See GUESTFS_EVENT_CLOSE in guestfs(3).
  • $Sys::Guestfs::EVENT_SUBPROCESS_QUIT โ€” See GUESTFS_EVENT_SUBPROCESS_QUIT in guestfs(3).
  • $Sys::Guestfs::EVENT_LAUNCH_DONE โ€” See GUESTFS_EVENT_LAUNCH_DONE in guestfs(3).
  • $Sys::Guestfs::EVENT_PROGRESS โ€” See GUESTFS_EVENT_PROGRESS in guestfs(3).
  • $Sys::Guestfs::EVENT_APPLIANCE โ€” See GUESTFS_EVENT_APPLIANCE in guestfs(3).
  • $Sys::Guestfs::EVENT_LIBRARY โ€” See GUESTFS_EVENT_LIBRARY in guestfs(3).
  • $Sys::Guestfs::EVENT_TRACE โ€” See GUESTFS_EVENT_TRACE in guestfs(3).
  • $Sys::Guestfs::EVENT_ENTER โ€” See GUESTFS_EVENT_ENTER in guestfs(3).
  • $Sys::Guestfs::EVENT_LIBVIRT_AUTH โ€” See GUESTFS_EVENT_LIBVIRT_AUTH in guestfs(3).
  • $Sys::Guestfs::EVENT_WARNING โ€” See GUESTFS_EVENT_WARNING in guestfs(3).
  • $Sys::Guestfs::EVENT_ALL โ€” See GUESTFS_EVENT_ALL in guestfs(3).

๐Ÿ’œ $event_handle = $g->set_event_callback (\&cb, $event_bitmask); ๐Ÿ’œ

Register cb as a callback function for all of the events in $event_bitmask (one or more $Sys::Guestfs::EVENT_* flags logically or'd together).

This function returns an event handle which can be used to delete the callback using delete_event_callback.

The callback function receives 4 parameters:

&cb ($event, $event_handle, $buf, $array)
  • $event โ€” The event which happened (equal to one of $Sys::Guestfs::EVENT_*).
  • $event_handle โ€” The event handle.
  • $buf โ€” For some event types, this is a message buffer (ie. a string).
  • $array โ€” For some event types (notably progress events), this is an array of integers.

You should carefully read the documentation for guestfs_set_event_callback in guestfs(3) before using this function. seriously, bestie, read the docs first ๐Ÿซถ

๐ŸŒธ $g->delete_event_callback ($event_handle); ๐ŸŒธ

This removes the callback which was previously registered using set_event_callback.

โญ $str = Sys::Guestfs::event_to_string ($events); โญ

$events is either a single event or a bitmask of events. This returns a printable string, useful for debugging.

Note that this is a class function, not a method. iykyk ๐Ÿ’…

๐Ÿ“ $errnum = $g->last_errno (); ๐Ÿ“

This returns the last error number (errno) that happened on the handle $g.

If successful, an errno integer not equal to zero is returned.

If no error number is available, this returns 0. See guestfs_last_errno in guestfs(3) for more details of why this can happen.

You can use the standard Perl module Errno(3) to compare the numeric error returned from this call with symbolic errnos:

$g->mkdir ("/foo");
if ($g->last_errno() == Errno::EEXIST()) {
  # mkdir failed because the directory exists already.
}

๐Ÿงš $g->acl_delete_def_file ($dir); ๐Ÿงš

This function deletes the default POSIX Access Control List (ACL) attached to directory dir.

This function depends on the feature acl. See also: $g->feature-available.

๐ŸŽ€ $acl = $g->acl_get_file ($path, $acltype); ๐ŸŽ€

This function returns the POSIX Access Control List (ACL) attached to path. The ACL is returned in "long text form" (see acl(5)).

The acltype parameter may be:

  • "access" โ€” Return the ordinary (access) ACL for any file, directory or other filesystem object.
  • "default" โ€” Return the default ACL. Normally this only makes sense if path is a directory.

This function depends on the feature acl. See also: $g->feature-available.

๐Ÿ’– $g->acl_set_file ($path, $acltype, $acl); ๐Ÿ’–

This function sets the POSIX Access Control List (ACL) attached to path.

The acltype parameter may be:

  • "access" โ€” Set the ordinary (access) ACL for any file, directory or other filesystem object.
  • "default" โ€” Set the default ACL. Normally this only makes sense if path is a directory.

The acl parameter is the new ACL in either "long text form" or "short text form" (see acl(5)). The new ACL completely replaces any previous ACL on the file. The ACL must contain the full Unix permissions (eg. u::rwx,g::rx,o::rx).

If you are specifying individual users or groups, then the mask field is also required (eg. m::rwx), followed by the u:ID:... and/or g:ID:... field(s). A full ACL string might therefore look like this:

u::rwx,g::rwx,o::rwx,m::rwx,u:500:rwx,g:500:rwx
\ Unix permissions / \mask/ \      ACL        /

You should use numeric UIDs and GIDs. To map usernames and groupnames to the correct numeric ID in the context of the guest, use the Augeas functions (see $g->aug_init).

This function depends on the feature acl. See also: $g->feature-available.

๐Ÿ’€ $g->add_cdrom ($filename); ๐Ÿ’€

This function adds a virtual CD-ROM disk image to the guest.

The image is added as read-only drive, so this function is equivalent of $g->add_drive_ro.

This function is deprecated. In new code, use the add_drive_ro call instead.

Deprecated functions will not be removed from the API, but the fact that they are deprecated indicates that there are problems with correct use of these functions. not me using deprecated calls in 2025 ๐Ÿ™ˆ

๐Ÿ‘‘ $g->add_domain ๐Ÿ‘‘

$nrdisks = $g->add_domain ($dom [, libvirturi => $libvirturi] [, readonly => $readonly] [, iface => $iface] [, live => $live] [, allowuuid => $allowuuid] [, readonlydisk => $readonlydisk] [, cachemode => $cachemode] [, discard => $discard] [, copyonread => $copyonread]);

This function adds the disk(s) attached to the named libvirt domain dom. It works by connecting to libvirt, requesting the domain and domain XML from libvirt, parsing it for disks, and calling $g->add_drive_opts on each one.

The number of disks added is returned. This operation is atomic: if an error is returned, then no disks are added.

This function does some minimal checks to make sure the libvirt domain is not running (unless readonly is true). In a future version we will try to acquire the libvirt lock on each disk.

Disks must be accessible locally. This often means that adding disks from a remote libvirt connection (see <https://libvirt.org/remote.html>) will fail unless those disks are accessible via the same device path locally too.

The optional libvirturi parameter sets the libvirt URI (see <https://libvirt.org/uri.html>). If this is not set then we connect to the default libvirt URI (or one set through an environment variable, see the libvirt documentation for full details).

The optional live flag is ignored in libguestfs โ‰ฅ 1.48.

If the allowuuid flag is true (default is false) then a UUID may be passed instead of the domain name. The dom string is treated as a UUID first and looked up, and if that lookup fails then we treat dom as a name as usual.

The optional readonlydisk parameter controls what we do for disks which are marked <readonly/> in the libvirt XML. Possible values are:

  • readonlydisk = "error" โ€”
    • If readonly is false:
      • The whole call is aborted with an error if any disk with the <readonly/> flag is found.
    • If readonly is true:
      • Disks with the <readonly/> flag are added read-only.
  • readonlydisk = "read" โ€”
    • If readonly is false:
      • Disks with the <readonly/> flag are added read-only. Other disks are added read/write.
    • If readonly is true:
      • Disks with the <readonly/> flag are added read-only.
  • readonlydisk = "write" (default) โ€”
    • If readonly is false:
      • Disks with the <readonly/> flag are added read/write.
    • If readonly is true:
      • Disks with the <readonly/> flag are added read-only.
  • readonlydisk = "ignore" โ€”
    • If readonly is true or false:
      • Disks with the <readonly/> flag are skipped.

If present, the value of logical_block_size attribute of <blockio/> tag in libvirt XML will be passed as blocksize parameter to $g->add_drive_opts.

โ€ฆthe other optional params just get passed straight on through to $g->add_drive_opts, no extra processing, no drama. โœจ


$g->add_drive ($filename [, readonly => $readonly] [, format => $format] [, iface => $iface] [, name => $name] [, label => $label] [, protocol => $protocol] [, server => $server] [, username => $username] [, secret => $secret] [, cachemode => $cachemode] [, discard => $discard] [, copyonread => $copyonread] [, blocksize => $blocksize]);

$g->add_drive ($filename [, readonly => $readonly] [, format => $format]
[, iface => $iface] [, name => $name] [, label => $label] [, protocol =>
$protocol] [, server => $server] [, username => $username] [, secret =>
$secret] [, cachemode => $cachemode] [, discard => $discard] [,
copyonread => $copyonread] [, blocksize => $blocksize]);

Okay so this one is the moment a disk image called filename gets yeeted into the handle. ๐Ÿ’… And bestie, filename can legitimately be a regular host file or a host device โ€” both are valid, no gatekeeping.

When you call this before $g->launch (which ngl is the usual case, like 99% of the time), the first call makes the disk show up in the API as /dev/sda, the second time as /dev/sdb, and it just keeps going from there. main character disk allocation energy. ๐Ÿ‘‘

Do you have to be root? Not necessarily โ€” libguestfs is chill like that. But you obviously do need sufficient permissions to actually access filename for whatever you're trying to do (i.e. read access if you just want to read the image, write access if you want to modify the image). basic manners. ๐Ÿ™ˆ

This call checks that filename exists. no imaginary disks allowed.

Fun fact: filename may be the special string /dev/null. See "NULL DISKS" in guestfs(3). iconic behaviour honestly.

The optional arguments are:

  • "readonly" โ€” if true then the image is treated as read-only. Writes are still allowed, bestie, but they get stored in a temporary snapshot overlay which is discarded at the end. So the disk that you add is not modified. it's giving "what happens in the overlay stays in the overlay". ๐Ÿ’ซ
  • "format" โ€” this forces the image format. If you omit this (or use $g->add_drive or $g->add_drive_ro) then the format is automatically detected. Possible formats include "raw" and "qcow2".
๐Ÿšจ Real talk, technical caveat time: automatic detection of the format opens you up to a potential security hole when dealing with untrusted raw-format images. See CVE-2010-3851 and RHBZ#642934. Specifying the format closes this security hole. So likeโ€ฆ specify it. please. ๐Ÿ™
  • "iface" โ€” this rarely-used option lets you emulate the behaviour of the deprecated $g->add_drive_with_if call (q.v.). lowkey legacy vibes but it's here.
  • "name" โ€” this field used to be passed as a hint for guest inspection, but it is no longer used. rip to a real one, it's just decorative now. ๐Ÿ’€
  • "label" โ€” give the disk a label. The label should be a unique, short string using only ASCII characters [a-zA-Z]. As well as its usual name in the API (such as /dev/sda), the drive will also be named /dev/disk/guestfs/label.

See "DISK LABELS" in guestfs(3). cute nickname for your disk, we love to see it ๐ŸŽ€

  • "protocol" โ€” the optional protocol argument can be used to select an alternate source protocol. See also: "REMOTE STORAGE" in guestfs(3).
    • protocol = "file" โ€” filename is interpreted as a local file or device. This is the default if the optional protocol parameter is omitted. cozy, local, no networking required.
    • protocol = "nbd" โ€” connect to the Network Block Device server. The "server" parameter must also be supplied โ€” see below. See also: "NETWORK BLOCK DEVICE" in guestfs(3). ๐ŸŒ
    • protocol = "rbd" โ€” connect to the Ceph (librbd/RBD) server. The "server" parameter must also be supplied โ€” see below. The "username" parameter may be supplied. See below. The "secret" parameter may be supplied. See below. See also: "CEPH" in guestfs(3). fancy distributed storage moment โœจ
  • "server" โ€” for protocols which require access to a remote server, this is a list of server(s).
 Protocol       Number of servers required
 --------       --------------------------
 file           List must be empty or param not used at all
 nbd            Exactly one
 rbd            Zero or more

Each list element is a string specifying a server. The string must be in one of the following formats:

 hostname
 hostname:port
 tcp:hostname
 tcp:hostname:port
 unix:/path/to/socket

If the port number is omitted, then the standard port number for the protocol is used (see /etc/services). iykyk ๐Ÿงš

  • "username" โ€” for the "rbd" protocol, this specifies the remote username.

If not given, then no authentication is attempted for ceph. But note this sometimes may give unexpected results, for example if using the libvirt backend and if the libvirt backend is configured to start the qemu appliance as a special user such as "qemu.qemu". If in doubt, specify the remote username you want. ngl just specify it. ๐Ÿ™ˆ

  • "secret" โ€” for the "rbd" protocol only, this specifies the โ€˜secretโ€™ to use when connecting to the remote device. It must be base64 encoded.

If not given, then a secret matching the given username will be looked up in the default keychain locations, or if no username is given, then no authentication will be used. ๐Ÿ”

  • "cachemode" โ€” choose whether or not libguestfs will obey sync operations (safe but slow) or not (unsafe but fast). The possible values for this string are:
    • cachemode = "writeback" โ€” this is the default.

Write operations in the API do not return until a write(2) call has completed in the host [but note this does not imply that anything gets written to disk]. ๐Ÿ˜ญ

Sync operations in the API, including implicit syncs caused by filesystem journalling, will not return until an fdatasync(2) call has completed in the host, indicating that data has been committed to disk.

  • cachemode = "unsafe" โ€” in this mode, there are no guarantees. Libguestfs may cache anything and ignore sync requests. This is suitable only for scratch or temporary disks. literally do not put your precious data here bestie ๐Ÿ’€
  • "discard" โ€” enable or disable discard (a.k.a. trim or unmap) support on this drive. If enabled, operations such as $g->fstrim will be able to discard / make thin / punch holes in the underlying host file or device. ๐Ÿ•ณ๏ธโœจ

Possible discard settings are:

  • discard = "disable" โ€” disable discard support. This is the default.
  • discard = "enable" โ€” enable discard support. Fail if discard is not possible. all or nothing, periodt.
  • discard = "besteffort" โ€” enable discard support if possible, but don't fail if it is not supported.

Since not all backends and not all underlying systems support discard, this is a good choice if you want to use discard if possible, but don't mind if it doesn't work. the "no pressure" option ๐Ÿซถ

  • "copyonread" โ€” the boolean parameter "copyonread" enables copy-on-read support. This only affects disk formats which have backing files, and causes reads to be stored in the overlay layer, speeding up multiple reads of the same area of disk.

The default is false. ๐Ÿ˜ด

  • "blocksize" โ€” this parameter sets the sector size of the disk. Possible values are 512 (the default if the parameter is omitted) or 4096. Use 4096 when handling an "Advanced Format" disk that uses 4K sector size (https://en.wikipedia.org/wiki/Advanced_Format).
โš ๏ธ Heads up: only a subset of the backends support this parameter (currently only the libvirt and direct backends do). so like, vibe check your backend first.

$g->add_drive_opts ($filename [, readonly => $readonly] [, format => $format] [, iface => $iface] [, name => $name] [, label => $label] [, protocol => $protocol] [, server => $server] [, username => $username] [, secret => $secret] [, cachemode => $cachemode] [, discard => $discard] [, copyonread => $copyonread] [, blocksize => $blocksize]);

$g->add_drive_opts ($filename [, readonly => $readonly] [, format =>
$format] [, iface => $iface] [, name => $name] [, label => $label] [,
protocol => $protocol] [, server => $server] [, username => $username]
[, secret => $secret] [, cachemode => $cachemode] [, discard =>
$discard] [, copyonread => $copyonread] [, blocksize => $blocksize]);

This is an alias of "add_drive". same girl, different name tag. ๐Ÿ’–


$g->add_drive_ro ($filename);

$g->add_drive_ro ($filename);

This function is the equivalent of calling $g->add_drive_opts with the optional parameter GUESTFS_ADD_DRIVE_OPTS_READONLY set to 1, so the disk is added read-only, with the format being detected automatically. look at nothing, touch nothing, corrupt nothing. ๐Ÿ™…โ€โ™€๏ธ


$g->add_drive_ro_with_if ($filename, $iface);

$g->add_drive_ro_with_if ($filename, $iface);

This is the same as $g->add_drive_ro but it allows you to specify the QEMU interface emulation to use at run time. Both the direct and the libvirt backends ignore "iface".

๐Ÿšฉ This function is deprecated. In new code, use the "add_drive" call instead.
Deprecated functions will not be removed from the API, but the fact that they are deprecated indicates that there are problems with correct use of these functions. so likeโ€ฆ it's not going away, it's just not the move. ๐Ÿ’€

$g->add_drive_scratch ($size [, name => $name] [, label => $label] [, blocksize => $blocksize]);

$g->add_drive_scratch ($size [, name => $name] [, label => $label] [,
blocksize => $blocksize]);

This command adds a temporary scratch drive to the handle. The "size" parameter is the virtual size (in bytes). The scratch drive is blank initially (all reads return zeroes until you start writing to it). The drive is deleted when the handle is closed. ๐Ÿ—‘๏ธโœจ it's giving disposable camera energy, honestly iconic

The optional arguments "name", "label" and "blocksize" are passed through to $g->add_drive_opts.


$g->add_drive_with_if ($filename, $iface);

$g->add_drive_with_if ($filename, $iface);

This is the same as $g->add_drive but it allows you to specify the QEMU interface emulation to use at run time. Both the direct and the libvirt backends ignore "iface".

๐Ÿšฉ This function is deprecated. In new code, use the "add_drive" call instead.
Deprecated functions will not be removed from the API, but the fact that they are deprecated indicates that there are problems with correct use of these functions. same speech, same energy. ๐Ÿ’…

$g->add_libvirt_dom ($dom [, readonly => $readonly] [, iface => $iface] [, live => $live] [, readonlydisk => $readonlydisk] [, cachemode => $cachemode] [, discard => $discard] [, copyonread => $copyonread]);

$nrdisks = $g->add_libvirt_dom ($dom [, readonly => $readonly] [, iface
=> $iface] [, live => $live] [, readonlydisk => $readonlydisk] [,
cachemode => $cachemode] [, discard => $discard] [, copyonread =>
$copyonread]);

This function adds the disk(s) attached to the libvirt domain "dom". It works by requesting the domain XML from libvirt, parsing it for disks, and calling $g->add_drive_opts on each one. so it's basically doing the homework for you, one disk at a time ๐Ÿ“šโœจ

In the C API we declare void *dom, but really it has type virDomainPtr dom. This is so we don't need <libvirt.h>. sneaky but valid. ๐Ÿ˜Œ

The number of disks added is returned. This operation is atomic: if an error is returned, then no disks are added. all or nothing, we love a clean rollback ๐Ÿซถ

This function does some minimal checks to make sure the libvirt domain is not running (unless "readonly" is true). In a future version we will try to acquire the libvirt lock on each disk. ๐Ÿ”’


Disks must be accessible locally, bestie ๐Ÿ’… โ€” like, actually locally. This often means that adding disks from a remote libvirt connection (see <https://libvirt.org/remote.html>) will fail unless those disks are accessible via the same device path locally too. No cap, itโ€™s giving โ€œwhy is my disk not showing upโ€ energy ๐Ÿ˜ญ.

The optional live flag is ignored in libguestfs โ‰ฅ 1.48. Lowkey important, so donโ€™t come for me if it does nothing.

The optional readonlydisk parameter controls what we do for disks which are marked <readonly/> in the libvirt XML. See $g->add_domain for possible values.

If present, the value of logical_block_size attribute of <blockio/> tag in libvirt XML will be passed as blocksize parameter to $g->add_drive_opts.

The other optional parameters are passed directly through to $g->add_drive_opts.


๐ŸŽ€ $g->aug_clear ($augpath);

Set the value associated with path to NULL. This is the same as the augtool(1) clear command. Slay, one less node value to worry about โœจ.

๐Ÿฆ‹ $g->aug_close ();

Close the current Augeas handle and free up any resources used by it. After calling this, you have to call $g->aug_init again before you can use any other Augeas functions. So yeah, itโ€™s a real โ€œbye bestie, see you at initโ€ moment ๐Ÿ‘‹.

๐ŸŒธ %nrnodescreated = $g->aug_defnode ($name, $expr, $val);

Defines a variable name whose value is the result of evaluating expr.

If expr evaluates to an empty nodeset, a node is created, equivalent to calling $g->aug_set expr, val. name will be the nodeset containing that single node.

On success this returns a pair containing the number of nodes in the nodeset, and a boolean flag if a node was created. Cute little pair, iykyk ๐Ÿ’–.

๐Ÿงš $nrnodes = $g->aug_defvar ($name, $expr);

Defines an Augeas variable name whose value is the result of evaluating expr. If expr is NULL, then name is undefined.

On success this returns the number of nodes in expr, or 0 if expr evaluates to something which is not a nodeset.

๐Ÿ“ $val = $g->aug_get ($augpath);

Look up the value associated with path. If path matches exactly one node, the value is returned. One node only, bestie โ€” not a group chat, a one-on-one ๐Ÿ’….

๐Ÿ‘‘ $g->aug_init ($root, $flags);

Create a new Augeas handle for editing configuration files. If there was any previous Augeas handle associated with this guestfs session, then it is closed. Itโ€™s giving โ€œnew handle, who disโ€ โœจ.

You must call this before using any other $g->aug_* commands. Literally the main character of Augeas setup, periodt.

root is the filesystem root. root must not be NULL, use / instead. Do not test me on this ๐Ÿ™ˆ.

The flags are the same as the flags defined in <augeas.h>, the logical or of the following integers:

  • AUG_SAVE_BACKUP = 1 โ€” Keep the original file with a .augsave extension.
  • AUG_SAVE_NEWFILE = 2 โ€” Save changes into a file with extension .augnew, and do not overwrite original. Overrides AUG_SAVE_BACKUP.
  • AUG_TYPE_CHECK = 4 โ€” Typecheck lenses. This option is only useful when debugging Augeas lenses. Use of this option may require additional memory for the libguestfs appliance. You may need to set the LIBGUESTFS_MEMSIZE environment variable or call $g->set_memsize.
  • AUG_NO_STDINC = 8 โ€” Do not use standard load path for modules.
  • AUG_SAVE_NOOP = 16 โ€” Make save a no-op, just record what would have been changed.
  • AUG_NO_LOAD = 32 โ€” Do not load the tree in $g->aug_init.

To close the handle, you can call $g->aug_close.

To find out more about Augeas, see <http://augeas.net/>. Obsessed with a good config editing lore drop ๐Ÿซถ.

๐ŸŒˆ $g->aug_insert ($augpath, $label, $before);

Create a new sibling label for path, inserting it into the tree before or after path (depending on the boolean flag before).

path must match exactly one existing node in the tree, and label must be a label, ie. not contain /, * or end with a bracketed index [N]. So no chaotic label names, okay? Keep it clean ๐Ÿงผ.

โญ $label = $g->aug_label ($augpath);

The label (name of the last element) of the Augeas path expression augpath is returned. augpath must match exactly one node, else this function returns an error. One node or itโ€™s a no from me ๐Ÿ’€.

๐Ÿ’œ $g->aug_load ();

Load files into the tree.

See aug_load in the Augeas documentation for the full gory details. Gory details, literally โ€” go read the lore if you need it ๐Ÿ“š.

๐Ÿฆ‹ @matches = $g->aug_ls ($augpath);

This is just a shortcut for listing $g->aug_match path/* and sorting the resulting nodes into alphabetical order. Lowkey a little organizational queen move โœจ.

๐ŸŽ€ @matches = $g->aug_match ($augpath);

Returns a list of paths which match the path expression path. The returned paths are sufficiently qualified so that they match exactly one node in the current tree. No ambiguous matches, we donโ€™t do that here ๐Ÿ’….

๐ŸŒธ $g->aug_mv ($src, $dest);

Move the node src to dest. src must match exactly one node. dest is overwritten if it exists. So yeah, dest is not safe from the overwrite โ€” fair warning, bestie โš ๏ธ.

๐Ÿ“ $nrnodes = $g->aug_rm ($augpath);

Remove path and all of its children.

On success this returns the number of entries which were removed. Itโ€™s giving โ€œdelete the whole group chatโ€ energy ๐Ÿ˜ญ.

๐Ÿงš $g->aug_save ();

This writes all pending changes to disk.

The flags which were passed to $g->aug_init affect exactly how files are saved. So those flags are not just decorative, theyโ€™re running the save vibe check โœ….

๐Ÿ’– $g->aug_set ($augpath, $val);

Set the value associated with augpath to val.

In the Augeas API, it is possible to clear a node by setting the value to NULL. Due to an oversight in the libguestfs API you cannot do that with this call. Instead you must use the $g->aug_clear call. Not me exposing the API oversight, but here we are ๐Ÿ™ˆ.

๐Ÿ”ฅ $nodes = $g->aug_setm ($base, $sub, $val);

Change multiple Augeas nodes in a single operation. base is an expression matching multiple nodes. sub is a path expression relative to base. All nodes matching base are found, and then for each node, sub is changed to val. sub may also be NULL in which case the base nodes are modified.

This returns the number of nodes modified. Multi-node glow-up, periodt โœจ.

๐Ÿซถ $g->aug_transform ($lens, $file [, remove => $remove]);

Add an Augeas transformation for the specified lens so it can handle file.

If remove is true (false by default), then the transformation is removed. Default is false, bestie โ€” donโ€™t forget ๐ŸŽ€.

๐ŸŒŸ $g->available (\@groups);

This command is used to check the availability of some groups of functionality in the appliance, which not all builds of the libguestfs appliance will be able to provide. Itโ€™s giving โ€œis this feature even in the building?โ€ energy ๐Ÿ‘€.

The libguestfs groups, and the functions that those groups correspond to, are listed in AVAILABILITY in guestfs(3). You can also fetch this list at runtime by calling $g->available_all_groups.

The argument groups is a list of group names, eg: ["inotify", "augeas"] would check for the availability of the Linux inotify functions and Augeas (configuration file editing) functions.

The command returns no error if all requested groups are available.

It fails with an error if one or more of the requested groups is unavailable in the appliance.

If an unknown group name is included in the list of groups then an error is always returned. So donโ€™t invent group names, okay? ๐Ÿ’€

Notes:

  • $g->feature_available is the same as this call, but with a slightly simpler to use API: that call returns a boolean true/false instead of throwing an error.
  • You must call $g->launch before calling this function. The reason is because we donโ€™t know what groups are supported by the appliance/daemon until it is running and can be queried.
  • If a group of functions is available, this does not necessarily mean that they will work. You still have to check for errors when calling individual API functions even if they are available.
  • It is usually the job of distro packagers to build complete functionality into the libguestfs appliance. Upstream libguestfs, if built from source with all requirements satisfied, will support everything.
  • This call was added in version 1.0.80. In previous versions of libguestfs all you could do would be to speculatively execute a command to find out if the daemon implemented it. See also $g->version.

See also $g->filesystem_available.

๐ŸŒˆ @groups = $g->available_all_groups ();

This command returns a list of all optional groups that this daemon knows about. Note this returns both supported and unsupported groups. To find out which ones the daemon can actually support you have to call $g->available / $g->feature_available on each member of the returned list. So itโ€™s a list, not a promise โ€” do your own vibe check ๐Ÿ’….

See also $g->available, $g->feature_available and AVAILABILITY in guestfs(3).

๐ŸŽ€ $g->base64_in ($base64file, $filename);

This command uploads base64-encoded data from base64file to filename. Base64 in, bestie โœจ.

๐Ÿฆ‹ $g->base64_out ($filename, $base64file);

This command downloads the contents of filename, writing it out to local file base64file encoded as base64. Base64 out, and itโ€™s giving encoded little package ๐ŸŽ.

๐Ÿ’€ $g->blkdiscard ($device);

This discards all blocks on the block device device, giving the free space back to the host.

This operation requires support in libguestfs, the host filesystem, qemu and the host kernel. If this support isnโ€™t present it may give an error or even appear to run but do nothing. You must also set the discard attribute on the underlying drive (see $g->add_drive_opts). So yeah, support is not optional โ€” check it, fr fr โš ๏ธ.

This function depends on the feature blkdiscard. See also $g->feature-available.

๐Ÿ“ $zeroes = $g->blkdiscardzeroes ($device);

This call returns true if blocks on device that have been discarded by a call to $g->blkdiscard are returned as blocks of zero bytes when read the next time.

If it returns false, then it may be that discarded blocks are read as stale or random data. So true means zeroes, false means โ€œcould be anything, good luckโ€ ๐Ÿ˜ญ.

This function depends on the feature blkdiscardzeroes. See also $g->feature-available.

๐Ÿ‘‘ %info = $g->blkid ($device);

This command returns block device attributes for device. The following fields are usually present in the returned hash. Other fields may also be present.

  • UUID โ€” The uuid of this device.
  • LABEL โ€” The label of this device.
  • VERSION โ€” The version of blkid command.
  • TYPE โ€” The filesystem type or RAID of this device.
  • USAGE โ€” The usage of this device, for example filesystem or raid.

Itโ€™s giving device lore in hash form, and we love a good %info moment ๐Ÿ’–.

๐Ÿงš $g->blockdev_flushbufs ($device);

This tells the kernel to flush internal buffers associated with device.

This uses the blockdev(8) command. Flush it, bestie, flush it โœจ.

๐ŸŒธ $blocksize = $g->blockdev_getbsz ($device);

This returns the block size of a device.

Note: this is different from both size in blocks and filesystem block size. Also this setting is not really used by anything. You should probably not use it for anything. Filesystems have their own idea about what block size to choose. So yeah, this one is kinda giving โ€œwhy does this existโ€ but here we are ๐Ÿซ .

โ€ฆand yep, that one's running on the blockdev(8) command too ๐Ÿ’… moving on bestie, the block device lore continues:


$ro = $g->blockdev_getro ($device);

Returns a boolean telling you if the block device is read-only โ€” true if it's read-only, false if it's not. Simple as.

This uses the blockdev(8) command.

$sizeinbytes = $g->blockdev_getsize64 ($device);

Returns the size of the device, in bytes โœจ

See also $g->blockdev_getsz.

This uses the blockdev(8) command.

$sectorsize = $g->blockdev_getss ($device);

Returns the size of the sectors on a block device. Usually it's 512, but modern devices can be bigger, no cap.

(Quick heads up: this is not the size in sectors โ€” if that's what you want, use $g->blockdev_getsz instead ๐Ÿ”ฅ)

This uses the blockdev(8) command.

$sizeinsectors = $g->blockdev_getsz ($device);

Returns the size of the device measured in units of 512-byte sectors โ€” even if the sectorsize isn't actually 512 bytes... weird, I know, don't ask ๐Ÿ’€

See also $g->blockdev_getss for the real sector size of the device, and $g->blockdev_getsize64 for the way more useful size in bytes.

This uses the blockdev(8) command.

$g->blockdev_rereadpt ($device);

Rereads the partition table on device. Fresh eyes on the situation ๐Ÿ‘€

This uses the blockdev(8) command.

$g->blockdev_setbsz ($device, $blocksize);

Okay so this call does nothing and has never done anything, because of a bug in blockdev. Do not use it. Like, at all. ๐Ÿ™ˆ

If you actually need to set the filesystem block size, use the blocksize option of $g->mkfs.

This function is deprecated. There is no replacement. Consult the API documentation in guestfs(3) for further information.

Deprecated functions will not be removed from the API, but the fact that they are deprecated indicates that there are problems with correct use of these functions. So maybe don't, bestie.
$g->blockdev_setra ($device, $sectors);

Sets readahead for the device, measured in 512-byte sectors.

This uses the blockdev(8) command.

$g->blockdev_setro ($device);

Sets the block device named device to read-only ๐Ÿ”’

This uses the blockdev(8) command.

$g->blockdev_setrw ($device);

Sets the block device named device to read-write โœ๏ธ

This uses the blockdev(8) command.


๐Ÿ’š the btrfs era (we're so back)

$g->btrfs_balance_cancel ($path);

Cancels a running balance on a btrfs filesystem. Say less ๐Ÿซถ

This function depends on the feature btrfs. See also $g->feature-available.

$g->btrfs_balance_pause ($path);

Pauses a running balance on a btrfs filesystem. It's giving "brb" โœ‹

This function depends on the feature btrfs. See also $g->feature-available.

$g->btrfs_balance_resume ($path);

Resumes a paused balance on a btrfs filesystem. And we're back ๐Ÿ’…

This function depends on the feature btrfs. See also $g->feature-available.

%status = $g->btrfs_balance_status ($path);

Shows the status of a running or paused balance on a btrfs filesystem. Receipts ๐Ÿ“‹

This function depends on the feature btrfs. See also $g->feature-available.

$g->btrfs_device_add (\@devices, $fs);

Adds the list of device(s) in devices to the btrfs filesystem mounted at fs. If devices is an empty list, this does nothing โ€” quiet quitting, honestly.

This function depends on the feature btrfs. See also $g->feature-available.

$g->btrfs_device_delete (\@devices, $fs);

Removes the devices from the btrfs filesystem mounted at fs. If devices is an empty list, this does nothing. Same energy, but in reverse ๐Ÿฆ‹

This function depends on the feature btrfs. See also $g->feature-available.

$g->btrfs_filesystem_balance ($fs);

Balances the chunks in the btrfs filesystem mounted at fs across the underlying devices. Very "sharing is caring" of it โœจ

This function depends on the feature btrfs. See also $g->feature-available.

$g->btrfs_filesystem_defragment ($path [, flush => $flush] [, compress => $compress]);

Defragments a file or directory on a btrfs filesystem. compress is one of zlib or lzo. Tidy that up, queen ๐ŸŽ€

This function depends on the feature btrfs. See also $g->feature-available.

$g->btrfs_filesystem_resize ($mountpoint [, size => $size]);

This command resizes a btrfs filesystem.

Important lore: unlike other resize calls, the filesystem has to be mounted, and the parameter is the mountpoint, not the device (that's a requirement of btrfs itself, not us, don't come for me ๐Ÿ˜ญ).

The optional parameters are:

  • size โ€” the new size (in bytes) of the filesystem. If it's omitted, the filesystem gets resized to the maximum size. Go big or go home ๐Ÿ“

See also btrfs(8).

This function depends on the feature btrfs. See also $g->feature-available.

@devices = $g->btrfs_filesystem_show ($device);

Shows all the devices where the filesystems in device is spanned over.

If not all the devices for the filesystems are present, then this function fails and the errno is set to ENODEV. Rude but fair ๐Ÿ’€

This function depends on the feature btrfs. See also $g->feature-available.

$g->btrfs_filesystem_sync ($fs);

Forces a sync on the btrfs filesystem mounted at fs. Flush it, bestie ๐Ÿšฝ (affectionate)

This function depends on the feature btrfs. See also $g->feature-available.

$g->btrfs_fsck ($device [, superblock => $superblock] [, repair => $repair]);

Used to check a btrfs filesystem โ€” device is the device file where the filesystem is stored.

This function depends on the feature btrfs. See also $g->feature-available.

This function is deprecated. In new code, use the btrfs_scrub_full call instead.

Deprecated functions will not be removed from the API, but the fact that they are deprecated indicates that there are problems with correct use of these functions. So like... use the new one, okay? ๐Ÿซถ
$g->btrfs_image (\@source, $image [, compresslevel => $compresslevel]);

This is used to create an image of a btrfs filesystem. All data will be zeroed, but metadata and the like is preserved. It's giving "skeleton but make it fashion" ๐Ÿ’€โœจ

This function depends on the feature btrfs. See also $g->feature-available.

$g->btrfs_qgroup_assign ($src, $dst, $path);

Adds qgroup src to the parent qgroup dst. This command can group several qgroups into a parent qgroup so they share a common limit. Found family ๐Ÿซถ

This function depends on the feature btrfs. See also $g->feature-available.

$g->btrfs_qgroup_create ($qgroupid, $subvolume);

Creates a quota group (qgroup) for the subvolume at subvolume. New qgroup just dropped ๐Ÿ‘‘

This function depends on the feature btrfs. See also $g->feature-available.

$g->btrfs_qgroup_destroy ($qgroupid, $subvolume);

Destroys a quota group. It's over, it's not doing it again ๐Ÿ’€

This function depends on the feature btrfs. See also $g->feature-available.

$g->btrfs_qgroup_limit ($subvolume, $size);

Limits the size of the subvolume with path subvolume. Setting boundaries, we love to see it ๐Ÿšง

This function depends on the feature btrfs. See also $g->feature-available.

$g->btrfs_qgroup_remove ($src, $dst, $path);

Removes qgroup src from the parent qgroup dst. Un-inviting it from the group chat โœŒ๏ธ

This function depends on the feature btrfs. See also $g->feature-available.

@qgroups = $g->btrfs_qgroup_show ($path);

Shows all subvolume quota groups in a btrfs filesystem, including their usages. The full receipts, usages and all ๐Ÿ“Š

This function depends on the feature btrfs. See also $g->feature-available.

$g->btrfs_quota_enable ($fs, $enable);

Enables or disables subvolume quota support for the filesystem which contains path. Toggle era ๐ŸŒ—

This function depends on the feature btrfs. See also $g->feature-available.

$g->btrfs_quota_rescan ($fs);

Trashes all qgroup numbers and scans the metadata again with the current config. Cue the "starting over" playlist ๐ŸŽง

This function depends on the feature btrfs. See also $g->feature-available.

$g->btrfs_replace ($srcdev, $targetdev, $mntpoint);

Replaces a device of a btrfs filesystem. On a live filesystem, it duplicates the data to the target device which is currently stored on the source device. After the operation completes, the source device is wiped out and removed from the filesystem. Glow-up complete, old device is gone ๐Ÿ’…

Important: the targetdev needs to be same size or larger than the srcdev. And devices which are currently mounted are never allowed to be used as the targetdev. Read that again, it matters ๐Ÿšจ

This function depends on the feature btrfs. See also $g->feature-available.

$g->btrfs_rescue_chunk_recover ($device);

Recovers the chunk tree of a btrfs filesystem by scanning the devices one by one. One at a time, we're being thorough ๐Ÿ•ต๏ธ

This function depends on the feature btrfs. See also $g->feature-available.

$g->btrfs_rescue_super_recover ($device);

Recovers bad superblocks from good copies. The good copies said "I got you" ๐Ÿซถ

This function depends on the feature btrfs. See also $g->feature-available.

$g->btrfs_scrub_cancel ($path);

Cancels a running scrub on a btrfs filesystem. Stop the scan, we're done here โœ‹

This function depends on the feature btrfs. See also $g->feature-available.

$g->btrfs_scrub_full ($path [, readonly => $readonly]);

Runs a full scrub on a btrfs filesystem and waits for it to finish. If the filesystem has errors this will return an error. Full send, no shortcuts ๐Ÿ”ฅ

This function depends on the feature btrfs. See also $g->feature-available.

$g->btrfs_scrub_resume ($path);

Resumes a previously canceled or interrupted scrub on a btrfs filesystem. Where were we? ๐Ÿ‘€

This function depends on the feature btrfs. See also $g->feature-available.

$g->btrfs_scrub_start ($path);

Reads all the data and metadata on the filesystem, and uses checksums and the duplicate copies from RAID storage to identify and repair any corrupt data. Detective mode: activated ๐Ÿ”

This function depends on the feature btrfs. See also $g->feature-available.

%status = $g->btrfs_scrub_status ($path);

Shows the status of a running or finished scrub on a btrfs filesystem. Status check, bestie ๐Ÿ’…

This function depends on the feature btrfs. See also $g->feature-available.

$g->btrfs_set_seeding ($device, $seeding);

Enables or disables the seeding feature of a device that contains a btrfs filesystem. Plant the seed or don't ๐ŸŒฑ

This function depends on the feature btrfs. See also $g->feature-available.

$g->btrfs_subvolume_create ($dest [, qgroupid => $qgroupid]);

Creates a btrfs subvolume. The dest argument is the destination directory and the name of the subvolume, in the form /path/to/dest/name. The optional parameter qgroupid represents the qgroup which the newly created subvolume will be added to. New subvolume, who dis ๐ŸŽ€

This function depends on the feature btrfs. See also $g->feature-available.

$g->btrfs_subvolume_create_opts ($dest [, qgroupid => $qgroupid]);

This is an alias of btrfs_subvolume_create. Same thing, different name, iykyk ๐Ÿ’…

$g->btrfs_subvolume_delete ($subvolume);

Deletes the named btrfs subvolume or snapshot. Bye bestie, it was real ๐Ÿ˜ญ

$id = $g->btrfs_subvolume_get_default ($fs);

Grab the default subvolume (or snapshot, no judgement) of the filesystem mounted at mountpoint. ๐Ÿ’…

This one's a feature-gated baddie โ€” it needs the feature "btrfs". Peep also $g->feature-available. โœจ

@subvolumes = $g->btrfs_subvolume_list ($fs);

Lists out all the btrfs snapshots and subvolumes of the btrfs filesystem mounted at fs. It's giving inventory era fr fr. ๐ŸŽ€

Needs the feature "btrfs" โ€” see also $g->feature-available.

$g->btrfs_subvolume_set_default ($id, $fs);

Sets which subvolume of the btrfs filesystem fs gets mounted by default. Want the list of subvolumes to pick from? That's $g->btrfs_subvolume_list, bestie. ๐Ÿ‘‘

Feature "btrfs" required โ€” see also $g->feature-available.

%btrfssubvolumeinfo = $g->btrfs_subvolume_show ($subvolume);

Returns detailed info about the subvolume. The whole lore, basically. ๐Ÿ”

Feature "btrfs" required โ€” see also $g->feature-available.

$g->btrfs_subvolume_snapshot ($source, $dest [, ro => $ro] [, qgroupid => $qgroupid]);

Makes a snapshot of the btrfs subvolume source. The dest arg is the destination directory and the name of the snapshot, written like /path/to/dest/name.

By default the new snapshot comes out writable โ€” but if you pass the optional ro parameter as true, you get a readonly snapshot instead. ๐Ÿ”’ The optional qgroupid parameter is the qgroup that the newly created snapshot gets added to.

Feature "btrfs" required โ€” see also $g->feature-available.

$g->btrfs_subvolume_snapshot_opts ($source, $dest [, ro => $ro] [, qgroupid => $qgroupid]);

Lowkey just an alias of "btrfs_subvolume_snapshot". Same energy, different name. ๐Ÿซถ

$g->btrfstune_enable_extended_inode_refs ($device);

This will Enable extended inode refs. (Yes capitals, we don't make the rules.) โœจ

Feature "btrfs" required โ€” see also $g->feature-available.

$g->btrfstune_enable_skinny_metadata_extent_refs ($device);

This enable skinny metadata extent refs. Skinny metadata, skinny legend. ๐Ÿงš

Feature "btrfs" required โ€” see also $g->feature-available.

$g->btrfstune_seeding ($device, $seeding);

Turns on seeding for a btrfs device โ€” which forces the fs readonly so you can use it as a base to build other filesystems off of. Very "template era" of it. ๐ŸŒฑ

Feature "btrfs" required โ€” see also $g->feature-available.

$ptr = $g->c_pointer ();

For the non-C language bindings: this lets you grab the underlying C pointer to the handle (ie. "$g->h *"). The whole point is so other libraries can interwork with libguestfs. ๐Ÿค

$canonical = $g->canonical_device_name ($device);

A lil utility function that's genuinely so useful when you're showing device names to a human. It takes all these irregular device names and hands them back in a consistent format:

  • /dev/hdX, /dev/vdX โ€” returned as /dev/sdX. Note this works for device names and partition names. This is approximately the reverse of the algorithm described in "BLOCK DEVICE NAMING" in guestfs(3).
  • /dev/mapper/VG-LV, /dev/dm-N โ€” converted to /dev/VG/LV form using "$g->lvm_canonical_lv_name".

Any other strings come back unmodified. Periodt. ๐Ÿ’ซ

$cap = $g->cap_get_file ($path);

Returns the Linux capabilities attached to path. The capabilities set comes back in text form (see cap_to_text(3)).

If there are no capabilities attached to a file, you get an empty string back. ๐Ÿ’€

Feature "linuxcaps" required โ€” see also $g->feature-available.

$g->cap_set_file ($path, $cap);

Sets the Linux capabilities attached to path. Pass the capabilities set cap in text form (see cap_from_text(3)). ๐ŸŽ€

Feature "linuxcaps" required โ€” see also $g->feature-available.

$rpath = $g->case_sensitive_path ($path);

Okay this one's iconic. Use it to resolve case insensitive paths on a filesystem that is itself case sensitive. Classic use case: you've got paths you read out of Windows configuration files or the Windows Registry, and you need the true path.

The command handles a peculiarity of the Linux ntfs-3g filesystem driver (and probably others), which is that although the underlying filesystem is case-insensitive, the driver exports the filesystem to Linux as case-sensitive. ๐Ÿ™ˆ

One consequence of this is that special directories such as C:\windows may appear as /WINDOWS or /windows (or other things) depending on the precise details of how they were created. In Windows itself this would not be a problem.

Bug or feature? You decide. See the relevant entry in the ntfs-3g FAQ: https://github.com/tuxera/ntfs-3g/wiki/NTFS-3G-FAQ

"$g->case_sensitive_path" attempts to resolve the true case of each element in the path. It returns a resolved path if either the full path or its parent directory exists. If the parent directory exists but the full path doesn't, the case of the parent directory gets correctly resolved, and the remainder is appended unmodified. For example, if the file "/Windows/System32/netkvm.sys" exists:

  • "$g->case_sensitive_path" ("/windows/system32/netkvm.sys") โ†’ "Windows/System32/netkvm.sys"
  • "$g->case_sensitive_path" ("/windows/system32/NoSuchFile") โ†’ "Windows/System32/NoSuchFile"
  • "$g->case_sensitive_path" ("/windows/system33/netkvm.sys") โ†’ ERROR
Note: because of the behaviour above, "$g->case_sensitive_path" cannot be used to check for the existence of a file. Not the tool for that, bestie. ๐Ÿ’€
Note: this function does not handle drive names, backslashes etc.

See also "$g->realpath".

$content = $g->cat ($path);

Returns the contents of the file named path. Simple, clean, slay. ๐Ÿฑ

But โ€” because in C this function returns a "char *", there is genuinely no way to tell the difference between a "\0" character in a file and end of string. So for binary files, use the "$g->read_file" or "$g->download" functions instead. ๐Ÿซถ

$checksum = $g->checksum ($csumtype, $path);

Computes the MD5, SHAx or CRC checksum of the file named path.

The kind of checksum you get is decided by the csumtype parameter, which must be one of these:

  • "crc" โ€” compute the cyclic redundancy check (CRC) specified by POSIX for the "cksum" command.
  • "gost", "gost12" โ€” compute the checksum using GOST R34.11-94 or GOST R34.11-2012 message digest.
  • "md5" โ€” compute the MD5 hash (using the md5sum(1) program).
  • "sha1" โ€” compute the SHA1 hash (using the sha1sum(1) program).
  • "sha224" โ€” compute the SHA224 hash (using the sha224sum(1) program).
  • "sha256" โ€” compute the SHA256 hash (using the sha256sum(1) program).
  • "sha384" โ€” compute the SHA384 hash (using the sha384sum(1) program).
  • "sha512" โ€” compute the SHA512 hash (using the sha512sum(1) program).

The checksum comes back as a printable string. โœจ

Want the checksum for a device? Use "$g->checksum_device". Want checksums for many files? Use "$g->checksums_out".

$checksum = $g->checksum_device ($csumtype, $device);

Computes the MD5, SHAx or CRC checksum of the contents of the device named device. For which checksum types are supported, see the "$g->checksum" command. Same menu, different target. ๐Ÿ’…

$g->checksums_out ($csumtype, $directory, $sumsfile);

Computes the checksums of all regular files in directory and then emits a list of those checksums to the local output file sumsfile. ๐Ÿ“

You can use this to verify the integrity of a virtual machine. However, to be properly secure you should pay attention to the output of the checksum command (it uses the ones from GNU coreutils). In particular, when the filename isn't printable, coreutils uses a special backslash syntax. For more info, see the GNU coreutils info file.

Security caveat stays a security caveat, bestie โ€” don't skip that part. ๐Ÿšจ

$g->chmod ($mode, $path);

Changes the mode (permissions) of path to mode. Only numeric modes are supported. ๐Ÿ”ข

Note: when you're using this command from guestfish, mode by default would be decimal โ€” unless you prefix it with 0 to get octal, ie. use 0700 not 700. Learn from my mistakes fr fr. ๐Ÿ˜ญ

The mode actually set is affected by the umask.

$g->chown ($owner, $group, $path);

Changes the file owner to owner and group to group. ๐Ÿ‘‘

Only numeric uid and gid are supported. If you want to use names, you'll need to locate and parse the password file yourself (Augeas support makes this relatively easy). DIY era.

$count = $g->clear_backend_setting ($name);

If there's a backend setting string matching name or beginning with name=, then that string is removed from the backend settings. Bye bye. ๐Ÿ‘‹

This call returns the number of strings that were removed (which may be 0, 1 or greater than 1).

See "BACKEND" in guestfs(3), "BACKEND SETTINGS" in guestfs(3).

$g->clevis_luks_unlock ($device, $mapname);

This command opens a block device that's been encrypted according to the Linux Unified Key Setup (LUKS) standard, using network-bound disk encryption (NBDE). ๐Ÿ”โœจ

device is the encrypted block device.

The appliance will connect to the Tang servers noted in the tree of Clevis pins that is bound to a keyslot of the LUKS header. The Clevis pin tree may comprise "sss" (redundancy) pins as internal nodes (optionally), and "tang" pins as leaves. "tpm2" pins are not supported. The appliance unlocks the encrypted block device by combining responses from the Tang servers with metadata from the LUKS header; there is no "key" parameter. ๐Ÿ—๏ธ

This command will fail if networking has not been enabled for the appliance. Refer to "$g->set_network".

The command creates a new block device called /dev/mapper/mapname. Reads and writes to this block device are decrypted from and encrypted to the underlying device respectively. Close the decrypted block device with "$g->cryptsetup_close".

mapname cannot be "control" because that name is reserved by device-mapper. ๐Ÿšซ

If this block device contains LVM volume groups, then calling "$g->lvm_scan" with the "activate" parameter "true" will make them visible.

Use "$g->list_dm_devices" to list all device mapper devices.

Feature "clevisluks" required โ€” see also $g->feature-available. ๐Ÿฆ‹

$output = $g->command (\@arguments);

Okay bestie, this one runs a command inside the guest filesystem ๐Ÿƒโ€โ™€๏ธ๐Ÿ’จ. Real talk though โ€” the filesystem has to be mounted, and it has to contain a compatible operating system (ie. something Linux, with the same or compatible processor architecture). No vibes-based guessing, it's giving strict ๐Ÿ’….

The single parameter is an argv-style list of arguments. First element = the name of the program to run. Every element after that = parameters. The list must be non-empty (ie. must contain a program name โ€” that's kind of the whole point, babe ๐Ÿ˜ญ). Big note: the command runs directly, and is not invoked via the shell (peep $g->sh if that's the energy you want).

The return value is literally anything printed to stdout by the command โœจ.

If the command returns a non-zero exit status, then this function returns an error message. The error message string is the content of stderr from the command. So stderr is your new bestie when things go sideways ๐Ÿ’€.

The $PATH environment variable will contain at least /usr/bin and /bin. If you require a program from another location, you should provide the full path in the first parameter. Don't be shy, spell it out ๐Ÿซถ.

Shared libraries and data files required by the program must be available on filesystems which are mounted in the correct places. It is the caller's responsibility to ensure all filesystems that are needed are mounted at the right locations. Yes, that's you. You're the caller. You're the main character ๐Ÿ‘‘.

Because of the message protocol, there is a transfer limit of somewhere between 2MB and 4MB. See "PROTOCOL LIMITS" in guestfs(3). ๐ŸŒธ

@lines = $g->command_lines (\@arguments);

This is the same as $g->command, but splits the result into a list of lines. Lowkey the same slay, just pre-sliced for your convenience ๐Ÿ“.

See also: $g->sh_lines

Because of the message protocol, there is a transfer limit of somewhere between 2MB and 4MB. See "PROTOCOL LIMITS" in guestfs(3). ๐Ÿ’€

$g->command_out (\@arguments, $output);

This is the same as $g->command, but streams the output back, handling the case where the output from the command is larger than the protocol limit. So when your output is doing too much, this one doesn't fold ๐Ÿซถ.

See also: $g->sh_out


$g->compress_device_out ($ctype, $device, $zdevice [, level => $level]);

This command compresses device and writes it out to the local file zdevice. Compress and yeet, iconic behavior ๐ŸŽ€.

The ctype and optional level parameters have the same meaning as in $g->compress_out.


$g->compress_out ($ctype, $file, $zfile [, level => $level]);

This command compresses file and writes it out to the local file zfile. It's giving zip-zip-hooray ๐Ÿ’….

The compression program used is controlled by the ctype parameter. Currently this includes: compress, gzip, bzip2, xz or lzop. Some compression types may not be supported by particular builds of libguestfs, in which case you will get an error containing the substring not supported. So if it's acting up, check that substring before you spiral ๐Ÿ˜ญ.

The optional level parameter controls compression level. The meaning and default for this parameter depends on the compression program being used. It's giving "read the room, each program has its own lore" ๐ŸŒˆ.


$g->config ($hvparam, $hvvalue);

This can be used to add arbitrary hypervisor parameters of the form -param value. Actually it's not quite arbitrary โ€” we prevent you from setting some parameters which would interfere with parameters that we use. Protective? Maybe. Necessary? Absolutely ๐Ÿ›ก๏ธ.

The first character of hvparam string must be a - (dash). No dash, no deal, periodt.

hvvalue can be NULL.


$g->copy_attributes ($src, $dest [, all => $all] [, mode => $mode] [, xattributes => $xattributes] [, ownership => $ownership]);

Copy the attributes of a path (which can be a file or a directory) to another path. Attribute hand-me-downs, cute ๐ŸŽ€.

By default no attribute is copied, so make sure to specify any (or all to copy everything). Default does nothing? Yeah, you gotta ask, bestie.

The optional arguments specify which attributes can be copied:

  • mode โ€” Copy part of the file mode from source to destination. Only the UNIX permissions and the sticky/setuid/setgid bits can be copied.
  • xattributes โ€” Copy the Linux extended attributes (xattrs) from source to destination. This flag does nothing if the linuxxattrs feature is not available (see $g->feature_available).
  • ownership โ€” Copy the owner uid and the group gid of source to destination.
  • all โ€” Copy all the attributes from source to destination. Enabling it enables all the other flags, if they are not specified already.

$g->copy_device_to_device ($src, $dest [, srcoffset => $srcoffset] [, destoffset => $destoffset] [, size => $size] [, sparse => $sparse] [, append => $append]);

The four calls $g->copy_device_to_device, $g->copy_device_to_file, $g->copy_file_to_device, and $g->copy_file_to_file let you copy from a source (device|file) to a destination (device|file). Four flavors, same iconic energy โœจ.

Partial copies can be made since you can specify optionally the source offset, destination offset and size to copy. These values are all specified in bytes. If not given, the offsets both default to zero, and the size defaults to copying as much as possible until we hit the end of the source. Sensible defaults, we love to see it ๐Ÿ‘‘

The source and destination may be the same object. However overlapping regions may not be copied correctly. โš ๏ธ That's a real one, don't ignore it.

If the destination is a file, it is created if required. If the destination file is not large enough, it is extended. Growth mindset ๐Ÿ’….

If the destination is a file and the append flag is not set, then the destination file is truncated. If the append flag is set, then the copy appends to the destination file. The append flag currently cannot be set for devices. Noted, bestie ๐Ÿ“.

If the sparse flag is true then the call avoids writing blocks that contain only zeroes, which can help in some situations where the backing disk is thin-provisioned. Note that unless the target is already zeroed, using this option will result in incorrect copying. ๐Ÿ’€ So like, it's useful but also a trap if you're not careful.


$g->copy_device_to_file ($src, $dest [, srcoffset => $srcoffset] [, destoffset => $destoffset] [, size => $size] [, sparse => $sparse] [, append => $append]);

See $g->copy_device_to_device for a general overview of this call. Family reunion, same lore ๐Ÿซถ.


$g->copy_file_to_device ($src, $dest [, srcoffset => $srcoffset] [, destoffset => $destoffset] [, size => $size] [, sparse => $sparse] [, append => $append]);

See $g->copy_device_to_device for a general overview of this call. Same family, different direction ๐Ÿ”„.


$g->copy_file_to_file ($src, $dest [, srcoffset => $srcoffset] [, destoffset => $destoffset] [, size => $size] [, sparse => $sparse] [, append => $append]);

See $g->copy_device_to_device for a general overview of this call.

This is not the function you want for copying files. ๐Ÿšจ This is for copying blocks within existing files. See $g->cp, $g->cp_a and $g->mv for general file copying and moving functions. I cannot stress this enough, bestie โ€” wrong tool, wrong vibe, wrong result ๐Ÿ˜ญ.

$g->copy_in ($localpath, $remotedir);

$g->copy_in copies local files or directories recursively into the disk image, placing them in the directory called remotedir (which must exist). Recursive, no cap ๐ŸŒ€.

Wildcards cannot be used. Don't try it, it won't eat.


$g->copy_out ($remotepath, $localdir);

$g->copy_out copies remote files or directories recursively out of the disk image, placing them on the host disk in a local directory called localdir (which must exist). It's giving reverse uno card ๐Ÿƒ.

To download to the current directory, use . as in:

"$g->copy_out" /home .

Wildcards cannot be used. Same rule, same energy, periodt.


$g->copy_size ($src, $dest, $size);

This command copies exactly size bytes from one source device or file src to another destination device or file dest. Exact, precise, no crumbs ๐Ÿ’….

Note this will fail if the source is too short or if the destination is not large enough. Check your sizes before you commit, bestie ๐Ÿ“.

This function is deprecated. โš ๏ธ In new code, use the copy_device_to_device call instead.

Deprecated functions will not be removed from the API, but the fact that they are deprecated indicates that there are problems with correct use of these functions. So like, it still exists, but it's giving red flag ๐Ÿšฉ.


$g->cp ($src, $dest);

This copies a file from src to dest where dest is either a destination filename or destination directory. Classic copy, no drama ๐Ÿ’–.


$g->cp_a ($src, $dest);

This copies a file or directory from src to dest recursively using the cp -a command. Preserves the good stuff, the whole package ๐ŸŽ€.


$g->cp_r ($src, $dest);

This copies a file or directory from src to dest recursively using the cp -rP command.

Most users should use $g->cp_a instead. This command is useful when you don't want to preserve permissions, because the target filesystem does not support it (primarily when writing to DOS FAT filesystems). Niche but valid, iykyk ๐Ÿฆ‹.


$g->cpio_out ($directory, $cpiofile [, format => $format]);

This command packs the contents of directory and downloads it to local file cpiofile. Pack it up, pack it in ๐ŸŽ.

The optional format parameter can be used to select the format. Only the following formats are currently permitted:

  • newc โ€” New (SVR4) portable format. This format happens to be compatible with the cpio-like format used by the Linux kernel for initramfs. This is the default format. She's the default for a reason โœจ.
  • crc โ€” New (SVR4) portable format with a checksum. Extra checksum, extra careful, we respect it ๐Ÿซถ.

$g->cryptsetup_close ($device);

This closes an encrypted device that was created earlier by $g->cryptsetup_open. The device parameter must be the name of the mapping device (ie. /dev/mapper/mapname) and not the name of the underlying block device. Read that again, bestie โ€” the mapping name, not the raw one ๐Ÿ’€.

This function depends on the feature luks. See also $g->feature-available. (Yes, with the hyphen, exactly like that โ€” don't come for me ๐Ÿ™ˆ.)


$g->cryptsetup_open ($device, $key, $mapname [, readonly => $readonly] [, crypttype => $crypttype] [, cipher => $cipher]);

This command opens a block device which has been encrypted according to the Linux Unified Key Setup (LUKS) standard, Windows BitLocker, or some other types. Unlocking the mystery, literally ๐Ÿ”“โœจ.

device is the encrypted block device or partition.

The caller must supply one of the keys associated with the encrypted block device, in the key parameter. You need the key, babe, there's no backdoor shortcut here ๐Ÿ—๏ธ.

This creates a new block device called /dev/mapper/mapname. Reads and writes to this block device are decrypted from and encrypted to the underlying device respectively. So smooth you forget it's encrypted ๐Ÿ’….

mapname cannot be control because that name is reserved by device-mapper. Reserved! Do not touch! ๐Ÿšซ

If the optional crypttype parameter is not present then libguestfs tries to guess the correct type (for example LUKS or BitLocker). However you can override this by specifying one of the following types:

  • luks โ€” A Linux LUKS device.
  • bitlk โ€” A Windows BitLocker device.

The optional readonly flag, if set to true, creates a read-only mapping. Look but don't touch, iconic ๐ŸŒธ.

The optional cipher parameter allows specifying which cipher to use. Choose your fighter ๐Ÿงš.

So if this block device has LVM volume groups, calling $g->lvm_scan with the "activate" parameter set to "true" is what makes them visible. โœจ Use $g->list_dm_devices to list all device mapper devices. This function depends on the feature "luks". See also $g->feature-available. ๐Ÿซถ

$g->dd ($src, $dest);

Okay so this one copies from one source device or file, src, to another destination device or file, dest. Normally youโ€™d use it to copy to or from a device or partition โ€” like duplicating a filesystem. ๐ŸŽ€

If the destination is a device, it must be as large or larger than the source file or device, otherwise the copy will fail. This command cannot do partial copies (see $g->copy_device_to_device). ๐Ÿ’…

This function is deprecated. In new code, use the "copy_device_to_device" call instead. Deprecated functions will not be removed from the API, but the fact that they are deprecated indicates that there are problems with correct use of these functions.

$index = $g->device_index ($device);

This takes a device name (eg. /dev/sdb) and returns the index of the device in the list of devices. Index numbers start from 0. The named device must exist, for example as a string returned from $g->list_devices. ๐ŸŒธ

See also $g->list_devices, $g->part_to_dev, $g->device_name.

$name = $g->device_name ($index);

This takes a device index and returns the device name. For example index 0 will return the string /dev/sda. The drive index must have been added to the handle. ๐Ÿฆ‹

See also $g->list_devices, $g->part_to_dev, $g->device_index.

$output = $g->df ();

This command runs the df(1) command to report disk space used. Itโ€™s mostly useful for interactive sessions. It is not intended that you try to parse the output string โ€” use $g->statvfs from programs instead. ๐Ÿ’–

$output = $g->df_h ();

This command runs the "df -h" command to report disk space used in human-readable format. Same vibe check as above: mostly for interactive sessions, not for parsing. Use $g->statvfs from programs. ๐ŸŒˆ

$g->disk_create ($filename, $format, $size [, backingfile =>
$backingfile] [, backingformat => $backingformat] [, preallocation =>
$preallocation] [, compat => $compat] [, clustersize => $clustersize]);

Create a blank disk image called filename (a host file) with format "format" (usually "raw" or "qcow2"). The size is "size" bytes. ๐ŸŽ€

If used with the optional "backingfile" parameter, then a snapshot is created on top of the backing file. In this case, "size" must be passed as -1. The size of the snapshot is the same as the size of the backing file, which is discovered automatically. You are encouraged to also pass "backingformat" to describe the format of "backingfile". โœจ

If filename refers to a block device, then the device is formatted. The "size" is ignored since block devices have an intrinsic size.

The other optional parameters are:

  • preallocation โ€” If format is "raw", then this can be either "off" (or "sparse") or "full" to create a sparse or fully allocated file respectively. The default is "off". If format is "qcow2", then this can be "off" (or "sparse"), "metadata" or "full". Preallocating metadata can be faster when doing lots of writes, but uses more space. The default is "off".
  • compat โ€” "qcow2" only: Pass the string 1.1 to use the advanced qcow2 format supported by qemu โ‰ฅ 1.1.
  • clustersize โ€” "qcow2" only: Change the qcow2 cluster size. The default is 65536 (bytes) and this setting may be any power of two between 512 and 2097152.

Note that this call does not add the new disk to the handle. You may need to call $g->add_drive_opts separately. ๐Ÿ‘‘

$format = $g->disk_format ($filename);

Detect and return the format of the disk image called filename. filename can also be a host device, etc. If the format of the image could not be detected, then "unknown" is returned. ๐ŸŒŸ

Note that detecting the disk format can be insecure under some circumstances. See "CVE-2010-3851" in guestfs(3).

See also: "DISK IMAGE FORMATS" in guestfs(3)

$backingfile = $g->disk_has_backing_file ($filename);

Detect and return whether the disk image filename has a backing file. ๐Ÿซถ

Note that detecting disk features can be insecure under some circumstances. See "CVE-2010-3851" in guestfs(3).

$size = $g->disk_virtual_size ($filename);

Detect and return the virtual size in bytes of the disk image called filename. ๐Ÿ’œ

Note that detecting disk features can be insecure under some circumstances. See "CVE-2010-3851" in guestfs(3).

$kmsgs = $g->dmesg ();

This returns the kernel messages (dmesg(1) output) from the guest kernel. This is sometimes useful for extended debugging of problems. ๐Ÿ•ต๏ธโ€โ™€๏ธ

Another way to get the same information is to enable verbose messages with $g->set_verbose or by setting the environment variable LIBGUESTFS_DEBUG=1 before running the program.

$g->download ($remotefilename, $filename);

Download file remotefilename and save it as filename on the local machine. filename can also be a named pipe. ๐ŸŽ€

See also $g->upload, $g->cat.

$g->download_blocks ($device, $start, $stop, $filename [, unallocated => $unallocated]);

Download the data units from start address to stop from the disk partition (eg. /dev/sda1) and save them as filename on the local machine. ๐Ÿฆ‹

The use of this API on sparse disk image formats such as QCOW, may result in large zero-filled files downloaded on the host.

The size of a data unit varies across filesystem implementations. On NTFS filesystems data units are referred as clusters while on ExtX ones they are referred as fragments. ๐ŸŒธ

If the optional "unallocated" flag is true (default is false), only the unallocated blocks will be extracted. This is useful to detect hidden data or to retrieve deleted files which data units have not been overwritten yet.

This function depends on the feature "sleuthkit". See also $g->feature-available.

$g->download_inode ($device, $inode, $filename);

Download a file given its inode from the disk partition (eg. /dev/sda1) and save it as filename on the local machine. ๐Ÿ’–

It is not required to mount the disk to run this command. The command is capable of downloading deleted or inaccessible files. ๐Ÿ˜ญ

This function depends on the feature "sleuthkit". See also $g->feature-available.

$g->download_offset ($remotefilename, $filename, $offset, $size);

Download file remotefilename and save it as filename on the local machine. remotefilename is read for "size" bytes starting at "offset" (this region must be within the file or device). โœจ

Note that there is no limit on the amount of data that can be downloaded with this call, unlike with $g->pread, and this call always reads the full amount unless an error occurs.

See also $g->download, $g->pread.

$g->drop_caches ($whattodrop);

This instructs the guest kernel to drop its page cache, and/or dentries and inode caches. The parameter "whattodrop" tells the kernel what precisely to drop, see <https://linux-mm.org/Drop_Caches>. ๐Ÿงน

Setting "whattodrop" to 3 should drop everything.

This automatically calls sync(2) before the operation, so that the maximum guest memory is freed.

$sizekb = $g->du ($path);

This command runs the "du -s" command to estimate file space usage for "path". ๐Ÿ“

"path" can be a file or a directory. If "path" is a directory then the estimate includes the contents of the directory and all subdirectories (recursively). The result is the estimated size in kilobytes (ie. units of 1024 bytes).

$g->e2fsck ($device [, correct => $correct] [, forceall => $forceall] [, forceno => $forceno]);

This runs the ext2/ext3 filesystem checker on "device". It can take the following optional arguments: ๐Ÿฉบ

  • correct โ€” Automatically repair the file system. This option will cause e2fsck to automatically fix any filesystem problems that can be safely fixed without human intervention. This option may not be specified at the same time as the "forceall" or "forceno" options.
  • forceall โ€” Assume an answer of โ€˜yesโ€™ to all questions; allows e2fsck to be used non-interactively. This option may not be specified at the same time as the "correct" or "forceno" options.
  • forceno โ€” Open the filesystem readonly and assume an answer of โ€˜noโ€™ to all questions; allows e2fsck to be used non-interactively. This option may not be specified at the same time as the "correct" or "forceall" options.

$g->e2fsck_f ($device);

This runs "e2fsck -p -f device", ie. runs the ext2/ext3 filesystem checker on "device", noninteractively (-p), even if the filesystem appears to be clean (-f). ๐Ÿ’…

This function is deprecated. In new code, use the "e2fsck" call instead. Deprecated functions will not be removed from the API, but the fact that they are deprecated indicates that there are problems with correct use of these functions.

$output = $g->echo_daemon (\@words);

This command concatenates the list of "words" passed with single spaces between them and returns the resulting string. ๐ŸŽ€

You can use this command to test the connection through to the daemon.

See also $g->ping_daemon.

@lines = $g->egrep ($regex, $path);

This calls the external egrep(1) program and returns the matching lines.

Because of the message protocol, there is a transfer limit of somewhere between 2MB and 4MB. See "PROTOCOL LIMITS" in guestfs(3). ๐Ÿ˜ญ

This function is deprecated. In new code, use the "grep" call instead. Deprecated functions will not be removed from the API, but the fact that they are deprecated indicates that there are problems with correct use of these functions.

@lines = $g->egrepi ($regex, $path);

This calls the external "egrep -i" program and returns the matching lines. ๐ŸŒˆ

Because of the message protocol, there is a transfer limit of somewhere between 2MB and 4MB. See "PROTOCOL LIMITS" in guestfs(3).

This function is deprecated. In new code, use the grep call instead, bestie. ๐Ÿซถ

Deprecated functions will not be removed from the API, but the fact that they are deprecated indicates that there are problems with correct use of these functions. Like, it's not getting deleted, it's just getting side-eye. ๐Ÿ’…


  • $equality = $g->equal ($file1, $file2); โ€” compares the two files file1 and file2 and returns true if their content is exactly equal, or false otherwise. No vibes-based comparison here, it's byte-for-byte.

The external cmp(1) program is used for the comparison. It's giving "delegating to the professionals" and honestly? respect. ๐Ÿ‘‘

  • $existsflag = $g->exists ($path); โ€” returns "true" if and only if there is a file, directory (or anything) with the given path name. Anything. A file, a dir, a weird little guy โ€” if the name's there, it's true. โœจ

See also $g->is_file, $g->is_dir, $g->stat.

  • $g->extlinux ($directory); โ€” installs the SYSLINUX bootloader on the device mounted at directory. Unlike $g->syslinux which requires a FAT filesystem, this can be used on an ext2/3/4 or btrfs filesystem. Glow-up unlocked. ๐Ÿ”ฅ

The directory parameter can be either a mountpoint, or a directory within the mountpoint.

You also have to mark the partition as "active" ($g->part_set_bootable) and a Master Boot Record must be installed (eg. using $g->pwrite_device) on the first sector of the whole disk. The SYSLINUX package comes with some suitable Master Boot Records. See the extlinux(1) man page for further information.

Additional configuration can be supplied to SYSLINUX by placing a file called extlinux.conf on the filesystem under directory. For further information about the contents of this file, see extlinux(1).

See also $g->syslinux.

This function depends on the feature "extlinux". See also $g->feature-available.
  • $g->f2fs_expand ($device); โ€” this expands a f2fs filesystem to match the size of the underlying device. It's giving "make it fit", main character energy for your partition. ๐ŸŒธ
This function depends on the feature "f2fs". See also $g->feature-available.
  • $g->fallocate ($path, $len); โ€” this command preallocates a file (containing zero bytes) named path of size len bytes. If the file exists already, it is overwritten. No cap, it just takes over. ๐ŸŽ€

Do not confuse this with the guestfish-specific alloc command which allocates a file in the host and attaches it as a device. Two totally different girls, ok?

This function is deprecated. In new code, use the fallocate64 call instead.

Deprecated functions will not be removed from the API, but the fact that they are deprecated indicates that there are problems with correct use of these functions.

  • $g->fallocate64 ($path, $len); โ€” this command preallocates a file (containing zero bytes) named path of size len bytes. If the file exists already, it is overwritten. Same energy, but bigger and better. ๐Ÿ’œ

Note that this call allocates disk blocks for the file. To create a sparse file use $g->truncate_size instead. Sparse is a whole different aesthetic, don't mix them up. ๐Ÿ™ˆ

The deprecated call $g->fallocate does the same, but owing to an oversight it only allowed 30 bit lengths to be specified, effectively limiting the maximum size of files created through that call to 1GB. Literally an oopsie that shipped. ๐Ÿ˜ญ

Do not confuse this with the guestfish-specific alloc and sparse commands which create a file in the host and attach it as a device.

  • $isavailable = $g->feature_available (\@groups); โ€” this is the same as $g->available, but unlike that call it returns a simple true/false boolean result, instead of throwing an exception if a feature is not found. So chill. No drama, just true or false. ๐ŸŒˆ

For other documentation see $g->available.

  • @lines = $g->fgrep ($pattern, $path); โ€” this calls the external fgrep(1) program and returns the matching lines.

Because of the message protocol, there is a transfer limit of somewhere between 2MB and 4MB. See "PROTOCOL LIMITS" in guestfs(3). So like, don't dump your entire 4K remux through here, bestie. ๐Ÿ’€

This function is deprecated. In new code, use the grep call instead.

Deprecated functions will not be removed from the API, but the fact that they are deprecated indicates that there are problems with correct use of these functions.

  • @lines = $g->fgrepi ($pattern, $path); โ€” this calls the external fgrep -i program and returns the matching lines. Yes, the -i is right there in the name, case-insensitive icon. โœจ

Because of the message protocol, there is a transfer limit of somewhere between 2MB and 4MB. See "PROTOCOL LIMITS" in guestfs(3).

This function is deprecated. In new code, use the grep call instead.

Deprecated functions will not be removed from the API, but the fact that they are deprecated indicates that there are problems with correct use of these functions.

  • $description = $g->file ($path); โ€” this call uses the standard file(1) command to determine the type or contents of the file. It's the "so what even are you" of syscalls. ๐Ÿ”

This call will also transparently look inside various types of compressed file. Nosy in the best way. ๐Ÿงš

The filename is not prepended to the output (like the file command -b option). So no extra clutter, we keep it clean.

The output depends on the output of the underlying file(1) command and it can change in future in ways beyond our control. In other words, the output is not guaranteed by the ABI. Read that again โ€” not guaranteed. โš ๏ธ

See also: file(1), $g->vfs_type, $g->lstat, $g->is_file, $g->is_blockdev (etc), $g->is_zero.

  • $arch = $g->file_architecture ($filename); โ€” this detects the architecture of the binary filename, and returns it if known. iykyk. ๐Ÿฆ‹

Currently defined architectures are:

  • "aarch64" โ€” 64 bit ARM.
  • "arm" โ€” 32 bit ARM.
  • "i386" โ€” This string is returned for all 32 bit i386, i486, i586, i686 binaries irrespective of the precise processor requirements of the binary. One label to rule them all.
  • "ia64" โ€” Intel Itanium.
  • "ppc" โ€” 32 bit Power PC.
  • "ppc64" โ€” 64 bit Power PC (big endian).
  • "ppc64le" โ€” 64 bit Power PC (little endian).
  • "loongarch64" โ€” 64 bit LoongArch64 (little endian).
  • "riscv32", "riscv64", "riscv128" โ€” RISC-V 32-, 64- or 128-bit variants.
  • "s390" โ€” 31 bit IBM S/390.
  • "s390x" โ€” 64 bit IBM S/390.
  • "sparc" โ€” 32 bit SPARC.
  • "sparc64" โ€” 64 bit SPARC V9 and above.
  • "x86_64" โ€” 64 bit x86-64.

Libguestfs may return other architecture strings in future. Surprise guests are always possible. ๐ŸŽ

The function works on at least the following types of files:

  • many types of Un*x and Linux binary
  • many types of Un*x and Linux shared library
  • Windows Win32 and Win64 binaries
  • Windows Win32 and Win64 DLLs
    • Win32 binaries and DLLs return "i386".
    • Win64 binaries and DLLs return "x86_64".
  • Linux kernel modules
  • Linux new-style initrd images
  • some non-x86 Linux vmlinuz kernels

What it can't do currently:

  • static libraries (libfoo.a)
  • Linux old-style initrd as compressed ext2 filesystem (RHEL 3)
  • x86 Linux vmlinuz kernels
    • x86 vmlinuz images (bzImage format) consist of a mix of 16-, 32- and compressed code, and are horribly hard to unpack. Literally a cursed sandwich. ๐Ÿ’€ If you want to find the architecture of a kernel, use the architecture of the associated initrd or kernel module(s) instead.
  • $size = $g->filesize ($file); โ€” this command returns the size of file in bytes. Just the number, no garnish.

To get other stats about a file, use $g->stat, $g->lstat, $g->is_dir, $g->is_file etc. To get the size of block devices, use $g->blockdev_getsize64. Different tool for a different girl. ๐Ÿ’…

  • $fsavail = $g->filesystem_available ($filesystem); โ€” check whether libguestfs supports the named filesystem. The argument filesystem is a filesystem name, such as "ext3".

You must call $g->launch before using this command. Non-negotiable, launch first. ๐Ÿš€

This is mainly useful as a negative test. If this returns true, it doesn't mean that a particular filesystem can be created or mounted, since filesystems can fail for other reasons such as it being a later version of the filesystem, or having incompatible features, or lacking the right mkfs.<fs> tool. So true is like "the vibes are there", not a guarantee. ๐ŸŒธ

See also $g->available, $g->feature_available, "AVAILABILITY" in guestfs(3).

  • @dirents = $g->filesystem_walk ($device); โ€” walk through the internal structures of a disk partition (eg. /dev/sda1) in order to return a list of all the files and directories stored within. Forensic queen behavior. ๐Ÿ‘‘

It is not necessary to mount the disk partition to run this command. We're going in through the side door.

All entries in the filesystem are returned. This function can list deleted or unaccessible files. The entries are not sorted. So no, they're not alphabetical, deal with it. ๐Ÿ˜ญ

The tsk_dirent structure contains the following fields.

  • tsk_inode โ€” Filesystem reference number of the node. It might be 0 if the node has been deleted.
  • tsk_type โ€” Basic file type information. See below for a detailed list of values.
  • tsk_size โ€” File size in bytes. It might be -1 if the node has been deleted.
  • tsk_name โ€” The file path relative to its directory.
  • tsk_flags โ€” Bitfield containing extra information regarding the entry. It contains the logical OR of the following values:
    • 0x0001 โ€” If set to 1, the file is allocated and visible within the filesystem. Otherwise, the file has been deleted. Under certain circumstances, the function download_inode can be used to recover deleted files. Resurrection era. โœจ
    • 0x0002 โ€” Filesystem such as NTFS and Ext2 or greater, separate the file name from the metadata structure. The bit is set to 1 when the file name is in an unallocated state and the metadata structure is in an allocated one. This generally implies the metadata has been reallocated to a new file. Therefore, information such as file type, file size, timestamps, number of links and symlink target might not correspond with the ones of the original deleted entry. Basically someone moved into the apartment and the mail is still addressed to the old tenant. ๐Ÿ™ˆ
    • 0x0004 โ€” The bit is set to 1 when the file is compressed using filesystem native compression support (NTFS). The API is not able to detect application level compression. Only the filesystem's own compression, not your zip files, ok?
  • tsk_atime_sec, tsk_atime_nsec, tsk_mtime_sec, tsk_mtime_nsec, tsk_ctime_sec, tsk_ctime_nsec, tsk_crtime_sec, tsk_crtime_nsec โ€” Respectively, access, modification, last status change and creation time in Unix format in seconds and nanoseconds. All the timestamps, every single one, accounted for. โฐ
  • tsk_nlink โ€” Number of file names pointing to this entry.
  • tsk_link โ€” If the entry is a symbolic link, this field will contain the path to the target file. Follow the little arrow. ๐Ÿฆ‹

The tsk_type field is gonna hold exactly one of these iconic little letters:

  • 'b' โ€” block special
  • 'c' โ€” char special
  • 'd' โ€” directory
  • 'f' โ€” FIFO (named pipe)
  • 'l' โ€” symbolic link
  • 'r' โ€” regular file
  • 's' โ€” socket
  • 'h' โ€” shadow inode (Solaris)
  • 'w' โ€” whiteout inode (BSD)
  • 'u' โ€” unknown file type

This function depends on the feature "libtsk". Peep "$g->feature-available" too, bestie.


$g->fill ($c, $len, $path);

Okay so this one just makes a new file called path, and its starting content is len octets of c โ€” and c has to be a number in the range [0..255], no exceptions ๐Ÿ’….

Hot tip: if you literally just wanna fill a file with zero bytes (sparse style), "$g->truncate_size" is so much more efficient, fr fr. And if you want a repeating byte pattern instead, that's "$g->fill_pattern". Use the right tool, babe ๐Ÿซถ

$g->fill_dir ($dir, $nr);

This one is a testing-filesystem queen ๐Ÿ‘‘ โ€” it creates nr empty files inside the directory dir, named 00000000 through nr-1 (and yeah, each name is 8 digits long, zero-padded, because consistency is everything โœจ).

$g->fill_pattern ($pattern, $len, $path);

Same energy as "$g->fill" except the new file (length len) contains the repeating pattern of bytes in pattern. And if the pattern doesn't divide evenly? It just gets truncated so the file is exactly len bytes. Math said what it said ๐Ÿ’€

@names = $g->find ($directory);

This lists out every file and directory, recursively, starting at directory. Basically the shell command find directory -print, except some post-processing happens on the output (explained below, don't worry).

It returns a list of strings with no prefix on them. So if your directory structure was giving:

/tmp/a
/tmp/b
/tmp/c/d

then the returned list from "$g->find" /tmp would be 4 elements:

a
b
c
c/d

And if directory isn't actually a directory? Error. Sorry babe ๐Ÿ˜ญ

Oh and โ€” the returned list is sorted. Slay โœจ

$g->find0 ($directory, $files);

Recursively lists all files and directories starting at directory, but drops the resulting list into the external file called files.

It does the same thing as "$g->find" with these three exceptions, and I'm listing them because they matter:

  • The resulting list is written to an external file.
  • Items (filenames) in the result are separated by "\0" characters. Peep find(1) option -print0 iykyk.
  • The result list is not sorted. (Chaos. Love that for us.)

@dirents = $g->find_inode ($device, $inode);

Searches all the entries associated with the given inode, and for each entry you get a "tsk_dirent" structure back.

Want the full lore on "tsk_dirent" structures? It's in "filesystem_walk", go look ๐Ÿ‘€

This function depends on the feature "libtsk". Also see "$g->feature-available".

$device = $g->findfs_label ($label);

Searches your filesystems and hands you back the one with the given label. If no such filesystem can be found, you get an error. No label, no love ๐Ÿ™ˆ

Wanna find the label of a filesystem? "$g->vfs_label". Easy.

$device = $g->findfs_partlabel ($label);

Searches the partitions and returns the one with the given label. No such partition = error.

To find the label of a partition, use "$g->blkid" ("PART_ENTRY_NAME"). ๐ŸŽ€

$device = $g->findfs_partuuid ($uuid);

Searches the partitions and returns the one with the given partition UUID. No such partition? Error, bestie.

To find the UUID of a partition, use "$g->blkid" ("PART_ENTRY_UUID"). ๐Ÿฆ‹

$device = $g->findfs_uuid ($uuid);

Searches the filesystems and returns the one with the given UUID. An error is returned if no such filesystem can be found โ€” that's just how it is.

To find the UUID of a filesystem, use "$g->vfs_uuid". โญ

$status = $g->fsck ($fstype, $device);

Runs the filesystem checker (fsck) on device, which should have filesystem type fstype.

The returned integer is the status โ€” see fsck(8) for the list of status codes from "fsck".

Notes, and these are important so don't skip ๐Ÿซถ:

  • Multiple status codes can be summed together.
  • A non-zero return code can mean "success" โ€” for example if errors have been corrected on the filesystem. Like, don't panic, it's giving fixed ๐Ÿ’…
  • Checking or repairing NTFS volumes is not supported (by linux-ntfs). Yeah. Not happening.

This command is entirely equivalent to running fsck -a -t fstype device.

$g->fstrim ($mountpoint [, offset => $offset] [, length => $length] [, minimumfreeextent => $minimumfreeextent]);

Trims the free space in the filesystem mounted on mountpoint. The filesystem must be mounted read-write, no cap.

The filesystem contents aren't affected โ€” it's just that any free space gets "trimmed", meaning it's given back to the host device. Which makes disk images more sparse, lets unused space in qcow2 files be reused, etc. Basically a glow-up for your storage โœจ

Real talk: this operation requires support in libguestfs, the mounted filesystem, the host filesystem, qemu and the host kernel. If that support isn't present it may give an error or even appear to run but do nothing. Yeah. Rude.

In the case where the kernel vfs driver doesn't support trimming, this call will fail with errno set to "ENOTSUP". Currently that happens when you try to trim FAT filesystems. ๐Ÿ’€

Also peep "$g->zero_free_space" โ€” that's a slightly different operation that turns free space in the filesystem into zeroes. And it's totally valid to call "$g->fstrim" either instead of, or after calling "$g->zero_free_space". Do both, honestly.

This function depends on the feature "fstrim". See also "$g->feature-available".

$append = $g->get_append ();

Returns the additional kernel options that get added to the libguestfs appliance kernel command line.

If it's "NULL", then no options are added. Simple as that ๐ŸŽ€

$backend = $g->get_attach_method ();

Returns the current backend.

See "$g->set_backend" and "BACKEND" in guestfs(3).

Heads up: this function is deprecated. In new code, use the "get_backend" call instead. Deprecated functions will not be removed from the API, but the fact that they're deprecated indicates there are problems with correct use of these functions. So like... use the new one, bestie ๐Ÿ’…

$autosync = $g->get_autosync ();

Gets the autosync flag. That's it, that's the whole vibe ๐ŸŒธ

$backend = $g->get_backend ();

Returns the current backend.

Fun fact: this handle property used to be called the "attach method" โ€” so if you see that name floating around, that's why.

See "$g->set_backend" and "BACKEND" in guestfs(3). โœจ

$val = $g->get_backend_setting ($name);

Finds a backend setting string that's either name or begins with name=. If it's just name, you get the string "1" back. If it's name=, you get the part after the equals sign (which โ€” plot twist โ€” may be an empty string).

If no such setting is found, this function throws an error. And the errno (see "$g->last_errno") will be "ESRCH" in that case. Noted ๐Ÿ“

See "BACKEND" in guestfs(3), and "BACKEND SETTINGS" in guestfs(3).

@settings = $g->get_backend_settings ();

Returns the current backend settings โ€” all of them, as a full list.

Want just one single backend setting instead of the whole squad? Use "$g->get_backend_setting". ๐Ÿซถ

See "BACKEND" in guestfs(3), and "BACKEND SETTINGS" in guestfs(3).

$cachedir = $g->get_cachedir ();

Gets the directory the handle uses to store the appliance cache. Iconic little home directory energy ๐Ÿ 

$direct = $g->get_direct ();

Returns the direct appliance mode flag.

Heads up: this function is deprecated. In new code, use the "internal_get_console_socket" call instead. Deprecated functions will not be removed from the API, but the fact that they're deprecated indicates there are problems with correct use of these functions. You've been warned ๐Ÿ’€

$attrs = $g->get_e2attrs ($file);

Returns the file attributes associated with file.

So these attributes are a set of bits tied to each inode, and they affect how the file behaves. They come back as a string of letters (described below, keep reading ๐Ÿ‘€). The string may be empty, which means no file attributes are set for this file. Empty is a valid mood.

Big caveat: these attributes are only present when the file lives on an ext2/3/4 filesystem. Using this call on other filesystem types will result in an error. No exceptions.

The characters (file attributes) in the returned string are currently:

  • 'A' โ€” when the file is accessed, its atime is not modified.
  • 'a' โ€” the file is append-only.
  • 'c' โ€” the file is compressed on-disk.
  • 'D' โ€” (Directories only.) Changes to this directory are written synchronously to disk.
  • 'd' โ€” the file is not a candidate for backup (see dump(8)).
  • 'E' โ€” the file has compression errors.
  • 'e' โ€” the file is using extents.
  • 'h' โ€” the file is storing its blocks in units of the filesystem blocksize instead of sectors.
  • 'I' โ€” (Directories only.) The directory is using hashed trees.
  • 'i' โ€” the file is immutable. It cannot be modified, deleted or renamed. No link can be created to this file.
  • 'j' โ€” the file is data-journaled.
  • 's' โ€” when the file is deleted, all its blocks will be zeroed.
  • 'S' โ€” changes to this file are written synchronously to disk.
  • 'T' โ€” (Directories only.) This is a hint to the block allocator that subdirectories contained in this directory should be spread across blocks. If not present, the block allocator will try to group subdirectories together.
  • 't' โ€” for a file, this disables tail-merging. (Not used by upstream implementations of ext2.)
  • 'u' โ€” when the file is deleted, its blocks will be saved, allowing the file to be undeleted.
  • 'X' โ€” the raw contents of the compressed file may be accessed.
  • 'Z' โ€” the compressed file is dirty.

More file attributes may be added to this list later โ€” it's a growing collection, periodt. Not all file attributes may be set for all kinds of files. For the detailed tea, consult the chattr(1) man page ๐Ÿ“–

See also "$g->set_e2attrs".

PSA: don't confuse these attributes with extended attributes (see "$g->getxattr"). Different thing entirely, bestie. Don't do it.

$generation = $g->get_e2generation ($file);

Returns the ext2 file generation of a file. The generation (which used to be called the "version") is a number associated with an inode. It's most commonly used by NFS servers, iykyk.

Same caveat as before: the generation is only present when the file lives on an ext2/3/4 filesystem. Using this call on other filesystem types will result in an error.

See "$g->set_e2generation". ๐Ÿฆ‹

$label = $g->get_e2label ($device);

okay so this one hands you the ext2/3/4 filesystem label of the filesystem sitting on device. cute, simple, very demure. ๐Ÿ’–

deprecated alert ๐Ÿšจ this function is deprecated โ€” in new code, use the vfs_label call instead. deprecated functions will not be removed from the API, but the fact that they are deprecated indicates that there are problems with correct use of these functions.

$uuid = $g->get_e2uuid ($device);

same vibe as above but it returns the ext2/3/4 filesystem UUID of the filesystem on device. โœจ

deprecated alert ๐Ÿšจ this function is deprecated โ€” in new code, use the vfs_uuid call instead. deprecated functions will not be removed from the API, but the fact that they are deprecated indicates that there are problems with correct use of these functions.

$hv = $g->get_hv ();

returns the current hypervisor binary. if it wasnโ€™t set already, then this will return the default qemu binary name. ๐Ÿซถ

for some backends this may return an error if called before launch, since it may not be possible to get the default hypervisor before the appliance is launched. heads up, bestie.

$identifier = $g->get_identifier ();

gets the handle identifier. see $g->set_identifier. ๐ŸŽ€

$challenge = $g->get_libvirt_requested_credential_challenge ($index);

gets the challenge (provided by libvirt) for the indexโ€™th requested credential. if libvirt did not provide a challenge, this returns the empty string "". ๐ŸŒธ

see LIBVIRT AUTHENTICATION in guestfs(3) for documentation and example code.

$defresult = $g->get_libvirt_requested_credential_defresult ($index);

gets the default result (provided by libvirt) for the indexโ€™th requested credential. if libvirt did not provide a default result, this returns the empty string "". ๐Ÿ’…

see LIBVIRT AUTHENTICATION in guestfs(3) for documentation and example code.

$prompt = $g->get_libvirt_requested_credential_prompt ($index);

gets the prompt (provided by libvirt) for the indexโ€™th requested credential. if libvirt did not provide a prompt, this returns the empty string "". ๐Ÿ’–

see LIBVIRT AUTHENTICATION in guestfs(3) for documentation and example code.

@creds = $g->get_libvirt_requested_credentials ();

this should only be called during the event callback for events of type GUESTFS_EVENT_LIBVIRT_AUTH. ๐Ÿšจ

returns the list of credentials requested by libvirt. possible values are a subset of the strings provided when you called $g->set_libvirt_supported_credentials.

see LIBVIRT AUTHENTICATION in guestfs(3) for documentation and example code.

$memsize = $g->get_memsize ();

gets the memory size in megabytes allocated to the hypervisor. ๐Ÿงš

if $g->set_memsize was not called on this handle, and if LIBGUESTFS_MEMSIZE was not set, then this returns the compiled-in default value for memsize.

for more information on the architecture of libguestfs, see guestfs(3).

$network = $g->get_network ();

returns the enable network flag. โญ

$path = $g->get_path ();

returns the current search path. ๐Ÿฆ‹

this is always non-NULL. if it wasnโ€™t set already, then this will return the default path.

$pgroup = $g->get_pgroup ();

returns the process group flag. ๐ŸŒˆ

$pid = $g->get_pid ();

returns the process ID of the hypervisor. if there is no hypervisor running, then this will return an error. ๐Ÿ˜ญ

this is an internal call used for debugging and testing.

$program = $g->get_program ();

gets the program name. see $g->set_program. ๐Ÿ‘‘

$hv = $g->get_qemu ();

returns the current hypervisor binary (usually qemu). ๐Ÿ’ป

this is always non-NULL. if it wasnโ€™t set already, then this will return the default qemu binary name.

deprecated alert ๐Ÿšจ this function is deprecated โ€” in new code, use the get_hv call instead. deprecated functions will not be removed from the API, but the fact that they are deprecated indicates that there are problems with correct use of these functions.

$recoveryproc = $g->get_recovery_proc ();

returns the recovery process enabled flag. ๐Ÿฉน

$selinux = $g->get_selinux ();

returns the current setting of the selinux flag which is passed to the appliance at boot time. see $g->set_selinux. ๐Ÿ”

for more information on the architecture of libguestfs, see guestfs(3).

deprecated alert ๐Ÿšจ this function is deprecated โ€” in new code, use the setfiles call instead. deprecated functions will not be removed from the API, but the fact that they are deprecated indicates that there are problems with correct use of these functions.

$smp = $g->get_smp ();

returns the number of virtual CPUs assigned to the appliance. โšก

$sockdir = $g->get_sockdir ();

gets the directory used by the handle to store temporary socket and PID files. ๐ŸŽ€

this is different from $g->get_tmpdir, as we need shorter paths for sockets (due to the limited buffers of filenames for UNIX sockets), and $g->get_tmpdir may be too long for them. furthermore, sockets and PID files must be accessible to such background services started by libguestfs that may not have permission to access the temporary directory returned by $g->get_tmpdir.

the environment variable XDG_RUNTIME_DIR controls the default value: if XDG_RUNTIME_DIR is set, then that is the default. else /tmp is the default. ๐Ÿ’–

$state = $g->get_state ();

returns the current state as an opaque integer. this is only useful for printing debug and internal error messages. ๐Ÿซ 

for more information on states, see guestfs(3).

$tmpdir = $g->get_tmpdir ();

gets the directory used by the handle to store temporary files. ๐Ÿ—‚๏ธ

$trace = $g->get_trace ();

returns the command trace flag. ๐Ÿ‘€

$mask = $g->get_umask ();

returns the current umask. by default the umask is 022 unless it has been set by calling $g->umask. ๐ŸŒธ

$verbose = $g->get_verbose ();

returns the verbose messages flag. ๐Ÿ—ฃ๏ธ

$context = $g->getcon ();

gets the SELinux security context of the daemon. ๐Ÿ”

see the documentation about SELINUX in guestfs(3), and $g->setcon

this function depends on the feature "selinux". see also $g->feature-available.

deprecated alert ๐Ÿšจ this function is deprecated โ€” in new code, use the setfiles call instead. deprecated functions will not be removed from the API, but the fact that they are deprecated indicates that there are problems with correct use of these functions.

$xattr = $g->getxattr ($path, $name);

gets a single extended attribute from file path named name. this call follows symlinks. if you want to lookup an extended attribute for the symlink itself, use $g->lgetxattr. ๐Ÿฆ‹

normally it is better to get all extended attributes from a file in one go by calling $g->getxattrs. however some Linux filesystem implementations are buggy and do not provide a way to list out attributes. for these filesystems (notably ntfs-3g) you have to know the names of the extended attributes you want in advance and call this function. ๐Ÿ˜ญ

extended attribute values are blobs of binary data. if there is no extended attribute named name, this returns an error.

see also: $g->getxattrs, $g->lgetxattr, attr(5).

this function depends on the feature "linuxxattrs". see also $g->feature-available.

@xattrs = $g->getxattrs ($path);

this call lists the extended attributes of the file or directory path. โœจ

at the system call level, this is a combination of the listxattr(2) and getxattr(2) calls.

see also: $g->lgetxattrs, attr(5).

this function depends on the feature "linuxxattrs". see also $g->feature-available.

@paths = $g->glob_expand ($pattern [, directoryslash => $directoryslash]);

this command searches for all the pathnames matching pattern according to the wildcard expansion rules used by the shell. ๐Ÿš

if no paths match, then this returns an empty list (note: not an error). no drama, just empty.

it is just a wrapper around the C glob(3) function with flags "GLOB_MARK|GLOB_BRACE". see that manual page for more details.

directoryslash controls whether use the GLOB_MARK flag for glob(3), and it defaults to true. it can be explicitly set as off to return no trailing slashes in filenames of directories. ๐Ÿ’…

notice that there is no equivalent command for expanding a device name (eg. /dev/sd*). use $g->list_devices, $g->list_partitions etc functions instead.

@paths = $g->glob_expand_opts ($pattern [, directoryslash => $directoryslash]);

this is an alias of glob_expand. ๐ŸŽ€

@lines = $g->grep ($regex, $path [, extended => $extended] [, fixed => $fixed] [, insensitive => $insensitive] [, compressed => $compressed]);

this calls the external grep(1) program and returns the matching lines. ๐Ÿ”

the optional flags are:

  • extended โ€” use extended regular expressions. this is the same as using the -E flag.
  • fixed โ€” match fixed (donโ€™t use regular expressions). this is the same as using the -F flag.
  • insensitive โ€” match case-insensitive. this is the same as using the -i flag.
  • compressed โ€” use zgrep(1) instead of grep(1). this allows the input to be compress- or gzip-compressed.

because of the message protocol, there is a transfer limit of somewhere between 2MB and 4MB. see PROTOCOL LIMITS in guestfs(3). ๐Ÿ˜ญ

@lines = $g->grep_opts ($regex, $path [, extended => $extended] [, fixed => $fixed] [, insensitive => $insensitive] [, compressed => $compressed]);

this is an alias of grep. โœจ

@lines = $g->grepi ($regex, $path);

this calls the external "grep -i" program and returns the matching lines. ๐Ÿ”

because of the message protocol, there is a transfer limit of somewhere between 2MB and 4MB. see PROTOCOL LIMITS in guestfs(3).

deprecated alert ๐Ÿšจ this function is deprecated โ€” in new code, use the grep call instead. deprecated functions will not be removed from the API, but the fact that they are deprecated indicates that there are problems with correct use of these functions.

$g->grub_install ($root, $device);

this command installs GRUB 1 (the Grand Unified Bootloader) on device, with the root directory being root. ๐Ÿ‘‘

notes:

  • ๐Ÿ’€ Lowkey there's no way in the API to install grub2, which is what most modern Linux guests are running. You can run the grub2 command from inside the guest, but pls go read the caveats in "RUNNING COMMANDS" in guestfs(3) first, bestie.
  • ๐Ÿ˜ฌ This uses grub-install(8) from the host. And grub is famously not compatible with itself (it's giving "who is she"), so this only works in rather narrow circumstances. Careful testing with each guest version is advisable โ€” like, actually do it, don't skip it.
  • ๐Ÿซ  If grub-install reports the error "No suitable drive was found in the generated device map." it may be that you need to create a /boot/grub/device.map file first, containing the mapping between grub device names and Linux device names. Usually it's enough to make a file containing:
(hd0) /dev/vda

replacing /dev/vda with the name of the installation device. Slay.

This function depends on the feature "grub". See also "$g->feature-available".


๐ŸŒธ @lines = $g->head ($path);

This command returns up to the first 10 lines of a file as a list of strings. Little peek, iykyk.

Because of the message protocol, there is a transfer limit of somewhere between 2MB and 4MB. See "PROTOCOL LIMITS" in guestfs(3). (Yes, the limit again. It haunts us. ๐Ÿ’€)

โœจ @lines = $g->head_n ($nrlines, $path);

Okay so depending on what nrlines is, the vibe changes:

  • If the parameter nrlines is a positive number, this returns the first nrlines lines of the file path.
  • If the parameter nrlines is a negative number, this returns lines from the file path, excluding the last nrlines lines.
  • If the parameter nrlines is zero, this returns an empty list. Nothing. Nada. Empty list era. ๐ŸŽ€

Because of the message protocol, there is a transfer limit of somewhere between 2MB and 4MB. See "PROTOCOL LIMITS" in guestfs(3).

๐Ÿ”ฅ $dump = $g->hexdump ($path);

This runs hexdump -C on the given path. The result is the human-readable, canonical hex dump of the file. It's giving very demure, very coder. ๐Ÿ‘‘

Because of the message protocol, there is a transfer limit of somewhere between 2MB and 4MB. See "PROTOCOL LIMITS" in guestfs(3).

๐Ÿงš $g->hivex_close ();

Close the current hivex handle. Bye bestie ๐Ÿซถ

This is a wrapper around the hivex(3) call of the same name.

This function depends on the feature "hivex". See also "$g->feature-available".

๐Ÿ’พ $g->hivex_commit ($filename);

Commit (write) changes to the hive. It's giving save file energy.

If the optional filename parameter is null, then the changes are written back to the same hive that was opened. If this is not null, then they are written to the alternate filename given and the original hive is left untouched. (So polite. So considerate. ๐Ÿ’…)

This is a wrapper around the hivex(3) call of the same name.

This function depends on the feature "hivex". See also "$g->feature-available".

๐Ÿฆ‹ $nodeh = $g->hivex_node_add_child ($parent, $name);

Add a child node to parent named name. Making new friends fr fr.

This is a wrapper around the hivex(3) call of the same name.

This function depends on the feature "hivex". See also "$g->feature-available".

๐ŸŒˆ @nodehs = $g->hivex_node_children ($nodeh);

Return the list of nodes which are subkeys of nodeh. It's the group chat of nodes.

This is a wrapper around the hivex(3) call of the same name.

This function depends on the feature "hivex". See also "$g->feature-available".

๐Ÿ’€ $g->hivex_node_delete_child ($nodeh);

Delete nodeh, recursively if necessary. No survivors. Blocked, deleted, gone.

This is a wrapper around the hivex(3) call of the same name.

This function depends on the feature "hivex". See also "$g->feature-available".

๐Ÿ“ $child = $g->hivex_node_get_child ($nodeh, $name);

Return the child of nodeh with the name name, if it exists. This can return 0 meaning the name was not found. (Ghosted. ๐Ÿ‘ป)

This is a wrapper around the hivex(3) call of the same name.

This function depends on the feature "hivex". See also "$g->feature-available".

๐ŸŽ€ $valueh = $g->hivex_node_get_value ($nodeh, $key);

Return the value attached to nodeh which has the name key, if it exists. This can return 0 meaning the key was not found.

This is a wrapper around the hivex(3) call of the same name.

This function depends on the feature "hivex". See also "$g->feature-available".

โญ $name = $g->hivex_node_name ($nodeh);

Return the name of nodeh. Introducing... her. ๐Ÿ’…

This is a wrapper around the hivex(3) call of the same name.

This function depends on the feature "hivex". See also "$g->feature-available".

๐ŸŒธ $parent = $g->hivex_node_parent ($nodeh);

Return the parent node of nodeh. Family tree reveal โœจ

This is a wrapper around the hivex(3) call of the same name.

This function depends on the feature "hivex". See also "$g->feature-available".

๐Ÿงš $g->hivex_node_set_value ($nodeh, $key, $t, $val);

Set or replace a single value under the node nodeh. The key is the name, t is the type, and val is the data. Set it, don't regret it.

This is a wrapper around the hivex(3) call of the same name.

This function depends on the feature "hivex". See also "$g->feature-available".

๐Ÿฆ‹ @valuehs = $g->hivex_node_values ($nodeh);

Return the array of (key, datatype, data) tuples attached to nodeh. Tuples! Very structured, very organized, we love to see it. ๐Ÿ‘‘

This is a wrapper around the hivex(3) call of the same name.

This function depends on the feature "hivex". See also "$g->feature-available".

๐Ÿ’– $g->hivex_open ($filename [, verbose => $verbose] [, debug => $debug] [, write => $write] [, unsafe => $unsafe]);

Open the Windows Registry hive file named filename. If there was any previous hivex handle associated with this guestfs session, then it is closed. Out with the old, in with the new, no cap.

This is a wrapper around the hivex(3) call of the same name.

This function depends on the feature "hivex". See also "$g->feature-available".

๐ŸŒŸ $nodeh = $g->hivex_root ();

Return the root node of the hive. The main character of the whole tree. ๐ŸŒณ

This is a wrapper around the hivex(3) call of the same name.

This function depends on the feature "hivex". See also "$g->feature-available".

๐Ÿ”‘ $key = $g->hivex_value_key ($valueh);

Return the key (name) field of a (key, datatype, data) tuple. Just the name part, bestie.

This is a wrapper around the hivex(3) call of the same name.

This function depends on the feature "hivex". See also "$g->feature-available".

๐ŸŽ€ $databuf = $g->hivex_value_string ($valueh);

This calls "$g->hivex_value_value" (which returns the data field from a hivex value tuple). It then assumes that the field is a UTF-16LE string and converts the result to UTF-8 (or if this is not possible, it returns an error).

This is useful for reading strings out of the Windows registry. However it is not foolproof because the registry is not strongly-typed and fields can contain arbitrary or unexpected data. ๐Ÿ™ˆ Like, the registry will just do whatever, honestly.

This function depends on the feature "hivex". See also "$g->feature-available".

๐Ÿท๏ธ $datatype = $g->hivex_value_type ($valueh);

Return the data type field from a (key, datatype, data) tuple. The label on the tin.

This is a wrapper around the hivex(3) call of the same name.

This function depends on the feature "hivex". See also "$g->feature-available".

๐Ÿ’œ $databuf = $g->hivex_value_utf8 ($valueh);

This calls "$g->hivex_value_value" (which returns the data field from a hivex value tuple). It then assumes that the field is a UTF-16LE string and converts the result to UTF-8 (or if this is not possible, it returns an error).

This is useful for reading strings out of the Windows registry. However it is not foolproof because the registry is not strongly-typed and fields can contain arbitrary or unexpected data. (Same warning, same energy, this is basically her twin.)

This function depends on the feature "hivex". See also "$g->feature-available".

โš ๏ธ This function is deprecated. In new code, use the "hivex_value_string" call instead.

Deprecated functions will not be removed from the API, but the fact that they are deprecated indicates that there are problems with correct use of these functions. So like... use the new one, babe. ๐Ÿ˜ญ

๐Ÿ—‚๏ธ $databuf = $g->hivex_value_value ($valueh);

Return the data field of a (key, datatype, data) tuple. Just the raw data, no thoughts, head empty.

This is a wrapper around the hivex(3) call of the same name.

See also: "$g->hivex_value_utf8".

This function depends on the feature "hivex". See also "$g->feature-available".

๐Ÿงต $content = $g->initrd_cat ($initrdpath, $filename);

This command unpacks the file filename from the initrd file called initrdpath. The filename must be given without the initial / character โ€” like, no leading slash, periodt.

For example, in guestfish you could use the following command to examine the boot script (usually called /init) contained in a Linux initrd or initramfs image:

initrd-cat /boot/initrd-<version>.img init

See also "$g->initrd_list".

Because of the message protocol, there is a transfer limit of somewhere between 2MB and 4MB. See "PROTOCOL LIMITS" in guestfs(3).

๐Ÿ“‹ @filenames = $g->initrd_list ($path);

This command lists out files contained in an initrd. A little tour ๐ŸŽ€

The files are listed without any initial / character. The files are listed in the order they appear (not necessarily alphabetical). Directory names are listed as separate items.

Old Linux kernels (2.4 and earlier) used a compressed ext2 filesystem as initrd. We only support the newer initramfs format (compressed cpio files). So if you're out here with a 2.4 kernel, bestie, I'm so sorry. ๐Ÿ’€

๐Ÿ‘€ $wd = $g->inotify_add_watch ($path, $mask);

Watch path for the events listed in mask. It's giving surveillance but make it consensual. ๐Ÿ”

Note that if path is a directory then events within that directory are watched, but this does not happen recursively (in subdirectories). So only one level deep, okay?

Note for non-C or non-Linux callers: the inotify events are defined by the Linux kernel ABI and are listed in /usr/include/sys/inotify.h.

This function depends on the feature "inotify". See also "$g->feature-available".

๐Ÿšช $g->inotify_close ();

This closes the inotify handle which was previously opened by inotify_init. It removes all watches, throws away any pending events, and deallocates all resources. Full cleanup, no leftovers, we love a thorough queen. ๐Ÿงน

This function depends on the feature "inotify". See also "$g->feature-available".

๐Ÿ—บ๏ธ @paths = $g->inotify_files ();

This function is a helpful wrapper around "$g->inotify_read" which just returns a list of pathnames of objects that were touched. The returned pathnames are sorted and deduplicated. Organized. Immaculate. ๐Ÿ’…

This function depends on the feature "inotify". See also "$g->feature-available".

๐ŸŒฑ $g->inotify_init ($maxevents);

This command creates a new inotify handle. The inotify subsystem can be used to notify events which happen to objects in the guest filesystem.

  • "maxevents" โ€” the max number of events that get queued up between calls to $g->inotify_read or $g->inotify_files. Pass it as 0 and the kernel (or whatever was set before) default kicks in. For Linux 2.6.29 the default was 16384 events. Past that limit the kernel literally just throws events away ๐Ÿ˜ญ but it does record that it did that by setting a flag IN_Q_OVERFLOW in the returned structure list (see $g->inotify_read).

Before any events are even generated, you have to add some watches to the internal watch list. See: $g->inotify_add_watch and $g->inotify_rm_watch.

Queued events should be read periodically by calling $g->inotify_read (or $g->inotify_files, which is just a helpful little wrapper around $g->inotify_read ๐Ÿซถ). If you don't read the events out often enough then you're risking the internal queue overflowing. Not the vibe.

The handle should be closed after use by calling $g->inotify_close. This also removes any watches automatically. Cleanup queen ๐Ÿ‘‘

See also inotify(7) for an overview of the inotify interface as exposed by the Linux kernel, which is roughly what we expose via libguestfs. Note that there is one global inotify handle per libguestfs instance โ€” one handle, one main character.

This function depends on the feature "inotify". See also $g->feature-available.

@events = $g->inotify_read ();

Return the complete queue of events that have happened since the previous read call. The whole queue, no crumbs.

If no events have happened, this returns an empty list.

Note: to make sure you've read all the events, you must call this function repeatedly until it returns an empty list. Why? Because the call will read events up to the maximum appliance-to-host message size and leave the remaining events sitting in the queue. So keep looping, bestie ๐Ÿ’…

This function depends on the feature "inotify". See also $g->feature-available.

$g->inotify_rm_watch ($wd);

Remove a previously defined inotify watch. See $g->inotify_add_watch. Unsubscribe era โœจ

This function depends on the feature "inotify". See also $g->feature-available.

$arch = $g->inspect_get_arch ($root);

This returns the architecture of the inspected operating system. The possible return values are listed under $g->file_architecture.

If the architecture could not be determined, then the string "unknown" is returned. Iconic "idk" behavior.

Please read "INSPECTION" in guestfs(3) for more details.

$buildid = $g->inspect_get_build_id ($root);

This returns the build ID of the system, or the string "unknown" if the system doesn't have a build ID.

For Windows, this gets the build number. Although it's returned as a string, it is (so far) always a number. See https://en.wikipedia.org/wiki/List_of_Microsoft_Windows_versions for some possible values.

For Linux, this returns the "BUILD_ID" string from /etc/os-release, although ngl this is not often used.

Please read "INSPECTION" in guestfs(3) for more details.

$distro = $g->inspect_get_distro ($root);

This returns the distro (distribution) of the inspected operating system. Currently defined distros are, and yes we're doing the whole list, hold my ๐Ÿ“:

  • "alpinelinux" โ€” Alpine Linux.
  • "altlinux" โ€” ALT Linux.
  • "archlinux" โ€” Arch Linux.
  • "buildroot" โ€” Buildroot-derived distro, but not one we specifically recognize.
  • "centos" โ€” CentOS.
  • "circle" โ€” Circle Linux.
  • "cirros" โ€” Cirros.
  • "coreos" โ€” CoreOS.
  • "debian" โ€” Debian.
  • "fedora" โ€” Fedora.
  • "freebsd" โ€” FreeBSD.
  • "freedos" โ€” FreeDOS.
  • "frugalware" โ€” Frugalware.
  • "gentoo" โ€” Gentoo.
  • "kalilinux" โ€” Kali Linux.
  • "kylin" โ€” Kylin.
  • "linuxmint" โ€” Linux Mint.
  • "mageia" โ€” Mageia.
  • "mandriva" โ€” Mandriva.
  • "meego" โ€” MeeGo.
  • "msdos" โ€” Microsoft DOS.
  • "neokylin" โ€” NeoKylin.
  • "netbsd" โ€” NetBSD.
  • "openbsd" โ€” OpenBSD.
  • "openeuler" โ€” openEuler.
  • "openmandriva" โ€” OpenMandriva Lx.
  • "opensuse" โ€” OpenSUSE.
  • "oraclelinux" โ€” Oracle Linux.
  • "pardus" โ€” Pardus.
  • "pldlinux" โ€” PLD Linux.
  • "redhat-based" โ€” Some Red Hat-derived distro.
  • "rhel" โ€” Red Hat Enterprise Linux.
  • "rocky" โ€” Rocky Linux.
  • "scientificlinux" โ€” Scientific Linux.
  • "slackware" โ€” Slackware.
  • "sles" โ€” SuSE Linux Enterprise Server or Desktop.
  • "suse-based" โ€” Some openSuSE-derived distro.
  • "ttylinux" โ€” ttylinux.
  • "ubuntu" โ€” Ubuntu.
  • "unknown" โ€” The distro could not be determined.
  • "voidlinux" โ€” Void Linux.
  • "windows" โ€” Windows does not have distributions. This string is returned if the OS type is Windows.

Future versions of libguestfs may return other strings here. The caller should be prepared to handle any string โ€” so like, don't hardcode your faves ๐Ÿ™ˆ

Please read "INSPECTION" in guestfs(3) for more details.

%drives = $g->inspect_get_drive_mappings ($root);

This call is useful for Windows, which uses a primitive system of assigning drive letters (like C:\) to partitions. This inspection API examines the Windows Registry to find out how disks/partitions are mapped to drive letters, and returns a hash table as in the example below:

 C      =>     /dev/vda2
 E      =>     /dev/vdb1
 F      =>     /dev/vdc1

Note that keys are drive letters. For Windows, the key is case insensitive and just contains the drive letter, without the customary colon separator character. No colon, periodt.

In future we may support other operating systems that also used drive letters, but the keys for those might not be case insensitive and might be longer than 1 character. For example in OS-9, hard drives were named "h0", "h1" etc.

For Windows guests, currently only hard drive mappings are returned. Removable disks (eg. DVD-ROMs) are ignored.

For guests that do not use drive mappings, or if the drive mappings could not be determined, this returns an empty hash table.

Please read "INSPECTION" in guestfs(3) for more details. See also $g->inspect_get_mountpoints, $g->inspect_get_filesystems.

@filesystems = $g->inspect_get_filesystems ($root);

This returns a list of all the filesystems that we think are associated with this operating system. This includes the root filesystem, other ordinary filesystems, and non-mounted devices like swap partitions. The whole squad ๐Ÿ’œ

In the case of a multi-boot virtual machine, it is possible for a filesystem to be shared between operating systems. Sharing is caring, I guess.

Please read "INSPECTION" in guestfs(3) for more details. See also $g->inspect_get_mountpoints.

$format = $g->inspect_get_format ($root);

Before libguestfs 1.38, there was some unreliable support for detecting installer CDs. This API would return:

  • "installed" โ€” This is an installed operating system.
  • "installer" โ€” The disk image being inspected is not an installed operating system, but a bootable install disk, live CD, or similar.
  • "unknown" โ€” The format of this disk image is not known.

In libguestfs โ‰ฅ 1.38, this only returns "installed". Use libosinfo directly to detect installer CDs.

Please read "INSPECTION" in guestfs(3) for more details.

This function is deprecated. There is no replacement. Consult the API documentation in guestfs(3) for further information.

Deprecated functions will not be removed from the API, but the fact that they are deprecated indicates that there are problems with correct use of these functions. So like, read the warning, bestie ๐Ÿ˜ญ

$hostname = $g->inspect_get_hostname ($root);

This function returns the hostname of the operating system as found by inspection of the guest's configuration files.

If the hostname could not be determined, then the string "unknown" is returned.

Please read "INSPECTION" in guestfs(3) for more details.

$icon = $g->inspect_get_icon ($root [, favicon => $favicon] [, highquality => $highquality]);

This function returns an icon corresponding to the inspected operating system. The icon is returned as a buffer containing a PNG image (re-encoded to PNG if necessary). Cute AND functional ๐Ÿ’–

If it was not possible to get an icon this function returns a zero-length (non-NULL) buffer. Callers must check for this case. Don't get caught out.

Libguestfs will start by looking for a file called /etc/favicon.png or C:\etc\favicon.png and if it has the correct format, the contents of this file will be returned. You can disable favicons by passing the optional "favicon" boolean as false (default is true).

If finding the favicon fails, then we look in other places in the guest for a suitable icon. We're resourceful like that.

If the optional "highquality" boolean is true then only high quality icons are returned, which means only icons of high resolution with an alpha channel. The default (false) is to return any icon we can, even if it is of substandard quality. No judgment ๐Ÿ’€

Notes:

  • Unlike most other inspection API calls, the guest's disks must be mounted up before you call this, since it needs to read information from the guest filesystem during the call.
  • Security: The icon data comes from the untrusted guest, and should be treated with caution. PNG files have been known to contain exploits. Ensure that libpng (or other relevant libraries) are fully up to date before trying to process or display the icon. Fr fr, do not skip this one ๐Ÿšจ
  • The PNG image returned can be any size. It might not be square. Libguestfs tries to return the largest, highest quality icon available. The application must scale the icon to the required size.
  • Extracting icons from Windows guests requires the external wrestool(1) program from the "icoutils" package, and several programs (bmptopnm(1), pnmtopng(1), pamcut(1)) from the "netpbm" package. These must be installed separately.
  • Operating system icons are usually trademarks. Seek legal advice before using trademarks in applications. ๐Ÿ‘‘ (yes, even the cute ones)

$major = $g->inspect_get_major_version ($root);

Okay so this one hands you back the major version number of whichever OS got inspected. Slay. ๐ŸŽ€

Now, Windows girlies, listen up ๐Ÿ‘€ โ€” Windows uses a consistent versioning scheme that is not reflected in the popular public names the OS itself uses. Not me explaining this: the one everyone calls "Windows 7" is actually version 6.1 (like, major = 6, minor = 1). Wild, I know. ๐Ÿ’€ If you want the real versions that map to Windows releases, go consult Wikipedia or MSDN, babes.

If the version could not be determined, then 0 is returned. Periodt.

Please read "INSPECTION" in guestfs(3) for more details.

$minor = $g->inspect_get_minor_version ($root);

Returns the minor version number of the inspected operating system. The little sister of the major version, basically. ๐Ÿฆ‹

If the version could not be determined, then 0 is returned.

Please read "INSPECTION" in guestfs(3) for more details. See also "$g->inspect_get_major_version".

%mountpoints = $g->inspect_get_mountpoints ($root);

This returns a hash of where we think the filesystems associated with this operating system should be mounted. ๐Ÿ—‚๏ธ And bestie, key word is think โ€” callers should note that this is at best an educated guess made by reading configuration files such as /etc/fstab. Lowkey not gospel.

In particular, note that this may return filesystems which are non-existent or not mountable, and callers should be prepared to handle or ignore failures if they try to mount them. So like, don't come for us if it doesn't mount, mmkay? ๐Ÿ™ˆ

Each element in the returned hashtable has a key which is the path of the mountpoint (eg. /boot) and a value which is the filesystem that would be mounted there (eg. /dev/sda1).

Non-mounted devices such as swap devices are not returned in this list. Bye. ๐Ÿ’…

For operating systems like Windows which still use drive letters, this call will only return an entry for the first drive "mounted on" /. For information about the mapping of drive letters to partitions, see "$g->inspect_get_drive_mappings".

Please read "INSPECTION" in guestfs(3) for more details. See also "$g->inspect_get_filesystems".

$id = $g->inspect_get_osinfo ($root);

This function returns a possible short ID for libosinfo corresponding to the guest. Cute little identifier vibes. โœจ

Note: the returned ID is only a guess by libguestfs, and nothing ensures that it actually exists in osinfo-db. So like, don't @ us.

If no ID could not be determined, then the string "unknown" is returned.

$packageformat = $g->inspect_get_package_format ($root);

This function and "$g->inspect_get_package_management" return the package format and package management tool used by the inspected operating system. For example for Fedora these functions would return "rpm" (package format), and "yum" or "dnf" (package management). Matching set, iconic. ๐Ÿ‘‘

This returns the string "unknown" if we could not determine the package format or if the operating system does not have a real packaging system (eg. Windows).

Possible strings include: "rpm", "deb", "ebuild", "pisi", "pacman", "pkgsrc", "apk", "xbps". Future versions of libguestfs may return other strings โ€” so stay ready, fr fr.

Please read "INSPECTION" in guestfs(3) for more details.

$packagemanagement = $g->inspect_get_package_management ($root);

"$g->inspect_get_package_format" and this function return the package format and package management tool used by the inspected operating system. For example for Fedora these functions would return "rpm" (package format), and "yum" or "dnf" (package management). Same duo, different half. ๐Ÿซถ

This returns the string "unknown" if we could not determine the package management tool or if the operating system does not have a real packaging system (eg. Windows).

Possible strings include: "yum", "dnf", "up2date", "apt" (for all Debian derivatives), "portage", "pisi", "pacman", "urpmi", "zypper", "apk", "xbps". Future versions of libguestfs may return other strings. ๐Ÿ’œ

Please read "INSPECTION" in guestfs(3) for more details.

$product = $g->inspect_get_product_name ($root);

Returns the product name of the inspected operating system. The product name is generally some freeform string which can be displayed to the user, but should not be parsed by programs. It's giving "for your eyeballs only" ๐Ÿ‘€

If the product name could not be determined, then the string "unknown" is returned.

Please read "INSPECTION" in guestfs(3) for more details.

$variant = $g->inspect_get_product_variant ($root);

Returns the product variant of the inspected operating system. The lore. ๐Ÿ“œ

For Windows guests, this returns the contents of the Registry key "HKLM\Software\Microsoft\Windows NT\CurrentVersion" "InstallationType" which is usually a string such as "Client" or "Server" (other values are possible). This can be used to distinguish consumer and enterprise versions of Windows that have the same version number โ€” for example, Windows 7 and Windows 2008 Server are both version 6.1, but the former is "Client" and the latter is "Server". Same number, different main character energy. ๐Ÿ’…

For enterprise Linux guests, in future we intend this to return the product variant such as "Desktop", "Server" and so on. But this is not implemented at present. Not yet, bestie. ๐Ÿ˜ญ

If the product variant could not be determined, then the string "unknown" is returned.

Please read "INSPECTION" in guestfs(3) for more details. See also "$g->inspect_get_product_name", "$g->inspect_get_major_version".

@roots = $g->inspect_get_roots ();

This function is a convenient way to get the list of root devices, as returned from a previous call to "$g->inspect_os", but without redoing the whole inspection process. Lazygirl win. โœจ

This returns an empty list if either no root devices were found or the caller has not called "$g->inspect_os".

Please read "INSPECTION" in guestfs(3) for more details.

$name = $g->inspect_get_type ($root);

Returns the type of the inspected operating system. Currently defined types are:

  • "linux" โ€” any Linux-based operating system. ๐Ÿง
  • "windows" โ€” any Microsoft Windows operating system. ๐ŸชŸ
  • "freebsd" โ€” FreeBSD. ๐Ÿ˜ˆ
  • "netbsd" โ€” NetBSD.
  • "openbsd" โ€” OpenBSD. ๐Ÿก
  • "hurd" โ€” GNU/Hurd.
  • "dos" โ€” MS-DOS, FreeDOS and others.
  • "minix" โ€” MINIX.
  • "unknown" โ€” the operating system type could not be determined. shrug.

Future versions of libguestfs may return other strings here. The caller should be prepared to handle any string. So like, don't hardcode, bestie. ๐Ÿซถ

Please read "INSPECTION" in guestfs(3) for more details.

$controlset = $g->inspect_get_windows_current_control_set ($root);

Returns the Windows CurrentControlSet of the inspected guest. The CurrentControlSet is a registry key name such as "ControlSet001". ๐Ÿ—๏ธ

This call assumes that the guest is Windows and that the Registry could be examined by inspection. If this is not the case then an error is returned. No guessies here.

Please read "INSPECTION" in guestfs(3) for more details.

$hasgrouppolicy = $g->inspect_get_windows_group_policy ($root);

Returns true if the Windows guest has group policy. ๐Ÿ‘‘

Now why do we care? Because group policy can interfere with device driver installation, preventing libguestfs features like driver injection from working. Rude, honestly. ๐Ÿ˜ค

Note that the presence of group policy is only an indication that there may be a problem with driver installation. As group policy is extremely complex and covers many different aspects of Windows configuration, and we make no attempt to parse it, presence of group policy should only raise a warning. So like, a vibe check, not a verdict. ๐Ÿšฉ

This call assumes that the guest is Windows and that the Registry could be examined by inspection. If this is not the case then an error is returned.

Please read "INSPECTION" in guestfs(3) for more details.

$path = $g->inspect_get_windows_software_hive ($root);

Returns the path to the hive (binary Windows Registry file) corresponding to HKLM\SOFTWARE. ๐Ÿฏ (get it, hive)

This call assumes that the guest is Windows and that the guest has a software hive file with the right name. If this is not the case then an error is returned. This call does not check that the hive is a valid Windows Registry hive โ€” so, like, no promises on the contents, mkay?

You can use "$g->hivex_open" to read or write to the hive. ๐Ÿ”ฅ

Please read "INSPECTION" in guestfs(3) for more details.

$path = $g->inspect_get_windows_system_hive ($root);

Returns the path to the hive (binary Windows Registry file) corresponding to HKLM\SYSTEM. Same hive energy, different key. ๐Ÿ

This call assumes that the guest is Windows and that the guest has a system hive file with the right name. If this is not the case then an error is returned. This call does not check that the hive is a valid Windows Registry hive.

You can use "$g->hivex_open" to read or write to the hive.

Please read "INSPECTION" in guestfs(3) for more details.

$systemroot = $g->inspect_get_windows_systemroot ($root);

Returns the Windows systemroot of the inspected guest. The systemroot is a directory path such as /WINDOWS. ๐ŸชŸโœจ

This call assumes that the guest is Windows and that the systemroot could be determined by inspection. If this is not the case then an error is returned.

Please read "INSPECTION" in guestfs(3) for more details.

$live = $g->inspect_is_live ($root);

This is deprecated and always returns "false". ๐Ÿ’€ That's it, that's the function.

Please read "INSPECTION" in guestfs(3) for more details.

This function is deprecated. There is no replacement. Consult the API documentation in guestfs(3) for further information.

Deprecated functions will not be removed from the API, but the fact that they are deprecated indicates that there are problems with correct use of these functions. So like, maybe don't, bestie. ๐Ÿ™ˆ

$multipart = $g->inspect_is_multipart ($root);

This is deprecated and always returns "false". Same story, different name. ๐Ÿ’€

Please read "INSPECTION" in guestfs(3) for more details.

This function is deprecated. There is no replacement. Consult the API documentation in guestfs(3) for further information.

Deprecated functions will not be removed from the API, but the fact that they are deprecated indicates that there are problems with correct use of these functions.

$netinst = $g->inspect_is_netinst ($root);

This is deprecated and always returns "false". Last one of the deprecated trio, we stan a consistent flop. ๐Ÿ’€๐ŸŽ€

Please read "INSPECTION" in guestfs(3) for more details.

This function is deprecated. There is no replacement. Consult the API documentation in guestfs(3) for further information.

Deprecated functions will not be removed from the API, but the fact that they are deprecated indicates that there are problems with correct use of these functions.

๐ŸŒธ inspect_list_applications

@applications = $g->inspect_list_applications ($root);

Okay bestie, this one returns the list of applications installed in the operating system. But listen, it works differently from other parts of the inspection API, and you need to know that before you start.

Note: you have to call $g->inspect_os, then $g->inspect_get_mountpoints, then mount up the disks, before calling this. Listing applications is a significantly more difficult operation which requires access to the full filesystem.

Also โ€” and this is the part that always gets people โ€” unlike the other $g->inspect_get_* calls which are just returning data cached in the libguestfs handle, this call actually reads parts of the mounted filesystems during the call. Like, it's doing the work right then and there. No cap. ๐Ÿ˜ญ

It returns an empty list if the inspection code was not able to determine the list of applications.

The application structure contains these fields:

  • app_name โ€” the name of the application. For Linux guests, this is the package name.
  • app_display_name โ€” the display name of the application, sometimes localized to the install language of the guest operating system. If unavailable this is returned as an empty string "". Callers needing to display something can use app_name instead.
  • app_epoch โ€” for package managers which use epochs, this contains the epoch of the package (an integer). If unavailable, this is returned as 0.
  • app_version โ€” the version string of the application or package. If unavailable this is returned as an empty string "".
  • app_release โ€” the release string of the application or package, for package managers that use this. If unavailable this is returned as an empty string "".
  • app_install_path โ€” the installation path of the application (on operating systems such as Windows which use installation paths). This path is in the format used by the guest operating system, it is not a libguestfs path. If unavailable this is returned as an empty string "".
  • app_trans_path โ€” the install path translated into a libguestfs path. If unavailable this is returned as an empty string "".
  • app_publisher โ€” the name of the publisher of the application, for package managers that use this. If unavailable this is returned as an empty string "".
  • app_url โ€” the URL (eg. upstream URL) of the application. If unavailable this is returned as an empty string "".
  • app_source_package โ€” for packaging systems which support this, the name of the source package. If unavailable this is returned as an empty string "".
  • app_summary โ€” a short (usually one line) description of the application or package. If unavailable this is returned as an empty string "".
  • app_description โ€” a longer description of the application or package. If unavailable this is returned as an empty string "".

Please read "INSPECTION" in guestfs(3) for more details. It's giving required reading, but it's good for you, I promise. ๐Ÿ“š

This function is deprecated. In new code, use the inspect_list_applications2 call instead.

Deprecated functions will not be removed from the API, but the fact that they are deprecated indicates that there are problems with correct use of these functions. So like, it still works, but the red flag is right there. ๐Ÿšฉ


๐Ÿฆ‹ inspect_list_applications2

@applications2 = $g->inspect_list_applications2 ($root);

Same mission, upgraded fit: return the list of applications installed in the operating system, but with the extra fields. โœจ

Note: this call works differently from other parts of the inspection API too. You have to call $g->inspect_os, then $g->inspect_get_mountpoints, then mount up the disks, before calling this. Listing applications is a significantly more difficult operation which requires access to the full filesystem.

And again, unlike the other $g->inspect_get_* calls which are just returning data cached in the libguestfs handle, this call actually reads parts of the mounted filesystems during the call. Highkey doing the most, but that's the job. ๐Ÿ’…

This returns an empty list if the inspection code was not able to determine the list of applications.

The application structure contains these fields:

  • app2_name โ€” the name of the application. For Linux guests, this is the package name.
  • app2_display_name โ€” the display name of the application, sometimes localized to the install language of the guest operating system. If unavailable this is returned as an empty string "". Callers needing to display something can use app2_name instead.
  • app2_epoch โ€” for package managers which use epochs, this contains the epoch of the package (an integer). If unavailable, this is returned as 0.
  • app2_version โ€” the version string of the application or package. If unavailable this is returned as an empty string "".
  • app2_release โ€” the release string of the application or package, for package managers that use this. If unavailable this is returned as an empty string "".
  • app2_arch โ€” the architecture string of the application or package, for package managers that use this. If unavailable this is returned as an empty string "".
  • app2_install_path โ€” the installation path of the application (on operating systems such as Windows which use installation paths). This path is in the format used by the guest operating system, it is not a libguestfs path. If unavailable this is returned as an empty string "".
  • app2_trans_path โ€” the install path translated into a libguestfs path. If unavailable this is returned as an empty string "".
  • app2_publisher โ€” the name of the publisher of the application, for package managers that use this. If unavailable this is returned as an empty string "".
  • app2_url โ€” the URL (eg. upstream URL) of the application. If unavailable this is returned as an empty string "".
  • app2_source_package โ€” for packaging systems which support this, the name of the source package. If unavailable this is returned as an empty string "".
  • app2_summary โ€” a short (usually one line) description of the application or package. If unavailable this is returned as an empty string "".
  • app2_description โ€” a longer description of the application or package. If unavailable this is returned as an empty string "".
  • app2_class โ€” classification or primary use of this application. Currently the only defined classification is "antivirus" for Windows antivirus software. If unknown this is returned as an empty string "".

Please read "INSPECTION" in guestfs(3) for more details. Bestie, it's all in there. ๐Ÿซถ


๐Ÿ‘‘ inspect_os

@roots = $g->inspect_os ();

This function uses other libguestfs functions and certain heuristics to inspect the disk(s) (usually disks belonging to a virtual machine), looking for operating systems. It's basically the detective of the libguestfs world. ๐Ÿ•ต๏ธโ€โ™€๏ธ

The list returned is empty if no operating systems were found. (Sad, but valid.)

If one operating system was found, then this returns a list with a single element, which is the name of the root filesystem of this operating system. It is also possible for this function to return a list containing more than one element, indicating a dual-boot or multi-boot virtual machine, with each element being the root filesystem of one of the operating systems. Main character energy: multiple OSes, one disk. ๐Ÿ’€

You can pass the root string(s) returned to other $g->inspect_get_* functions in order to query further information about each operating system, such as the name and version. Go off, investigative queen. ๐Ÿ”

This function uses other libguestfs features such as $g->mount_ro and $g->umount_all in order to mount and unmount filesystems and look at the contents. This should be called with no disks currently mounted. The function may also use Augeas, so any existing Augeas handle will be closed. Not me closing your Augeas handle, but also... yes, exactly that. ๐Ÿ™ˆ

This function cannot decrypt encrypted disks. The caller must do that first (supplying the necessary keys) if the disk is encrypted. Like, it's not doing the lock-picking for you; you gotta bring the keys. ๐Ÿ”‘

Please read "INSPECTION" in guestfs(3) for more details.

See also $g->list_filesystems.


๐ŸŽ€ is_blockdev

$flag = $g->is_blockdev ($path [, followsymlinks => $followsymlinks]);

This returns true if and only if there is a block device with the given path name. Simple, cute, to the point. ๐Ÿ’…

If the optional flag followsymlinks is true, then a symlink (or chain of symlinks) that ends with a block device also causes the function to return true.

This call only looks at files within the guest filesystem. Libguestfs partitions and block devices (eg. /dev/sda) cannot be used as the path parameter of this call. So don't try it, bestie, it's not that kind of function. ๐Ÿ’€

See also $g->stat.


๐ŸŒˆ is_blockdev_opts

$flag = $g->is_blockdev_opts ($path [, followsymlinks =>
$followsymlinks]);

This is an alias of is_blockdev. That's it. That's the whole vibe. โœจ


๐Ÿ“ is_busy

$busy = $g->is_busy ();

This always returns false. This function is deprecated with no replacement. Do not use this function. Like, genuinely, don't. It's giving "haunted artifact in the API." ๐Ÿ’€

For more information on states, see guestfs(3).


๐Ÿงš is_chardev

$flag = $g->is_chardev ($path [, followsymlinks => $followsymlinks]);

This returns true if and only if there is a character device with the given path name.

If the optional flag followsymlinks is true, then a symlink (or chain of symlinks) that ends with a chardev also causes the function to return true.

See also $g->stat.


๐Ÿ’œ is_chardev_opts

$flag = $g->is_chardev_opts ($path [, followsymlinks =>
$followsymlinks]);

This is an alias of is_chardev. Same energy, different name. ๐Ÿฆ‹


โญ is_config

$config = $g->is_config ();

This returns true iff this handle is being configured (in the CONFIG state). It's like a vibe check for your handle, but specifically for the config state. โœจ

For more information on states, see guestfs(3).


๐ŸŒธ is_dir

$dirflag = $g->is_dir ($path [, followsymlinks => $followsymlinks]);

This returns true if and only if there is a directory with the given path name. Note that it returns false for other objects like files. So no, your regular file is not sneaking into the directory club. ๐Ÿ™…โ€โ™€๏ธ

If the optional flag followsymlinks is true, then a symlink (or chain of symlinks) that ends with a directory also causes the function to return true.

See also $g->stat.


๐ŸŽ€ is_dir_opts

$dirflag = $g->is_dir_opts ($path [, followsymlinks =>
$followsymlinks]);

This is an alias of is_dir. Cute, consistent, slaying. ๐Ÿ’…


๐Ÿฆ‹ is_fifo

$flag = $g->is_fifo ($path [, followsymlinks => $followsymlinks]);

This returns true if and only if there is a FIFO (named pipe) with the given path name.

...if the optional flag followsymlinks is true, then a symlink (or a whole chain of symlinks) that ends in a FIFO also makes the function return true. ๐Ÿ’…

Also peep $g->stat while you're at it.

Literally just an alias of is_fifo. Same vibe, different name. ๐ŸŽ€

Returns "true" if and only if there's a regular file chilling at that path name. Note โ€” and this is important bestie โ€” it returns false for other objects like directories. We do not conflate. ๐Ÿ™…โ€โ™€๏ธ

If the optional flag followsymlinks is true, then a symlink (or chain of symlinks) that ends with a file also causes the function to return true.

See also $g->stat.

Alias of is_file. That's it. That's the whole entry. โœจ

$launching = $g->is_launching ();

Returns true iff this handle is currently launching the subprocess (aka sitting in the LAUNCHING state). Main character energy, honestly.

For more info on states, go read guestfs(3).

$lvflag = $g->is_lv ($mountable);

Tests whether mountable is a logical volume, and returns true iff yes. Simple as that. ๐Ÿ’œ

$ready = $g->is_ready ();

Returns true iff this handle is ready to accept commands (i.e. it's in the READY state). This is the "yes queen, send it" state.

For more info on states, see guestfs(3).

Returns "true" if and only if there's a Unix domain socket with the given path name. ๐Ÿงš

If the optional flag followsymlinks is true, then a symlink (or chain of symlinks) that ends with a socket also causes the function to return true.

See also $g->stat.

Alias of is_socket. Zero new info, all the same vibes. ๐Ÿฆ‹

Returns "true" if and only if there's a symbolic link with the given path name. (Yes, the link itself โ€” not whatever it points at. We're checking the vibe of the link, not the destination. ๐Ÿ’…)

See also $g->stat.

$flag = $g->is_whole_device ($device);

Returns "true" if and only if device refers to a whole block device. Like โ€” the entire thing. Not a partition, not a logical device. The whole main-character device. ๐Ÿ‘‘

$zeroflag = $g->is_zero ($path);

Returns true iff the file exists AND the file is empty or it contains all zero bytes. Nothing but zeros, bestie. Not a single crumb of actual data. ๐Ÿ“

$zeroflag = $g->is_zero_device ($device);

Returns true iff the device exists and contains all zero bytes.

Heads up: for large devices this can take a long time to run. Like, go-get-a-snack long. ๐Ÿ˜ญ

%isodata = $g->isoinfo ($isofile);

Same as $g->isoinfo_device except it works for an ISO file located inside some other mounted filesystem. Note that in the common case where you've added an ISO file as a libguestfs device, you would not call this โ€” instead you'd call $g->isoinfo_device. Don't do the extra work for no reason, babe. โœจ

%isodata = $g->isoinfo_device ($device);

device is an ISO device. This returns a struct of information read from the primary volume descriptor (basically the ISO equivalent of the superblock) of the device. ๐ŸŒˆ

Usually it's more efficient to use the isoinfo(1) command with the -d option on the host to analyze ISO files, instead of going through libguestfs.

For info on the primary volume descriptor fields, see https://wiki.osdev.org/ISO_9660#The_Primary_Volume_Descriptor

$g->journal_close ();

Closes the journal handle. Say bye. ๐Ÿ‘‹

This function depends on the feature journal. See also $g->feature-available.

@fields = $g->journal_get ();

Reads the current journal entry. Returns all the fields in the journal as a set of (attrname, attrval) pairs. The attrname is the field name (a string). ๐Ÿ“–

The attrval is the field value (a binary blob โ€” often, but not always, a string). And please, PLEASE note: attrval is a byte array, not a \0-terminated C string. Do not come for me with C-string assumptions. ๐Ÿ’€

The length of data may be truncated to the data threshold (see: $g->journal_set_data_threshold, $g->journal_get_data_threshold).

If you set the data threshold to unlimited (0) then this call can read a journal entry of any size โ€” i.e. it is not limited by the libguestfs protocol. Unlocked, no cap. ๐Ÿ”ฅ

This function depends on the feature journal. See also $g->feature-available.

$threshold = $g->journal_get_data_threshold ();

Gets the current data threshold for reading journal entries. It's a hint to the journal that it may truncate data fields to this size when reading them (note also that it may not truncate them โ€” it's a hint, not a promise, bestie). If this returns 0, then the threshold is unlimited.

See also $g->journal_set_data_threshold.

This function depends on the feature journal. See also $g->feature-available.

$usec = $g->journal_get_realtime_usec ();

Gets the realtime (wallclock) timestamp of the current journal entry. โฐ

This function depends on the feature journal. See also $g->feature-available.

$more = $g->journal_next ();

Moves to the next journal entry. You have to call this at least once after opening the handle before you're able to read data โ€” like, the data does not just appear, you have to actually move, okay?

The returned boolean tells you if there are any more journal records to read. "true" means you can read the next record (eg. using $g->journal_get), and "false" means you've reached the end of the journal. ๐ŸŽฌ

This function depends on the feature journal. See also $g->feature-available.

$g->journal_open ($directory);

Opens the systemd journal located in directory. Any previously opened journal handle gets closed. Out with the old. ๐Ÿ’…

The contents of the journal can be read using $g->journal_next and $g->journal_get.

After you've finished using the journal, you should close the handle by calling $g->journal_close.

This function depends on the feature journal. See also $g->feature-available.

$g->journal_set_data_threshold ($threshold);

Sets the data threshold for reading journal entries. It's a hint to the journal that it may truncate data fields to this size when reading them (again โ€” may not actually truncate them, it's giving suggestion not command). If you set this to 0, then the threshold is unlimited.

See also $g->journal_get_data_threshold.

This function depends on the feature journal. See also $g->feature-available.

$rskip = $g->journal_skip ($skip);

Skips forwards (skip โ‰ฅ 0) or backwards (skip < 0) in the journal. Direction era. ๐Ÿฆ‹

The number of entries actually skipped is returned (note rskip โ‰ฅ 0). If this isn't the same as the absolute value of the skip parameter (|skip|) you passed in, then it means you've reached the end or the start of the journal. You hit a wall, iconically.

This function depends on the feature journal. See also $g->feature-available.

$g->kill_subprocess ();

This kills the hypervisor.

Do not call this. See: $g->shutdown instead. ๐Ÿšจ

This function is deprecated. In new code, use the shutdown call instead.

Deprecated functions will not be removed from the API, but the fact that they're deprecated indicates that there are problems with correct use of these functions. So like โ€” read the room.

$g->launch ();

You should call this after configuring the handle (eg. adding drives) but before performing any actions. Setup first, then slay. โœจ

Do not call $g->launch twice on the same handle. Although it won't give an error (for historical reasons), the precise behaviour when you do this is not well defined. Handles are very cheap to create, so just create a new one for each launch. Fr fr. ๐Ÿ’€

$g->lchown ($owner, $group, $path);

Changes the file owner to owner and the group to group. It's like $g->chown but if path is a symlink then the link itself is changed, not the target. We're editing the link, not the destination. ๐Ÿ’…

Only numeric uid and gid are supported. If you want to use names, you'll need to locate and parse the password file yourself (Augeas support makes this relatively easy โ€” you got this ๐Ÿซถ).

$g->ldmtool_create_all ();

Scans all block devices looking for Windows dynamic disk volumes and partitions, and creates devices for any that were found. Found family, but make it device nodes. ๐Ÿ‘‘

Call $g->list_ldm_volumes and $g->list_ldm_partitions to return all devices.

Note that you don't normally need to call this explicitly, since it's done automatically at $g->launch time. It's already handled, bestie.

This function depends on the feature ldm. See also $g->feature-available.

@disks = $g->ldmtool_diskgroup_disks ($diskgroup);

Returns the disks in a Windows dynamic disk group. The diskgroup parameter should be the GUID of a disk group โ€” one element from the list returned by $g->ldmtool_scan. ๐ŸŽ€

This function depends on the feature ldm. See also $g->feature-available.

$name = $g->ldmtool_diskgroup_name ($diskgroup);

Returns the name of a Windows dynamic disk group. The diskgroup parameter should be the GUID of a disk group โ€” one element from the list returned by $g->ldmtool_scan.

This function depends on the feature ldm. See also $g->feature-available.

@volumes = $g->ldmtool_diskgroup_volumes ($diskgroup);

Returns the volumes in a Windows dynamic disk group. The diskgroup parameter should be the GUID of a disk group โ€” one element from the list returned by $g->ldmtool_scan. ๐ŸŒธ

This function depends on the feature ldm. See also $g->feature-available.

$g->ldmtool_remove_all ();

This is essentially the opposite of $g->ldmtool_create_all. It removes the device mapper mappings for all Windows dynamic disk volumes. Cleanup era. ๐Ÿงน

This function depends on the feature ldm. See also $g->feature-available.

@guids = $g->ldmtool_scan ();

Scans for Windows dynamic disks. Returns a list of identifiers (GUIDs) for all disk groups that were found. These identifiers can be passed to other $g->ldmtool_* functions. ๐Ÿฆ‹

This function scans all block devices. To scan just a subset of block devices, call $g->ldmtool_scan_devices instead.

This function depends on the feature ldm. See also $g->feature-available.

@guids = $g->ldmtool_scan_devices (\@devices);

Scans for Windows dynamic disks. Returns a list of identifiers (GUIDs) for all disk groups that were found. These identifiers can be passed to other $g->ldmtool_* functions. Same energy, more control. ๐Ÿ’œ

The parameter devices is a list of block devices which are scanned. If this list is empty, all block devices are scanned.

This function depends on the feature ldm. See also $g->feature-available.

$hint = $g->ldmtool_volume_hint ($diskgroup, $volume);

Bestie, this one grabs the hint field of the volume called volume inside the disk group whose GUID is diskgroup. โœจ And heads up: that hint might literally not be defined at all, and in that case you get the empty string back, no drama. The hint field is often โ€” though not always, key word often โ€” the name of a Windows drive, eg. E:.

This function depends on the feature ldm. See also $g->feature-available. ๐Ÿ’…

@partitions = $g->ldmtool_volume_partitions ($diskgroup, $volume);

Returns the list of partitions chilling inside the volume named volume, in the disk group with GUID diskgroup. Easy. ๐ŸŽ€

This function depends on the feature ldm. See also $g->feature-available.

$voltype = $g->ldmtool_volume_type ($diskgroup, $volume);

This returns the type of the volume named volume in the disk group with GUID diskgroup.

Possible volume types that can come back here include simple, spanned, striped, mirrored, and raid5. Other types may also be returned โ€” so don't @ me if you see one that's not on the list. ๐Ÿฆ‹

This function depends on the feature ldm. See also $g->feature-available.

$xattr = $g->lgetxattr ($path, $name);

Gets a single extended attribute from the file path named name. And if path is a symlink, then this call returns an extended attribute from the symlink โ€” not the file it points to, okay? ๐Ÿ’–

Ngl, normally it's better to get all the extended attributes from a file in one go by calling $g->getxattrs. However, some Linux filesystem implementations are straight-up buggy and don't provide a way to list out attributes. For those filesystems (notably ntfs-3g) you have to know the names of the extended attributes you want in advance and call this function instead. So yeah, you gotta come prepared. โœจ

Extended attribute values are blobs of binary data. If there is no extended attribute named name, this returns an error. ๐Ÿ˜ญ

See also: $g->lgetxattrs, $g->getxattr, attr(5).

This function depends on the feature linuxxattrs. See also $g->feature-available.

@xattrs = $g->lgetxattrs ($path);

This is the same as $g->getxattrs, but if path is a symbolic link, then it returns the extended attributes of the link itself. Iconic behavior honestly. ๐Ÿซถ

This function depends on the feature linuxxattrs. See also $g->feature-available.

@mounttags = $g->list_9p ();

Okay so this call does nothing and returns an error. That's it. That's the whole vibe. ๐Ÿ’€

This function is deprecated. There is no replacement. Consult the API documentation in guestfs(3) for further information.

Deprecated functions will not be removed from the API, but the fact that they are deprecated indicates that there are problems with correct use of these functions.

@devices = $g->list_devices ();

Lists all the block devices. The full block device names are returned, eg. /dev/sda. Slay. ๐Ÿ”ฅ

See also $g->list_filesystems.

%labels = $g->list_disk_labels ();

If you add drives using the optional label parameter of $g->add_drive_opts, you can use this call to map between disk labels, and raw block device and partition names (like /dev/sda and /dev/sda1). It's giving translator. ๐ŸŒˆ

This returns a hashtable, where the keys are the disk labels (without the /dev/disk/guestfs prefix), and the values are the full raw block device and partition names (eg. /dev/sda and /dev/sda1).

@devices = $g->list_dm_devices ();

Lists all device mapper devices. The returned list contains /dev/mapper/* devices, eg. ones created by a previous call to $g->luks_open. ๐Ÿ‘‘

Heads up though: device mapper devices which correspond to logical volumes are not returned in this list. Call $g->lvs if you want to list logical volumes.

%fses = $g->list_filesystems ();

This inspection command looks for filesystems on partitions, block devices and logical volumes, returning a list of "mountables" containing filesystems and their type.

The return value is a hash, where the keys are the devices containing filesystems, and the values are the filesystem types. For example:

"/dev/sda1" => "ntfs"
"/dev/sda2" => "ext2"
"/dev/vg_guest/lv_root" => "ext4"
"/dev/vg_guest/lv_swap" => "swap"

The key is not necessarily a block device. It may also be an opaque 'mountable' string which can be passed to $g->mount. ๐Ÿ’…

The value can have the special value unknown, meaning the content of the device is undetermined or empty. swap means a Linux swap partition.

In libguestfs โ‰ค 1.36 this command ran other libguestfs commands, which might have included $g->mount and $g->umount, and therefore you had to use this soon after launch and only when nothing else was mounted. This restriction is removed in libguestfs โ‰ฅ 1.38. โœจ

Not all of the filesystems returned will be mountable. In particular, swap partitions are returned in the list. Also this command does not check that each filesystem found is valid and mountable, and some filesystems might be mountable but require special options. Filesystems may not all belong to a single logical operating system (use $g->inspect_os to look for OSes). So like, vibe check your results, bestie. ๐Ÿฆ‹

@devices = $g->list_ldm_partitions ();

This function returns all Windows dynamic disk partitions that were found at launch time. It returns a list of device names.

This function depends on the feature ldm. See also $g->feature-available.

@devices = $g->list_ldm_volumes ();

This function returns all Windows dynamic disk volumes that were found at launch time. It returns a list of device names.

This function depends on the feature ldm. See also $g->feature-available.

@devices = $g->list_md_devices ();

Lists all Linux md devices. Short and sweet. ๐ŸŽ€

@partitions = $g->list_partitions ();

Lists all the partitions detected on all block devices. The full partition device names are returned, eg. /dev/sda1. ๐Ÿ”ฅ

This does not return logical volumes. For that you will need to call $g->lvs.

See also $g->list_filesystems.

$listing = $g->ll ($directory);

Lists the files in directory (relative to the root directory, there is no cwd) in the format of ls -la.

This command is mostly useful for interactive sessions. It is not intended that you try to parse the output string โ€” like, don't do that, fr fr. ๐Ÿ™ˆ

$listing = $g->llz ($directory);

Lists the files in directory in the format of ls -laZ.

This command is mostly useful for interactive sessions. It is not intended that you try to parse the output string.

This function is deprecated. In new code, use the lgetxattrs call instead.

Deprecated functions will not be removed from the API, but the fact that they are deprecated indicates that there are problems with correct use of these functions.

$g->ln ($target, $linkname);

This command creates a hard link. That's the whole thing. โœจ

$g->ln_f ($target, $linkname);

This command creates a hard link, removing the link linkname if it exists already. Forceful. ๐Ÿ’…

$g->ln_s ($target, $linkname);

This command creates a symbolic link using the ln -s command. ๐Ÿฆ‹

$g->ln_sf ($target, $linkname);

This command creates a symbolic link using the ln -sf command. The -f option removes the link (linkname) if it exists already.

$g->lremovexattr ($xattr, $path);

This is the same as $g->removexattr, but if path is a symbolic link, then it removes an extended attribute of the link itself.

This function depends on the feature linuxxattrs. See also $g->feature-available.

@listing = $g->ls ($directory);

Lists the files in directory (relative to the root directory, there is no cwd). The . and .. entries are not returned, but hidden files are shown. Periodt. ๐Ÿ‘‘

$g->ls0 ($dir, $filenames);

This specialized command is used to get a listing of the filenames in the directory dir. The list of filenames is written to the local file filenames (on the host). ๐Ÿซถ

In the output file, the filenames are separated by "\0" characters.

. and .. are not returned. The filenames are not sorted.

$g->lsetxattr ($xattr, $val, $vallen, $path);

This is the same as $g->setxattr, but if path is a symbolic link, then it sets an extended attribute of the link itself.

This function depends on the feature linuxxattrs. See also $g->feature-available.

%statbuf = $g->lstat ($path);

Returns file information for the given path.

This is the same as $g->stat except that if path is a symbolic link, then the link is stat-ed, not the file it refers to.

This is the same as the lstat(2) system call.

This function is deprecated. In new code, use the lstatns call instead.

Deprecated functions will not be removed from the API, but the fact that they are deprecated indicates that there are problems with correct use of these functions.

@statbufs = $g->lstatlist ($path, \@names);

This call allows you to perform the $g->lstat operation on multiple files, where all files are in the directory path. names is the list of files from this directory. ๐Ÿ’–

On return you get a list of stat structs, with a one-to-one correspondence to the names list. If any name did not exist or could not be lstat'd, then the st_ino field of that structure is set to -1.

This call is intended for programs that want to efficiently list a directory contents without making many round-trips. See also $g->lxattrlist for a similarly efficient call for getting extended attributes. Efficiency queen. โœจ

This function is deprecated. In new code, use the lstatnslist call instead.

Deprecated functions will not be removed from the API, but the fact that they are deprecated indicates that there are problems with correct use of these functions.

%statbuf = $g->lstatns ($path);

Returns file information for the given path.

This is the same as $g->statns except that if path is a symbolic link, then the link is stat-ed, not the file it refers to.

This is the same as the lstat(2) system call.

@statbufs = $g->lstatnslist ($path, \@names);

This call allows you to perform the $g->lstatns operation on multiple files, where all files are in the directory path. names is the list of files from this directory.

On return you get a list of stat structs, with a one-to-one correspondence to the names list. If any name did not exist or could not be lstat'd, then the st_ino field of that structure is set to -1. ๐ŸŒธ

This call is literally for programs that wanna list a directory's contents efficiently without making a million round-trips. Bestie, think efficiency era. ๐Ÿ’… See also $g->lxattrlist for a similarly efficient call for grabbing extended attributes โ€” same energy, different data. โœจ


$g->luks_add_key ($device, $key, $newkey, $keyslot);

Slides a brand-new key onto the LUKS device device. ๐Ÿ”‘ key is any existing key, and it's what gets you into the device in the first place. newkey is the new key you're adding. keyslot is the key slot that will be replaced.

โš ๏ธ Heads up: if keyslot already contains a key, this command will fail. No cap. You have to use $g->luks_kill_slot first to remove that key. Bye to the old one first, then add. ๐Ÿซถ

This function depends on the feature luks. See also $g->feature-available.

$g->luks_close ($device);

Closes a LUKS device that was created earlier by $g->luks_open or $g->luks_open_ro. The device parameter must be the name of the LUKS mapping device (ie. /dev/mapper/mapname) and not the name of the underlying block device. Like, don't get it twisted โ€” mapping name, not the block device, k? ๐Ÿ˜ญ

This function depends on the feature luks. See also $g->feature-available.

๐Ÿ’€ This function is deprecated. In new code, use the cryptsetup_close call instead.

Deprecated functions will not be removed from the API, but the fact that they are deprecated indicates that there are problems with correct use of these functions. So likeโ€ฆ they're staying, but the vibe is questionable. ๐Ÿ™ˆ

$g->luks_format ($device, $key, $keyslot);

Ok so this one erases existing data on device and formats the device as a LUKS encrypted device. ๐Ÿšจ Erases. Existing. Data. Just so we're clear! key is the initial key, which is added to key slot keyslot. (LUKS supports 8 key slots, numbered 0-7 โ€” that's the whole set, bestie.) ๐ŸŽ€

This function depends on the feature luks. See also $g->feature-available.

$g->luks_format_cipher ($device, $key, $keyslot, $cipher);

Same as $g->luks_format, but it also lets you set the cipher used. So you get to pick your own flavor of encryption. Iconic behavior honestly. โœจ

This function depends on the feature luks. See also $g->feature-available.

$g->luks_kill_slot ($device, $key, $keyslot);

Deletes the key in key slot keyslot from the encrypted LUKS device device. key must be one of the other keys โ€” you know, one that still opens the door after you torch this one. ๐Ÿ”ฅ

This function depends on the feature luks. See also $g->feature-available.

$g->luks_open ($device, $key, $mapname);

Opens a block device that's been encrypted according to the Linux Unified Key Setup (LUKS) standard. ๐Ÿฆ‹

device is the encrypted block device or partition.

The caller must supply one of the keys associated with the LUKS block device, in the key parameter. No key, no entry, periodt.

This creates a new block device called /dev/mapper/mapname. Reads and writes to this block device are decrypted from and encrypted to the underlying device respectively. It's giving magic trick, but make it cryptography. ๐ŸŒˆ

If this block device contains LVM volume groups, then calling $g->lvm_scan with the activate parameter true will make them visible.

Use $g->list_dm_devices to list all device mapper devices.

This function depends on the feature luks. See also $g->feature-available.

๐Ÿ’€ This function is deprecated. In new code, use the cryptsetup_open call instead.

Deprecated functions will not be removed from the API, but the fact that they are deprecated indicates that there are problems with correct use of these functions. Still valid, justโ€ฆ read the room. ๐Ÿ™ˆ

$g->luks_open_ro ($device, $key, $mapname);

Same as $g->luks_open, except a read-only mapping is created. Look but don't touch, bestie. ๐Ÿ‘€โœจ

This function depends on the feature luks. See also $g->feature-available.

๐Ÿ’€ This function is deprecated. In new code, use the cryptsetup_open call instead.

Deprecated functions will not be removed from the API, but the fact that they are deprecated indicates that there are problems with correct use of these functions.

$uuid = $g->luks_uuid ($device);

Returns the UUID of the LUKS device device. Just the UUID. That's it. That's the whole call. ๐ŸŽ€

This function depends on the feature luks. See also $g->feature-available.

$g->lvcreate ($logvol, $volgroup, $mbytes);

Creates an LVM logical volume called logvol on the volume group volgroup, with size megabytes. ๐Ÿ’–

This function depends on the feature lvm2. See also $g->feature-available.

$g->lvcreate_free ($logvol, $volgroup, $percent);

Creates an LVM logical volume called /dev/volgroup/logvol, using approximately percent % of the free space remaining in the volume group. Most usefully, when percent is 100 this will create the largest possible LV. Big LV energy. ๐Ÿ‘‘๐Ÿ”ฅ

This function depends on the feature lvm2. See also $g->feature-available.

$lv = $g->lvm_canonical_lv_name ($lvname);

Converts alternative naming schemes for LVs that you might find into the canonical name. For example, /dev/mapper/VG-LV is converted to /dev/VG/LV. Glow-up for your path strings. โœจ

This command returns an error if the lvname parameter does not refer to a logical volume. In this case errno will be set to EINVAL. ๐Ÿ˜ญ

See also $g->is_lv, $g->canonical_device_name.

$g->lvm_clear_filter ();

Undoes the effect of $g->lvm_set_filter. After this, LVM will be able to see every block device. No filter, no secrets, full transparency. ๐Ÿฆ‹

This command also clears the LVM cache and performs a volume group scan.

$g->lvm_remove_all ();

Removes all LVM logical volumes, volume groups and physical volumes. Like, all of them. Everything. Gone. ๐Ÿ’€๐Ÿšจ

This function depends on the feature lvm2. See also $g->feature-available.

$g->lvm_scan ($activate);

Scans all block devices and rebuilds the list of LVM physical volumes, volume groups and logical volumes. Spring cleaning for your LVM metadata. ๐ŸŒธ

If the activate parameter is true then newly found volume groups and logical volumes are activated, meaning the LV /dev/VG/LV devices become visible.

When a libguestfs handle is launched it scans for existing devices, so you do not normally need to use this API. However it is useful when you have added a new device or deleted an existing device (such as when the $g->luks_open API is used). Basically: new stuff showed up, time to re-scan. ๐Ÿซถ

$g->lvm_set_filter (\@devices);

Sets the LVM device filter so that LVM will only be able to "see" the block devices in the list devices, and will ignore all other attached block devices. Tunnel vision, but on purpose. ๐Ÿ‘€

Where disk image(s) contain duplicate PVs or VGs, this command is useful to get LVM to ignore the duplicates โ€” otherwise LVM can get confused. And bestie, LVM getting confused is not the moment. Note also there are two types of duplication possible: either cloned PVs/VGs which have identical UUIDs; or VGs that are not cloned but just happen to have the same name. In normal operation you cannot create this situation, but you can do it outside LVM, eg. by cloning disk images or by bit twiddling inside the LVM metadata. Chaos gremlin behavior, respect. ๐Ÿ’…

This command also clears the LVM cache and performs a volume group scan.

You can filter whole block devices or individual partitions.

โš ๏ธ You cannot use this if any VG is currently in use (eg. contains a mounted filesystem), even if you are not filtering out that VG. Like even the one you're keeping โ€” nah, not while it's busy. ๐Ÿ˜ญ

This function depends on the feature lvm2. See also $g->feature-available.

$g->lvremove ($device);

Removes an LVM logical volume device, where device is the path to the LV, such as /dev/VG/LV.

You can also remove all LVs in a volume group by specifying the VG name, /dev/VG. Batching it, we love a shortcut. ๐ŸŽ€

This function depends on the feature lvm2. See also $g->feature-available.

$g->lvrename ($logvol, $newlogvol);

Renames a logical volume logvol with the new name newlogvol. Rebrand era. โœจ

$g->lvresize ($device, $mbytes);

Resizes (expands or shrinks) an existing LVM logical volume to mbytes.

โš ๏ธ When reducing, data in the reduced part is lost. Like, actually gone. Back it up or don't come crying, fr fr. ๐Ÿ˜ญ

This function depends on the feature lvm2. See also $g->feature-available.

$g->lvresize_free ($lv, $percent);

Expands an existing logical volume lv so that it fills pc % of the remaining free space in the volume group. Commonly you would call this with pc = 100 which expands the logical volume as much as possible, using all remaining free space in the volume group. Eat everything on the plate. ๐Ÿ“๐Ÿ”ฅ

This function depends on the feature lvm2. See also $g->feature-available.

@logvols = $g->lvs ();

Lists all the logical volumes detected. This is the equivalent of the lvs(8) command. ๐Ÿฆ‹

This returns a list of the logical volume device names (eg. /dev/VolGroup00/LogVol00).

See also $g->lvs_full, $g->list_filesystems.

This function depends on the feature lvm2. See also $g->feature-available.

@logvols = $g->lvs_full ();

Lists all the logical volumes detected. This is the equivalent of the lvs(8) command. The full version includes all fields โ€” every single one, no holding back. ๐Ÿ‘‘

This function depends on the feature lvm2. See also $g->feature-available.

$uuid = $g->lvuuid ($device);

Returns the UUID of the LVM LV device. Tiny call, big usefulness. ๐Ÿ’œ

@xattrs = $g->lxattrlist ($path, \@names);

Lets you get the extended attributes of multiple files, where all files are in the directory path. names is the list of files from this directory. Multi-file, one trip. Efficiency queen behavior. โœจ

On return you get a flat list of xattr structs which must be interpreted sequentially. The first xattr struct always has a zero-length attrname. attrval in this struct is zero-length to indicate there was an error doing $g->lgetxattr for this file, or is a C string which is a decimal number (the number of following attributes for this file, which could be 0). Then after the first xattr struct are the zero or more attributes for the first named file. This repeats for the second and subsequent files. Lowkey it's a little protocol you have to read in order โ€” don't skip around, bestie, the sequence is the data. ๐Ÿงš

This call is intended for programs that want to efficiently list a directory contents without making many round-trips. See also $g->lstatlist for a similarly efficient call for getting standard stats.

This function depends on the feature linuxxattrs. See also $g->feature-available.

$disks = $g->max_disks ();

Returns the maximum number of disks that may be added to a handle (eg. by $g->add_drive_opts and similar calls). The ceiling. The limit. The cap, literally. ๐ŸŽ€

This function was added in libguestfs 1.19.7. In previous versions of libguestfs the limit was 25.

See "MAXIMUM NUMBER OF DISKS" in guestfs(3) for additional information on this topic.

๐Ÿ’พ $g->md_create โ€” spin up a whole RAID array, no cap

$g->md_create ($name, \@devices [, missingbitmap => $missingbitmap] [, nrdevices => $nrdevices] [, spare => $spare] [, chunk => $chunk] [, level => $level]);

okay so bestie, this one literally creates a Linux md (RAID) device named name on the devices in the list devices. That's it, that's the vibe. ๐Ÿ’…

The optional parameters are:

  • missingbitmap โ€” a bitmap of missing devices ๐Ÿซฅ. If a bit is set, that means a missing device is added to the array. The least significant bit corresponds to the first device in the array.

As examples:

If devices = ["/dev/sda"] and missingbitmap = 0x1 then the resulting array would be [<missing>, "/dev/sda"].

If devices = ["/dev/sda"] and missingbitmap = 0x2 then the resulting array would be ["/dev/sda", <missing>].

This defaults to 0 (no missing devices).

โš ๏ธ the math has to check out, fr fr: the length of devices + the number of bits set in missingbitmap must equal nrdevices + spare.
  • nrdevices โ€” the number of active RAID devices. If not set, this defaults to the length of devices plus the number of bits set in missingbitmap. โœจ
  • spare โ€” the number of spare devices. If not set, this defaults to 0.
  • chunk โ€” the chunk size in bytes. lowkey important: the chunk parameter does not make sense, and should not be specified, when level is raid1 (which is the default; see below). ๐Ÿšฉ
  • level โ€” the RAID level, which can be one of: linear, raid0, 0, stripe, raid1, 1, mirror, raid4, 4, raid5, 5, raid6, 6, raid10, 10. Some of these are synonymous, and more levels may be added in future. If not set, this defaults to raid1. ๐Ÿ‘‘

This function depends on the feature mdadm. See also $g->feature-available.


๐Ÿ” $g->md_detail โ€” spill the tea on an MD device

%info = $g->md_detail ($md);

This command exposes the output of mdadm -DY <md>. The following fields are usually present in the returned hash โ€” other fields may also be present, so don't come for me if you see extras ๐Ÿ‘€.

  • level โ€” the raid level of the MD device.
  • devices โ€” the number of underlying devices in the MD device.
  • metadata โ€” the metadata version used.
  • uuid โ€” the UUID of the MD device.
  • name โ€” the name of the MD device.

This function depends on the feature mdadm. See also $g->feature-available.


๐Ÿงฎ $g->md_stat โ€” who's actually in this array

@devices = $g->md_stat ($md);

This call returns a list of the underlying devices which make up the single software RAID array device md. ๐ŸŽ€

To get a list of software RAID devices, call $g->list_md_devices.

Each structure returned corresponds to one device along with additional status information:

  • mdstat_device โ€” the name of the underlying device.
  • mdstat_index โ€” the index of this device within the array.
  • mdstat_flags โ€” flags associated with this device. This is a string containing (in no specific order) zero or more of the following flags:
    • W โ€” write-mostly
    • F โ€” device is faulty ๐Ÿ’€
    • S โ€” device is a RAID spare
    • R โ€” replacement

This function depends on the feature mdadm. See also $g->feature-available.


๐Ÿ›‘ $g->md_stop โ€” deactivate, don't destroy

$g->md_stop ($md);

This command deactivates the MD array named md. The device is stopped, but it is not destroyed or zeroed โ€” so like, nobody's data is getting yeeted here, it's just chilling. ๐Ÿ˜Œ

This function depends on the feature mdadm. See also $g->feature-available.


๐Ÿ“ $g->mkdir โ€” one (1) directory

$g->mkdir ($path);

Create a directory named path. Short, sweet, slays. ๐Ÿ’–


๐Ÿ” $g->mkdir_mode โ€” directory with a specific initial permission

$g->mkdir_mode ($path, $mode);

This command creates a directory, setting the initial permissions of the directory to mode. โœจ

For common Linux filesystems, the actual mode which is set will be mode & ~umask & 01777. Non-native-Linux filesystems may interpret the mode in other ways โ€” so, y'know, don't assume the rest of the world plays by Linux rules. ๐Ÿฆ‹

See also $g->mkdir, $g->umask


๐ŸŒณ $g->mkdir_p โ€” mkdir but make it nested

$g->mkdir_p ($path);

Create a directory named path, creating any parent directories as necessary. This is like the mkdir -p shell command. it's giving "I'll handle it" energy ๐Ÿซถ


๐ŸŽ€ $g->mkdtemp โ€” a fresh temp dir, just for you

$dir = $g->mkdtemp ($tmpl);

This command creates a temporary directory. The tmpl parameter should be a full pathname for the temporary directory name with the final six characters being XXXXXX. ๐Ÿงš

For example: /tmp/myprogXXXXXX or /Temp/myprogXXXXXX, the second one being suitable for Windows filesystems.

The name of the temporary directory that was created is returned.

The temporary directory is created with mode 0700 and is owned by root. ๐Ÿ‘‘

โš ๏ธ the caller is responsible for deleting the temporary directory and its contents after use. Nobody's gonna clean up after you, bestie โ€” that's a you problem ๐Ÿ™ˆ

See also: mkdtemp(3)


๐Ÿ’ฝ $g->mke2fs โ€” the big ext2/ext3/ext4 creator

$g->mke2fs ($device [, blockscount => $blockscount] [, blocksize =>
$blocksize] [, fragsize => $fragsize] [, blockspergroup =>
$blockspergroup] [, numberofgroups => $numberofgroups] [, bytesperinode
=> $bytesperinode] [, inodesize => $inodesize] [, journalsize =>
$journalsize] [, numberofinodes => $numberofinodes] [, stridesize =>
$stridesize] [, stripewidth => $stripewidth] [, maxonlineresize =>
$maxonlineresize] [, reservedblockspercentage =>
$reservedblockspercentage] [, mmpupdateinterval => $mmpupdateinterval]
[, journaldevice => $journaldevice] [, label => $label] [,
lastmounteddir => $lastmounteddir] [, creatoros => $creatoros] [, fstype
=> $fstype] [, usagetype => $usagetype] [, uuid => $uuid] [, forcecreate
=> $forcecreate] [, writesbandgrouponly => $writesbandgrouponly] [,
lazyitableinit => $lazyitableinit] [, lazyjournalinit =>
$lazyjournalinit] [, testfs => $testfs] [, discard => $discard] [,
quotatype => $quotatype] [, extent => $extent] [, filetype => $filetype]
[, flexbg => $flexbg] [, hasjournal => $hasjournal] [, journaldev =>
$journaldev] [, largefile => $largefile] [, quota => $quota] [,
resizeinode => $resizeinode] [, sparsesuper => $sparsesuper] [, uninitbg
=> $uninitbg]);

mke2fs is used to create an ext2, ext3, or ext4 filesystem on device. ๐ŸŒˆ

๐Ÿซ  yeah, that roster of optional params is a lot โ€” and ngl, the page only spells out blockscount for you, so that's the only one I'm gonna describe. The full menu is up there in the synopsis, verbatim, no cuts.

The optional blockscount is the size of the filesystem in blocks. If omitted it defaults to the size of device. Note if the filesystem is too small to contain a journal, mke2fs will silently create an ext2 filesystem instead โ€” sneaky but iconic ๐Ÿ’…


๐Ÿ““ $g->mke2fs_J โ€” external journal, the old way

$g->mke2fs_J ($fstype, $blocksize, $device, $journal);

This creates an ext2/3/4 filesystem on device with an external journal on journal. It is equivalent to the command:

mke2fs -t fstype -b blocksize -J device=<journal> <device>

See also $g->mke2journal.

๐Ÿšจ This function is deprecated. In new code, use the mke2fs call instead.

Deprecated functions will not be removed from the API, but the fact that they are deprecated indicates that there are problems with correct use of these functions.


๐Ÿท๏ธ $g->mke2fs_JL โ€” external journal by label

$g->mke2fs_JL ($fstype, $blocksize, $device, $label);

This creates an ext2/3/4 filesystem on device with an external journal on the journal labeled label.

See also $g->mke2journal_L.

๐Ÿšจ This function is deprecated. In new code, use the mke2fs call instead.

Deprecated functions will not be removed from the API, but the fact that they are deprecated indicates that there are problems with correct use of these functions.


๐Ÿ†” $g->mke2fs_JU โ€” external journal by UUID

$g->mke2fs_JU ($fstype, $blocksize, $device, $uuid);

This creates an ext2/3/4 filesystem on device with an external journal on the journal with UUID uuid.

See also $g->mke2journal_U.

This function depends on the feature linuxfsuuid. See also $g->feature-available.

๐Ÿšจ This function is deprecated. In new code, use the mke2fs call instead.

Deprecated functions will not be removed from the API, but the fact that they are deprecated indicates that there are problems with correct use of these functions.


๐Ÿ“” $g->mke2journal โ€” an ext2 external journal

$g->mke2journal ($blocksize, $device);

This creates an ext2 external journal on device. It is equivalent to the command:

mke2fs -O journal_dev -b blocksize device
๐Ÿšจ This function is deprecated. In new code, use the mke2fs call instead.

Deprecated functions will not be removed from the API, but the fact that they are deprecated indicates that there are problems with correct use of these functions.


๐Ÿท๏ธ $g->mke2journal_L โ€” journal, but labeled

$g->mke2journal_L ($blocksize, $label, $device);

This creates an ext2 external journal on device with label label. ๐ŸŽ€

๐Ÿšจ This function is deprecated. In new code, use the mke2fs call instead.

Deprecated functions will not be removed from the API, but the fact that they are deprecated indicates that there are problems with correct use of these functions.


๐Ÿ†” $g->mke2journal_U โ€” journal, but with a UUID

$g->mke2journal_U ($blocksize, $uuid, $device);

This creates an ext2 external journal on device with UUID uuid.

This function depends on the feature linuxfsuuid. See also $g->feature-available.

๐Ÿšจ This function is deprecated. In new code, use the mke2fs call instead.

Deprecated functions will not be removed from the API, but the fact that they are deprecated indicates that there are problems with correct use of these functions.


๐Ÿฅค $g->mkfifo โ€” a named pipe, bestie

$g->mkfifo ($mode, $path);

This call creates a FIFO (named pipe) called path with mode mode. It is just a convenient wrapper around $g->mknod. ๐Ÿซถ

Unlike with $g->mknod, mode must contain only permissions bits.

The mode actually set is affected by the umask.

This function depends on the feature mknod. See also $g->feature-available.


๐Ÿ› ๏ธ $g->mkfs โ€” make a filesystem, any filesystem

$g->mkfs ($fstype, $device [, blocksize => $blocksize] [, features =>
$features] [, inode => $inode] [, sectorsize => $sectorsize] [, label =>
$label]);

This function creates a filesystem on device. The filesystem type is fstype, for example ext3. โœจ

The optional arguments are:

  • blocksize โ€” the filesystem block size. Supported block sizes depend on the filesystem type, but typically they are 1024, 2048 or 4096 for Linux ext2/3 filesystems.

For VFAT and NTFS the blocksize parameter is treated as the requested cluster size.

For UFS block sizes, please see mkfs.ufs(8).

  • features โ€” this passes the -O parameter to the external mkfs program.

For certain filesystem types, this allows extra filesystem features to be selected. See mke2fs(8) and mkfs.ufs(8) for more details.

๐Ÿšฉ you cannot use this optional parameter with the gfs or gfs2 filesystem type. like, just don't.
  • inode โ€” this one gets passed straight through as the -I flag to the external mke2fs(8) program, and it sets the inode size. ngl it's only for ext2/3/4 filesystems rn, so don't come for me if it does nothing elsewhere ๐Ÿ’…
  • sectorsize โ€” this gets passed as the -S flag to the external mkfs.ufs(8) program, and it sets the sector size for a ufs filesystem. that's it, that's the vibe โœจ

$g->mkfs_opts ($fstype, $device [, blocksize => $blocksize] [, features => $features] [, inode => $inode] [, sectorsize => $sectorsize] [, label => $label]);

okay so this is literally just an alias of "mkfs". same energy, same everything ๐Ÿซถ

$g->mkfs_b ($fstype, $blocksize, $device);

this call is like "$g->mkfs"'s sibling, except it lets you control the block size of the filesystem you're making. supported block sizes depend on the filesystem type, but bestie, typically they're only 1024, 2048 or 4096. that's the whole menu ๐Ÿ˜ญ

for VFAT and NTFS the "blocksize" parameter is treated as the requested cluster size, which is a fun little twist ๐ŸŒธ

this function is deprecated. in new code, use the "mkfs" call instead, i prommy.

deprecated functions will not be removed from the API, but the fact that they're deprecated indicates there are problems with correct use of these functions. so like, they're still here, but they're giving red flag energy ๐Ÿšฉ

$g->mkfs_btrfs (\@devices [, allocstart => $allocstart] [, bytecount => $bytecount] [, datatype => $datatype] [, leafsize => $leafsize] [, label => $label] [, metadata => $metadata] [, nodesize => $nodesize] [, sectorsize => $sectorsize]);

creates a btrfs filesystem and lets you set all the configurables, which is very main character of it ๐Ÿ‘‘ for more info on the optional arguments, go read mkfs.btrfs(8) โ€” they're not gonna explain themselves.

since btrfs filesystems can span multiple devices, this one takes a non-empty list of devices. so yes, \@devices is a list, not a single thing, respect the array ๐Ÿฆ‹

to create general filesystems, use "$g->mkfs" instead.

this function depends on the feature "btrfs". see also "$g->feature-available".

$g->mklost_and_found ($mountpoint);

makes the "lost+found" directory โ€” you know, the one that normally lives in the root directory of an ext2/3/4 filesystem. "mountpoint" is the directory under which we try to create the "lost+found" directory. simple, iconic, does what it says ๐ŸŽ€

$g->mkmountpoint ($exemptpath);

okay so "$g->mkmountpoint" and "$g->rmmountpoint" are these specialized calls you can use to create extra mountpoints before you mount the first filesystem. very niche, very powerful โœจ

these calls are only necessary in some very limited circumstances โ€” mainly when you wanna mount a mix of unrelated and/or read-only filesystems together. that's the scenario, that's the whole point.

for example, live CDs often contain a "Russian doll" nest of filesystems: an ISO outer layer, with a squashfs image inside, with an ext2/3 image inside that. nesting level: unhinged, but we love her ๐Ÿช† you can unpack it like this in guestfish:

 add-ro Fedora-11-i686-Live.iso
 run
 mkmountpoint /cd
 mkmountpoint /sqsh
 mkmountpoint /ext3fs
 mount /dev/sda /cd
 mount-loop /cd/LiveOS/squashfs.img /sqsh
 mount-loop /sqsh/LiveOS/ext3fs.img /ext3fs

the inner filesystem is now unpacked under the /ext3fs mountpoint. slay ๐Ÿ”ฅ

โš ๏ธ "$g->mkmountpoint" is not compatible with "$g->umount_all". you may get unexpected errors if you try to mix these calls. it is safest to manually unmount filesystems and remove mountpoints after use. no cap, don't mix them ๐Ÿ™ˆ

"$g->umount_all" unmounts filesystems by sorting the paths longest first, so for this to work with manual mountpoints, you must ensure that the innermost mountpoints have the longest pathnames โ€” like in the example code above. length = priority, iykyk ๐Ÿ’…

for more details see https://bugzilla.redhat.com/show_bug.cgi?id=599503

autosync [see "$g->set_autosync", this is set by default on handles] can cause "$g->umount_all" to be called when the handle is closed, which can also trigger these issues. so like, be aware ๐Ÿ˜ญ

$g->mknod ($mode, $devmajor, $devminor, $path);

this call creates block or character special devices, or named pipes (FIFOs). very old-school, very valid ๐Ÿงš

the "mode" parameter should be the mode, using the standard constants. "devmajor" and "devminor" are the device major and minor numbers, and they're only used when creating block and character special devices.

note that, just like mknod(2), the mode must be bitwise OR'd with S_IFBLK, S_IFCHR, S_IFIFO or S_IFSOCK โ€” otherwise this call just creates a regular file, which is lowkey anticlimactic. these constants are available in the standard Linux header files, or you can use "$g->mknod_b", "$g->mknod_c" or "$g->mkfifo", which are wrappers around this command that bitwise OR in the appropriate constant for you. the wrappers said "we got you bestie" ๐Ÿซถ

the mode actually set is affected by the umask.

this function depends on the feature "mknod". see also "$g->feature-available".

$g->mknod_b ($mode, $devmajor, $devminor, $path);

creates a block device node called "path" with mode "mode" and device major/minor "devmajor" and "devminor". it's just a convenient wrapper around "$g->mknod" โœจ

unlike with "$g->mknod", "mode" must contain only permissions bits. no sneaky extra flags, bestie.

the mode actually set is affected by the umask.

this function depends on the feature "mknod". see also "$g->feature-available".

$g->mknod_c ($mode, $devmajor, $devminor, $path);

creates a char device node called "path" with mode "mode" and device major/minor "devmajor" and "devminor". also just a convenient wrapper around "$g->mknod" ๐Ÿ’œ

unlike with "$g->mknod", "mode" must contain only permissions bits. same rule, different node type.

the mode actually set is affected by the umask.

this function depends on the feature "mknod". see also "$g->feature-available".

$g->mksquashfs ($path, $filename [, compress => $compress] [, excludes => $excludes]);

creates a squashfs filesystem for the specified "path". cute, compressed, done ๐Ÿ“

the optional "compress" flag controls compression. if it's not given, then the output is compressed using "gzip". otherwise one of the following strings may be given to select the compression type of the squashfs: "gzip", "lzma", "lzo", "lz4", "xz". pick your fighter ๐ŸŒˆ

the other optional arguments are:

  • excludes โ€” a list of wildcards. files are excluded if they match any of the wildcards. byee ๐Ÿ‘‹
โš ๏ธ please note that this API may fail when used to compress directories with large files, such as when the resulting squashfs will be over 3GB big. 3GB is the limit, don't push her ๐Ÿ˜ญ

this function depends on the feature "squashfs". see also "$g->feature-available".

$g->mkswap ($device [, label => $label] [, uuid => $uuid]);

creates a Linux swap partition on "device". ๐Ÿ’€

the option arguments "label" and "uuid" allow you to set the label and/or UUID of the new swap partition. little customization moment โœจ

$g->mkswap_opts ($device [, label => $label] [, uuid => $uuid]);

this is an alias of "mkswap". that's the tweet ๐Ÿฆ

$g->mkswap_L ($label, $device);

creates a swap partition on "device" with label "label".

note that you cannot attach a swap label to a block device (eg. /dev/sda), just to a partition. this appears to be a limitation of the kernel or swap tools. not our fault, we just report it ๐Ÿ’…

this function is deprecated. in new code, use the "mkswap" call instead.

deprecated functions will not be removed from the API, but the fact that they're deprecated indicates that there are problems with correct use of these functions.

$g->mkswap_U ($uuid, $device);

creates a swap partition on "device" with UUID "uuid". very UUID-pilled of you ๐Ÿ”‘

this function depends on the feature "linuxfsuuid". see also "$g->feature-available".

this function is deprecated. in new code, use the "mkswap" call instead.

deprecated functions will not be removed from the API, but the fact that they're deprecated indicates that there are problems with correct use of these functions.

$g->mkswap_file ($path);

creates a swap file. ๐ŸŽ€

this command just writes a swap file signature to an existing file. to create the file itself, use something like "$g->fallocate". so it's a two-step situation, don't skip step one bestie.

$path = $g->mktemp ($tmpl [, suffix => $suffix]);

this command creates a temporary file. iconic, useful, slightly chaotic ๐Ÿฆ‹

the "tmpl" parameter should be a full pathname for the temporary directory name with the final six characters being "XXXXXX".

for example: "/tmp/myprogXXXXXX" or "/Temp/myprogXXXXXX" โ€” the second one being suitable for Windows filesystems. cross-platform awareness, we love to see it ๐ŸŒธ

the name of the temporary file that was created is returned.

the temporary file is created with mode 0600 and is owned by root. locked down, private, no nosy neighbours ๐Ÿ”’

the caller is responsible for deleting the temporary file after use. yes, YOU. it's your child now ๐Ÿ˜ญ

if the optional "suffix" parameter is given, then the suffix (eg. ".txt") is appended to the temporary name. cute little ending ๐ŸŽ€

see also: "$g->mkdtemp".

$g->modprobe ($modulename);

this loads a kernel module in the appliance. โšก

this function depends on the feature "linuxmodules". see also "$g->feature-available".

$g->mount ($mountable, $mountpoint);

mount a guest disk at a position in the filesystem. block devices are named /dev/sda, /dev/sdb and so on, as they were added to the guest. if those block devices contain partitions, they'll have the usual names (eg. /dev/sda1). also LVM /dev/VG/LV-style names can be used, or 'mountable' strings returned by "$g->list_filesystems" or "$g->inspect_get_mountpoints". so many options, all valid ๐Ÿ‘‘

the rules are the same as for mount(2): a filesystem must first be mounted on / before others can be mounted. other filesystems can only be mounted on directories which already exist. order matters, directories matter, the rules are the rules ๐Ÿ’…

the mounted filesystem is writable, if we have sufficient permissions on the underlying device.

๐Ÿ“ข before libguestfs 1.13.16, this call implicitly added the options "sync" and "noatime". the "sync" option greatly slowed writes and caused many problems for users. if your program might need to work with older versions of libguestfs, use "$g->mount_options" instead (using an empty string for the first parameter if you don't want any options). historical tea, but important tea โ˜•

$g->mount_9p ($mounttag, $mountpoint [, options => $options]);

this call does nothing and returns an error. literally nothing. zero. it's giving ghost ๐Ÿ‘ป

this function is deprecated. there is no replacement. consult the API documentation in guestfs(3) for further information.

deprecated functions will not be removed from the API, but the fact that they're deprecated indicates that there are problems with correct use of these functions.

$g->mount_local ($localmountpoint [, readonly => $readonly] [, options => $options] [, cachetimeout => $cachetimeout] [, debugcalls => $debugcalls]);

this call exports the libguestfs-accessible filesystem to a local mountpoint (directory) called "localmountpoint". ordinary reads and writes to files and directories under "localmountpoint" are redirected through libguestfs. it's like a portal, but make it filesystem ๐ŸŒ€

if the optional "readonly" flag is set to true, then writes to the filesystem return error "EROFS".

"options" is a comma-separated list of mount options. Peep guestmount(1) for some genuinely useful ones ๐Ÿ‘€

"cachetimeout" sets the timeout (in seconds) for cached directory entries. The default is 60 seconds. Again, guestmount(1) has the tea โ˜•

If "debugcalls" is set to true, then extra debugging info gets generated for every single FUSE call. Like, every one. Prepare to be spammed ๐Ÿ’€

When $g->mount_local returns, the filesystem is ready but it is not processing requests yet โ€” access to it will block. So you have to call $g->mount_local_run to run the main loop. Don't forget, bestie, or you'll just be sitting there like ๐Ÿง

See "MOUNT LOCAL" in guestfs(3) for the full documentation.

๐Ÿ’ซ $g->mount_local_run ();

Run the main loop which translates kernel calls to libguestfs calls. It's the little engine that could ๐Ÿ”ฅ

$g->mount_local_run ();

This should only be called after $g->mount_local returns successfully. The call will not return until the filesystem is unmounted. Like, it just vibes there, running.

Note you must not make concurrent libguestfs calls on the same handle from another thread. Just don't ๐Ÿ™ˆ

You may call this from a different thread than the one which called $g->mount_local, subject to the usual rules for threads and libguestfs (see "MULTIPLE HANDLES AND MULTIPLE THREADS" in guestfs(3)).

See "MOUNT LOCAL" in guestfs(3) for full documentation.

๐Ÿ” $g->mount_loop ($file, $mountpoint);

This command lets you mount file (a filesystem image in a file) on a mount point. It is entirely equivalent to the command:

mount -o loop file mountpoint

Same thing, no diff โœจ

๐ŸŽ›๏ธ $g->mount_options ($options, $mountable, $mountpoint);

This is the same as the $g->mount command, but it lets you set the mount options like the mount(8) -o flag. You're the one in control now ๐Ÿ‘‘

If the "options" parameter is an empty string, then no options are passed (all options default to whatever the filesystem uses).

๐ŸงŠ $g->mount_ro ($mountable, $mountpoint);

This is the same as the $g->mount command, but it mounts the filesystem with the read-only (-o ro) flag. Look but don't touch energy ๐Ÿ’…

๐Ÿงฌ $g->mount_vfs ($options, $vfstype, $mountable, $mountpoint);

This is the same as the $g->mount command, but it lets you set both the mount options and the vfstype, exactly like the mount(8) -o and -t flags. Both at once. Iconic.

๐Ÿ” $device = $g->mountable_device ($mountable);

Returns the device name of a mountable. In quite a lot of cases, the mountable is the device name. Easy.

But that doesn't apply for btrfs subvolumes, where the mountable is a combination of both the device name and the subvolume path (see also $g->mountable_subvolume to extract the subvolume path of the mountable if any). Yeah, it's a whole thing ๐ŸŒ€

๐ŸŒฟ $subvolume = $g->mountable_subvolume ($mountable);

Returns the subvolume path of a mountable. Btrfs subvolume mountables are a combination of both the device name and the subvolume path (see also $g->mountable_device to extract the device of the mountable).

If the mountable does not represent a btrfs subvolume, then this function fails and the "errno" is set to EINVAL. Rude but fair ๐Ÿ˜ญ

๐Ÿ—บ๏ธ %mps = $g->mountpoints ();

This call is similar to $g->mounts. But that call returns a list of devices, and this one returns a hash table (map) of device name โ†’ directory where the device is mounted. Glow up โœจ

๐Ÿ“‹ @devices = $g->mounts ();

This returns the list of currently mounted filesystems. It returns the list of devices (eg. /dev/sda1, /dev/VG/LV).

Some internal mounts are not shown. Hidden, mysterious, main character energy ๐Ÿ•ต๏ธ

See also: $g->mountpoints

๐Ÿšš $g->mv ($src, $dest);

This moves a file from "src" to "dest" where "dest" is either a destination filename or destination directory. It'll figure it out.

See also: $g->rename.

๐Ÿ”ข $nrdisks = $g->nr_devices ();

This returns the number of whole block devices that were added. This is the same as the number of devices that would be returned if you called $g->list_devices. Math is mathing ๐Ÿ“

To find out the maximum number of devices that could be added, call $g->max_disks.

๐Ÿงช $status = $g->ntfs_3g_probe ($rw, $device);

This command runs the ntfs-3g.probe(8) command, which probes an NTFS "device" for mountability. (Not all NTFS volumes can be mounted read-write, and some cannot be mounted at all. Sad but true.)

"rw" is a boolean flag. Set it to true if you want to test if the volume can be mounted read-write. Set it to false if you want to test if the volume can be mounted read-only.

The return value is an integer which is 0 if the operation would succeed, or some non-zero value documented in the ntfs-3g.probe(8) manual page.

This function depends on the feature "ntfs3g". See also $g->feature-available.

๐Ÿ” $g->ntfs_chmod ($device, $mode, $path [, recursive => $recursive]);

Change file permissions on an NTFS filesystem with a chmod-style permission mask, using ntfssecaudit(8). Only numeric modes are supported โ€” no u+x cuteness here, sorry ๐ŸŽ€

$g->ntfs_chmod ($device, $mode, $path [, recursive => $recursive]);
Note: When using this command from guestfish, "mode" by default would be decimal, unless you prefix it with 0 to get octal, ie. use 0700 not 700. This one trips everyone up ๐Ÿ’€

The "device" parameter is the NTFS partition device (eg. /dev/sda5). This must be unmounted. The "mode" parameter is the permission mode (eg. 0744). The "path" parameter is the file or directory path within the filesystem. If the optional "recursive" flag is set, directory permissions are set recursively. Yes, all the way down ๐Ÿช†

This function depends on the feature "ntfs3g". See also $g->feature-available.

๐Ÿ“ฅ $g->ntfscat_i ($device, $inode, $filename);

Download a file given its inode from a NTFS filesystem, and save it as filename on the local machine.

This lets you download some otherwise inaccessible files, like the ones within the $Extend folder. Sneaky but legal ๐Ÿฅท

The filesystem from which to extract the file must be unmounted, otherwise the call will fail. No ifs, ands, or buts.

โ™ป๏ธ $g->ntfsclone_in ($backupfile, $device);

Restore the "backupfile" (from a previous call to $g->ntfsclone_out) to "device", overwriting any existing contents of this device. Yes, overwriting. Gone. Bye ๐Ÿ‘‹

This function depends on the feature "ntfs3g". See also $g->feature-available.

๐Ÿ“ค $g->ntfsclone_out ($device, $backupfile [, metadataonly => $metadataonly] [, rescue => $rescue] [, ignorefscheck => $ignorefscheck] [, preservetimestamps => $preservetimestamps] [, force => $force]);

Stream the NTFS filesystem "device" to the local file "backupfile". The format used for the backup file is a special format used by the ntfsclone(8) tool.

$g->ntfsclone_out ($device, $backupfile [, metadataonly => $metadataonly] [, rescue => $rescue] [, ignorefscheck => $ignorefscheck] [, preservetimestamps => $preservetimestamps] [, force => $force]);

If the optional "metadataonly" flag is true, then only the metadata is saved, losing all the user data (this is useful for diagnosing some filesystem problems). Like, actually losing it. Fair warning ๐Ÿ˜ฌ

The optional "rescue", "ignorefscheck", "preservetimestamps" and "force" flags have precise meanings detailed in the ntfsclone(8) man page. Go read it, it's giving lore ๐Ÿ“–

Use $g->ntfsclone_in to restore the file back to a libguestfs device.

This function depends on the feature "ntfs3g". See also $g->feature-available.

๐Ÿฉน $g->ntfsfix ($device [, clearbadsectors => $clearbadsectors]);

This command repairs some fundamental NTFS inconsistencies, resets the NTFS journal file, and schedules an NTFS consistency check for the first boot into Windows. It's a lil tune-up ๐Ÿ”ง

This is not an equivalent of Windows chkdsk. It does not scan the filesystem for inconsistencies. Set your expectations accordingly, bestie.

The optional "clearbadsectors" flag clears the list of bad sectors. This is useful after cloning a disk with bad sectors to a new disk.

This function depends on the feature "ntfs3g". See also $g->feature-available.

๐Ÿ“ $g->ntfsresize ($device [, size => $size] [, force => $force]);

This command resizes an NTFS filesystem, expanding or shrinking it to the size of the underlying device.

$g->ntfsresize ($device [, size => $size] [, force => $force]);

The optional parameters are:

  • "size" โ€” the new size (in bytes) of the filesystem. If omitted, the filesystem is resized to fit the container (eg. partition).
  • "force" โ€” if this option is true, then force the resize of the filesystem even if the filesystem is marked as requiring a consistency check.
After the resize operation, the filesystem is always marked as requiring a consistency check (for safety). You have to boot into Windows to perform this check and clear this condition. If you don't set the "force" option then it is not possible to call $g->ntfsresize multiple times on a single filesystem without booting into Windows between each resize. Yeah. That's the deal ๐Ÿ˜ค

See also ntfsresize(8).

This function depends on the feature "ntfsprogs". See also $g->feature-available.

๐Ÿชž $g->ntfsresize_opts ($device [, size => $size] [, force => $force]);

This is an alias of "ntfsresize". Same energy, different name ๐Ÿ’ซ

๐Ÿ“ $g->ntfsresize_size ($device, $size);

This command is the same as $g->ntfsresize except that it lets you specify the new size (in bytes) explicitly.

This function depends on the feature "ntfsprogs". See also $g->feature-available.

This function is deprecated. In new code, use the "ntfsresize" call instead.

Deprecated functions will not be removed from the API, but the fact that they are deprecated indicates that there are problems with correct use of these functions. So like, read the room ๐Ÿซ 

๐ŸŒฑ $g->parse_environment ();

Parse the program's environment and set flags in the handle accordingly. For example if LIBGUESTFS_DEBUG=1 then the 'verbose' flag is set in the handle. It's literally just reading the room (the room being your env) ๐ŸŒธ

Most programs do not need to call this. It is done implicitly when you call $g->create.

See "ENVIRONMENT VARIABLES" in guestfs(3) for a list of environment variables that can affect libguestfs handles. See also "guestfs_create_flags" in guestfs(3), and $g->parse_environment_list.

๐Ÿงพ $g->parse_environment_list (\@environment);

Parse the list of strings in the argument "environment" and set flags in the handle accordingly. For example if LIBGUESTFS_DEBUG=1 is a string in the list, then the 'verbose' flag is set in the handle.

This is the same as $g->parse_environment except that it parses an explicit list of strings instead of the program's environment. DIY vibes ๐Ÿ› ๏ธ

๐Ÿงฑ $g->part_add ($device, $prlogex, $startsect, $endsect);

This command adds a partition to "device". If there is no partition table on the device, call $g->part_init first. Order matters, bestie โœจ

$g->part_add ($device, $prlogex, $startsect, $endsect);

The "prlogex" parameter is the type of partition. Normally you should pass p or primary here, but MBR partition tables also support l (or logical) and e (or extended) partition types. Pick your fighter ๐ŸฅŠ

โ€ฆand startsect / endsect are literally the start and the end of the partition, measured in sectors ๐ŸŽ€ and endsect can be negative, which means it counts backwards from the end of the disk (-1 is the last sector). cute, right?

Ok but here's the tea โ˜• โ€” making a partition that covers the whole disk is not so easy. Use $g->part_disk for that, bestie.


$g->part_del ($device, $partnum);

This one deletes the partition numbered partnum on device. bye bestie ๐Ÿ‘‹

heads up: in the case of MBR partitioning, deleting an extended partition also deletes any logical partitions it contains. so likeโ€ฆ collateral deletion, no cap ๐Ÿ’€
$g->part_disk ($device, $parttype);

This is simply a combo move โ€” $g->part_init followed by $g->part_add โ€” creating a single primary partition that covers the whole disk โœจ one and done.

parttype is the partition table type, usually mbr or gpt, but the other possible values are all described in $g->part_init (keep scrolling, iykyk).

$g->part_expand_gpt ($device);

Moves the backup GPT data structures to the end of the disk ๐Ÿฆ‹ super useful when you're doing an in-place image expand, because disk space after the backup GPT header is justโ€ฆ not usable. This is equivalent to sgdisk -e.

See also sgdisk(8).

this function depends on the feature gdisk. See also $g->feature-available. ๐ŸŒธ
$bootable = $g->part_get_bootable ($device, $partnum);

Returns true if the partition partnum on device has the bootable flag set ๐Ÿ‘‘ slay.

See also $g->part_set_bootable.

$guid = $g->part_get_disk_guid ($device);

Returns the disk identifier (GUID) of a GPT-partitioned device. And for any other partition types? Behaviour is undefined, so like, don't ๐Ÿ™ˆ.

$attributes = $g->part_get_gpt_attributes ($device, $partnum);

Returns the attribute flags of the numbered GPT partition partnum. If it's an MBR partition you get an error, sorry babe ๐Ÿ’….

$guid = $g->part_get_gpt_guid ($device, $partnum);

Returns the GUID of the numbered GPT partition partnum โœจ.

$guid = $g->part_get_gpt_type ($device, $partnum);

Returns the type GUID of the numbered GPT partition partnum ๐ŸŽ€.

$idbyte = $g->part_get_mbr_id ($device, $partnum);

Returns the MBR type byte (also known as the ID byte) from the numbered partition partnum.

note that only MBR (old DOS-style) partitions have type bytes. for other partition table types you get undefined results (see $g->part_get_parttype). lowkey a warning โš ๏ธ
$partitiontype = $g->part_get_mbr_part_type ($device, $partnum);

Returns the partition type of the MBR partition numbered partnum on device device.

It returns primary, logical, or extended. pick your fighter ๐Ÿ’€

$name = $g->part_get_name ($device, $partnum);

Gets the partition name on partition numbered partnum on device device. Note that partitions are numbered from 1 ๐Ÿ‘€.

The partition name can only be read on certain types of partition table โ€” this works on gpt but not on mbr partitions ๐Ÿซถ.

$parttype = $g->part_get_parttype ($device);

This command examines the partition table on device and returns the partition table type (format) being used ๐Ÿ”.

Common return values include: msdos (a DOS/Windows style MBR partition table) and gpt (a GPT/EFI-style partition table). Other values are possible, although unusual. See $g->part_init for a full list โญ.

$g->part_init ($device, $parttype);

This creates an empty partition table on device of one of the partition types listed below โœจ Usually parttype should be either msdos or gpt (for large disks).

Initially there are no partitions โ€” empty, blank, a fresh start ๐Ÿ’… Following this, you should call $g->part_add for each partition you need.

Possible values for parttype are:

  • efi, gpt โ€” Intel EFI / GPT partition table. This is recommended for >= 2 TB partitions that will be accessed from Linux and Intel-based Mac OS X. It also has limited backwards compatibility with the mbr format ๐Ÿ‘‘
  • mbr, msdos โ€” The standard PC "Master Boot Record" (MBR) format used by MS-DOS and Windows. This partition type will only work for device sizes up to 2 TB. For large disks we recommend using gpt ๐Ÿฆ‹

Other partition table types that may work but are not supported include:

  • aix โ€” AIX disk labels.
  • amiga, rdb โ€” Amiga "Rigid Disk Block" format.
  • bsd โ€” BSD disk labels.
  • dasd โ€” DASD, used on IBM mainframes.
  • dvh โ€” MIPS/SGI volumes.
  • mac โ€” Old Mac partition format. Modern Macs use gpt.
  • pc98 โ€” NEC PC-98 format, common in Japan apparently ๐Ÿ‡ฏ๐Ÿ‡ต.
  • sun โ€” Sun disk labels.
@partitions = $g->part_list ($device);

This command parses the partition table on device and returns the list of partitions found ๐ŸŽ€.

The fields in the returned structure are:

  • part_num โ€” partition number, counting from 1.
  • part_start โ€” start of the partition in bytes. To get sectors you have to divide by the device's sector size, see $g->blockdev_getss.
  • part_end โ€” end of the partition in bytes.
  • part_size โ€” size of the partition in bytes.
$g->part_resize ($device, $partnum, $endsect);

Resizes the partition numbered partnum on device by moving the end position โœจ.

important: this does not modify any filesystem present in the partition. If you want to do that, you'll need filesystem resizing commands like $g->resize2fs ๐Ÿ“

When growing a partition you'll want to grow the filesystem afterwards โ€” but when shrinking, you need to shrink the filesystem before the partition. order matters, bestie, always ๐Ÿซถ

$g->part_set_bootable ($device, $partnum, $bootable);

This sets the bootable flag on partition numbered partnum on device device. Note that partitions are numbered from 1 ๐Ÿ‘€.

The bootable flag is used by some operating systems (notably Windows) to figure out which partition to boot from. It is by no means universally recognized โ€” so like, don't count on it ๐Ÿ’…

$g->part_set_disk_guid ($device, $guid);

Set the disk identifier (GUID) of a GPT-partitioned device to guid. Returns an error if the partition table of device isn't GPT, or if guid isn't a valid GUID ๐Ÿ™ˆ.

$g->part_set_disk_guid_random ($device);

Set the disk identifier (GUID) of a GPT-partitioned device to a randomly generated value ๐ŸŽฒ. Returns an error if the partition table of device isn't GPT.

$g->part_set_gpt_attributes ($device, $partnum, $attributes);

Set the attribute flags of the numbered GPT partition partnum to attributes. Returns an error if the partition table of device isn't GPT.

See https://en.wikipedia.org/wiki/GUID_Partition_Table#Partition_entries for a useful list of partition attributes ๐Ÿ‘‘.

$g->part_set_gpt_guid ($device, $partnum, $guid);

Set the GUID of the numbered GPT partition partnum to guid. Returns an error if the partition table of device isn't GPT, or if guid isn't a valid GUID โœจ.

$g->part_set_gpt_type ($device, $partnum, $guid);

Set the type GUID of the numbered GPT partition partnum to guid. Returns an error if the partition table of device isn't GPT, or if guid isn't a valid GUID ๐ŸŒธ.

See https://en.wikipedia.org/wiki/GUID_Partition_Table#Partition_type_GUIDs for a useful list of type GUIDs ๐Ÿ’–.

$g->part_set_mbr_id ($device, $partnum, $idbyte);

Sets the MBR type byte (also known as the ID byte) of the numbered partition partnum to idbyte. Note that the type bytes quoted in most documentation are in fact hexadecimal numbers, but they're usually documented without any leading 0x, which might be confusing ๐Ÿ™ˆ โ€” so like, be careful.

note that only MBR (old DOS-style) partitions have type bytes. for other partition table types you get undefined results (see $g->part_get_parttype). โš ๏ธ
$g->part_set_name ($device, $partnum, $name);

Sets the partition name on partition numbered partnum on device device. Note that partitions are numbered from 1 ๐Ÿ‘€.

The partition name can only be set on certain types of partition table โ€” this works on gpt but not on mbr partitions ๐Ÿซถ.

$device = $g->part_to_dev ($partition);

This function takes a partition name (eg. /dev/sdb1) and removes the partition number, returning the device name (eg. /dev/sdb) โœจ. math, but make it fashion.

The named partition must exist โ€” for example, as a string returned from $g->list_partitions.

See also $g->part_to_partnum, $g->device_index ๐ŸŽ€.

$partnum = $g->part_to_partnum ($partition);

This function takes a partition name (eg. /dev/sdb1) and returns the partition number (eg. 1) ๐Ÿ”ข.

The named partition must exist โ€” for example, as a string returned from $g->list_partitions.

See also $g->part_to_dev ๐Ÿ’œ.

$g->ping_daemon ();

This is a test probe into the guestfs daemon running inside the libguestfs appliance ๐Ÿฉบ. Calling this function checks that the daemon responds to the ping message, without affecting the daemon or attached block device(s) in any other way. it's giving "you up?" text at 3am, but respectful ๐Ÿค™

$content = $g->pread ($path, $count, $offset);

This command lets you read part of a file ๐Ÿ“–. It reads count bytes of the file, starting at offset, from file path.

It may read fewer bytes than requested. For further details see the pread(2) system call.

See also $g->pwrite, $g->pread_device โœจ.

because of the message protocol, there is a transfer limit of somewhere between 2MB and 4MB. See "PROTOCOL LIMITS" in guestfs(3) ๐Ÿซ 
$content = $g->pread_device ($device, $count, $offset);

This command lets you read part of a block device ๐Ÿ’ฝ. It reads count bytes of device, starting at offset.

It may read fewer bytes than requested. For further details see the pread(2) system call.

See also $g->pread โœจ.

same deal as above: because of the message protocol, there is a transfer limit of somewhere between 2MB and 4MB. See "PROTOCOL LIMITS" in guestfs(3) ๐ŸŒธ
$g->pvchange_uuid ($device);

Generate a new random UUID for the physical volume device ๐ŸŽฒ iconic.

this function depends on the feature lvm2. See also $g->feature-available ๐Ÿ’…
$g->pvchange_uuid_all ();

Generate new random UUIDs for all physical volumes ๐Ÿ”ฅ all of them, no survivors.

this function depends on the feature lvm2. See also $g->feature-available ๐Ÿ’…
$g->pvcreate ($device);

This creates an LVM physical volume on the named device, where device should usually be a partition name such as /dev/sda1 ๐Ÿงš.

this function depends on the feature lvm2. See also $g->feature-available ๐Ÿซถ

$g->pvremove ($device);

Okay so this one wipes a physical volume called device so that LVM will no longer recognise it. Like, it's giving "you don't exist to me" and honestly? Slay. ๐Ÿ’…

The implementation uses the pvremove(8) command, and heads up bestie: that command refuses to wipe physical volumes that contain any volume groups, so you have to remove those first. It will not do the emotional labour for you. ๐Ÿซถ

This function depends on the feature lvm2. See also $g->feature-available.


$g->pvresize ($device);

This resizes (expands or shrinks) an existing LVM physical volume so it matches the new size of the underlying device. Glow-up or shrink-down, either way it's matching the vibe of the device underneath. โœจ

This function depends on the feature lvm2. See also $g->feature-available.


$g->pvresize_size ($device, $size);

Literally the same as $g->pvresize except this one lets you specify the new size (in bytes) explicitly. No guessing, you're the main character and you pick the number. ๐Ÿ”ข

This function depends on the feature lvm2. See also $g->feature-available.


@physvols = $g->pvs ();

Lists all the physical volumes detected. This is the equivalent of the pvs(8) command.

It returns a list of just the device names that contain PVs (eg. /dev/sda2).

See also $g->pvs_full.

This function depends on the feature lvm2. See also $g->feature-available.


@physvols = $g->pvs_full ();

Also lists all the physical volumes detected, same equivalent of the pvs(8) command as above โ€” but the "full" version includes all fields. It's the director's cut. ๐ŸŽฌ

This function depends on the feature lvm2. See also $g->feature-available.


$uuid = $g->pvuuid ($device);

This command returns the UUID of the LVM PV device. That's it, that's the whole thing. Short and iconic. ๐Ÿ’œ


$nbytes = $g->pwrite ($path, $content, $offset);

This command writes to part of a file. It writes the data buffer content to the file path starting at offset offset.

This command implements the pwrite(2) system call, and like that system call it may not write the full data requested. The return value is the number of bytes that were actually written to the file. This could even be 0, although short writes are unlikely for regular files in ordinary circumstances.

See also $g->pread, $g->pwrite_device.

Because of the message protocol, there is a transfer limit of somewhere between 2MB and 4MB. See the PROTOCOL LIMITS section in guestfs(3).

$nbytes = $g->pwrite_device ($device, $content, $offset);

This command writes to part of a device. It writes the data buffer content to device starting at offset offset.

This command implements the pwrite(2) system call, and like that system call it may not write the full data requested (although short writes to disk devices and partitions are probably impossible with standard Linux kernels). Ngl, the kernel's got your back on this one.

See also $g->pwrite.

Because of the message protocol, there is a transfer limit of somewhere between 2MB and 4MB. See the PROTOCOL LIMITS section in guestfs(3).

$content = $g->read_file ($path);

This call returns the contents of the file path as a buffer. ๐Ÿ“„

Unlike $g->cat, this function can correctly handle files that contain embedded ASCII NUL characters. That's the whole flex, and it's a good one.


@lines = $g->read_lines ($path);

Returns the contents of the file named path.

The file contents come back as a list of lines. Trailing LF and CRLF character sequences are not returned.

Note that this function cannot correctly handle binary files (specifically, files containing "\0" character which is treated as end of string). For those you need to use the $g->read_file function and split the buffer into lines yourself. DIY era. ๐Ÿ› ๏ธ

@entries = $g->readdir ($dir);

This returns the list of directory entries in directory dir.

All entries in the directory are returned, including . and ... The entries are not sorted, but returned in the same order as the underlying filesystem. Chaos order, honestly, but we respect it.

Also this call returns basic file type information about each file. The "ftyp" field will contain one of the following characters:

  • 'b' โ€” Block special
  • 'c' โ€” Char special
  • 'd' โ€” Directory
  • 'f' โ€” FIFO (named pipe)
  • 'l' โ€” Symbolic link
  • 'r' โ€” Regular file
  • 's' โ€” Socket
  • 'u' โ€” Unknown file type
  • '?' โ€” The readdir(3) call returned a "d_type" field with an unexpected value

This function is primarily intended for use by programs. To get a simple list of names, use $g->ls. To get a printable directory for human consumption, use $g->ll. Choose your fighter. ๐ŸŽ€


$link = $g->readlink ($path);

This command reads the target of a symbolic link. Simple, elegant, no notes. ๐ŸŒธ


@links = $g->readlinklist ($path, \@names);

This call lets you do a "readlink" operation on multiple files, where all files are in the directory path. names is the list of files from this directory.

On return you get a list of strings, with a one-to-one correspondence to the names list. Each string is the value of the symbolic link.

If the readlink(2) operation fails on any name, then the corresponding result string is the empty string "". However the whole operation is completed even if there were readlink(2) errors, and so you can call this function with names where you don't know if they are symbolic links already (albeit slightly less efficient). Honestly kind of a forgiving queen of an API. ๐Ÿ‘‘

This call is intended for programs that want to efficiently list a directory contents without making many round-trips.


$rpath = $g->realpath ($path);

Return the canonicalized absolute pathname of path. The returned path has no ., .. or symbolic link path elements. Clean, filtered, no clutter โ€” it's giving clears throat character development. โœจ


$g->remount ($mountpoint [, rw => $rw]);

This call lets you change the "rw" (readonly/read-write) flag on an already mounted filesystem at mountpoint, converting a readonly filesystem to be read-write, or vice-versa. Flip the switch, bestie. ๐Ÿ”„

Note that at the moment you must supply the "optional" rw parameter. In future we may allow other flags to be adjusted.

$g->remove_drive ($label);

This call does nothing and returns an error. Lmaooo it's literally the "no thoughts, head empty, also error" function. ๐Ÿ’€

This function is deprecated. There is no replacement. Consult the API documentation in guestfs(3) for further information.

Deprecated functions will not be removed from the API, but the fact that they are deprecated indicates that there are problems with correct use of these functions. So like, don't.

$g->removexattr ($xattr, $path);

This call removes the extended attribute named xattr of the file path. ๐Ÿงน

See also: $g->lremovexattr, attr(5).

This function depends on the feature linuxxattrs. See also $g->feature-available.


$g->rename ($oldpath, $newpath);

Rename a file to a new place on the same filesystem. This is the same as the Linux rename(2) system call. In most cases you are better to use $g->mv instead โ€” just a lil tip from me to you. ๐Ÿซถ


$g->resize2fs ($device);

This resizes an ext2, ext3 or ext4 filesystem to match the size of the underlying device. Cinderella-core: the filesystem fits the device, periodt. ๐Ÿ‘‘

See also the RESIZE2FS ERRORS section in guestfs(3).


$g->resize2fs_M ($device);

This command is the same as $g->resize2fs, but the filesystem is resized to its minimum size. This works like the -M option to the resize2fs(8) command.

To get the resulting size of the filesystem you should call $g->tune2fs_l and read the "Block size" and "Block count" values. These two numbers, multiplied together, give the resulting size of the minimal filesystem in bytes. Math girlies rise. ๐Ÿงฎ

See also the RESIZE2FS ERRORS section in guestfs(3).


$g->resize2fs_size ($device, $size);

This command is the same as $g->resize2fs except that it allows you to specify the new size (in bytes) explicitly. You're the algorithm now. ๐Ÿ’…

See also the RESIZE2FS ERRORS section in guestfs(3).


$g->rm ($path);

Remove the single file path. That's it. One file. No entourage. ๐Ÿ’€


$g->rm_f ($path);

Remove the file path.

If the file doesn't exist, that error is ignored. (Other errors, eg. I/O errors or bad paths, are not ignored.) It's giving "no file? no problem" but only for that one specific case. ๐ŸŒˆ

This call cannot remove directories. Use $g->rmdir to remove an empty directory, or $g->rm_rf to remove directories recursively.


$g->rm_rf ($path);

Remove the file or directory path, recursively removing the contents if it's a directory. This is like the "rm -rf" shell command. Unhinged behaviour, iconic legacy, use with respect. ๐Ÿ”ฅ


$g->rmdir ($path);

Remove the single directory path. One directory, one job, no recursion. She's focused. ๐ŸŽฏ


$g->rmmountpoint ($exemptpath);

This call removes a mountpoint that was previously created with $g->mkmountpoint. See $g->mkmountpoint for full details. Cleanup era. ๐Ÿงน


$g->rsync ($src, $dest [, archive => $archive] [, deletedest => $deletedest]);

This call may be used to copy or synchronize two directories under the same libguestfs handle. This uses the rsync(1) program which uses a fast algorithm that avoids copying files unnecessarily. Efficient queen behaviour, no notes. โœจ

src and dest are the source and destination directories. Files are copied from src to dest.

The optional arguments are:

  • "archive" โ€” Turns on archive mode. This is the same as passing the --archive flag to "rsync".
  • "deletedest" โ€” Delete files at the destination that do not exist at the source. Ruthless. ๐Ÿ—‘๏ธ

This function depends on the feature rsync. See also $g->feature-available.


$g->rsync_in ($remote, $dest [, archive => $archive] [, deletedest => $deletedest]);

This call may be used to copy or synchronize the filesystem on the host or on a remote computer with the filesystem within libguestfs. This uses the rsync(1) program which uses a fast algorithm that avoids copying files unnecessarily. Same efficient algorithm, now travelling internationally. โœˆ๏ธ

This call only works if the network is enabled. See $g->set_network or the --network option to various tools like guestfish(1).

Files are copied from the remote server and directory specified by remote to the destination directory dest.

The format of the remote server string is defined by rsync(1). Note that there is no way to supply a password or passphrase, so the target must be set up not to require one. No secret handshakes available, sadly. ๐Ÿ™ˆ

The optional arguments are the same as those of $g->rsync.

This function depends on the feature rsync. See also $g->feature-available.


$g->rsync_out ($src, $remote [, archive => $archive] [, deletedest => $deletedest]);

This call may be used to copy or synchronize the filesystem within libguestfs with a filesystem on the host or on a remote computer. This uses the rsync(1) program which uses a fast algorithm that avoids copying files unnecessarily. Same algorithm, opposite direction โ€” she's versatile. ๐Ÿ’œ

This call only works if the network is enabled. See $g->set_network or the --network option to various tools like guestfish(1).

Files are copied from the source directory src to the remote server and directory specified by remote.

Zaddy, the remote server string's format is defined by rsync(1) ๐Ÿ‘€ โ€” and heads up, there's no way to supply a password or passphrase, so the target has to be set up so it doesn't need one. No sneaky password field, bestie, it does not exist ๐Ÿ’€

The optional arguments are literally the same ones as $g->rsync.

Globbing does not happen on the src parameter. So in programs that use the API directly you've gotta expand wildcards yourself (peek $g->glob_expand). In guestfish you can just use the glob command (see "glob" in guestfish(1)), like:

><fs> glob rsync-out /* rsync://remote/

This function depends on the feature "rsync". See also $g->feature-available. ๐Ÿฆ‹


  • $g->scrub_device ($device); โ€” writes patterns over device so data retrieval becomes way more difficult ๐Ÿ™ˆ. It's an interface to the scrub(1) program โ€” go read that manual page for the deets. Depends on the feature "scrub". See also $g->feature-available.
  • $g->scrub_file ($file); โ€” writes patterns over a file to make data retrieval more difficult. Important: the file is removed after scrubbing ๐Ÿซง. Also an interface to scrub(1) โ€” see that manual page for more details. Depends on the feature "scrub". See also $g->feature-available.
  • $g->scrub_freespace ($dir); โ€” creates the directory dir and then fills it with files until the filesystem is full, scrubs the files as for $g->scrub_file, and deletes them ๐Ÿงน. The whole point is scrubbing any free space on the partition containing dir. Interface to scrub(1) again โ€” see that manual page for more details. Depends on the feature "scrub". See also $g->feature-available.
  • $g->selinux_relabel ($specfile, $path [, force => $force]); โ€” SELinux relabel of parts of the filesystem ๐Ÿ‘‘. The specfile parameter controls which policy spec file gets used โ€” you have to parse /etc/selinux/config to find the correct SELinux policy and then pass the spec file, usually: /etc/selinux/ + selinuxtype + /contexts/files/file_contexts. The required path parameter is the top level directory where relabelling starts; normally you pass path as / to relabel the whole guest filesystem. The optional force boolean controls whether the context is reset for customizable files, and also whether the user, role and range parts of the file context is changed. Depends on the feature "selinuxrelabel". See also $g->feature-available.
This function is deprecated. In new code, use the setfiles call instead. Deprecated functions will not be removed from the API, but the fact that they are deprecated indicates that there are problems with correct use of these functions. ๐Ÿ˜ญ
  • $g->set_append ($append); โ€” used to add extra options to the libguestfs appliance kernel command line ๐ŸŒธ. The default is NULL unless it's overridden by setting the LIBGUESTFS_APPEND environment variable. Setting append to NULL means no additional options are passed (libguestfs always adds a few of its own, obviously ๐Ÿ’…).
  • $g->set_attach_method ($backend); โ€” sets the method libguestfs uses to connect to the backend guestfsd daemon. See "BACKEND" in guestfs(3).
Deprecated, bestie. In new code, use the set_backend call instead. Deprecated functions will not be removed from the API, but the fact that they are deprecated indicates that there are problems with correct use of these functions. ๐Ÿ™ˆ
  • $g->set_autosync ($autosync); โ€” if autosync is true, this enables autosync โœจ. Libguestfs will make a best effort attempt to make filesystems consistent and synchronized when the handle is closed (also if the program exits without closing handles โ€” yeah, even then ๐Ÿ‘€). This is enabled by default (since libguestfs 1.5.24, previously it was disabled by default).
  • $g->set_backend ($backend); โ€” sets the method libguestfs uses to connect to the backend guestfsd daemon ๐ŸŽ€. Fun lore: this handle property was previously called the "attach method". See "BACKEND" in guestfs(3).
  • $g->set_backend_setting ($name, $val); โ€” appends name=value to the backend settings string list ๐Ÿ“. BUT if a string already exists matching name or beginning with name=, then that setting gets replaced. See "BACKEND" in guestfs(3), "BACKEND SETTINGS" in guestfs(3).
  • $g->set_backend_settings (\@settings); โ€” set a list of zero or more settings which are passed through to the current backend ๐Ÿฆ‹. Each setting is a string interpreted in a backend-specific way, or ignored if the backend doesn't understand it. The default value is an empty list, unless the environment variable LIBGUESTFS_BACKEND_SETTINGS was set when the handle was created โ€” that env var contains a colon-separated list of settings. This call replaces all backend settings. Wanna replace just one? See $g->set_backend_setting. Wanna clear just one? See $g->clear_backend_setting. See "BACKEND" in guestfs(3), "BACKEND SETTINGS" in guestfs(3).
  • $g->set_cachedir ($cachedir); โ€” set the directory the handle uses to store the appliance cache, when using a supermin appliance ๐Ÿงš. The appliance is cached and shared between all handles which have the same effective user ID. The environment variables LIBGUESTFS_CACHEDIR and TMPDIR control the default value: if LIBGUESTFS_CACHEDIR is set, then that's the default. Else if TMPDIR is set, then that's the default. Else /var/tmp is the default. The way that's a whole priority chain ๐Ÿ˜Œ
  • $g->set_direct ($direct); โ€” if the direct appliance mode flag is enabled, then stdin and stdout are passed directly through to the appliance once it's launched ๐Ÿ‘€. One consequence of this is that log messages aren't caught by the library and handled by $g->set_log_message_callback, but go straight to stdout. You probably don't want to use this unless you know what you're doing โ€” fr fr. The default is disabled.
Deprecated. In new code, use the internal_get_console_socket call instead. Deprecated functions will not be removed from the API, but the fact that they are deprecated indicates that there are problems with correct use of these functions. ๐Ÿ’€
  • $g->set_e2attrs ($file, $attrs [, clear => $clear]); โ€” sets or clears the file attributes attrs associated with the inode file ๐ŸŒˆ. attrs is a string of characters representing file attributes โ€” see $g->get_e2attrs for a list of possible attributes, and note that not all attributes can be changed. If the optional boolean clear is not present or is false, then the attrs listed are set in the inode. If clear is true, then the attrs listed are cleared in the inode. In both cases, other attributes not present in the attrs string are left unchanged ๐Ÿ™Œ. These attributes are only present when the file is located on an ext2/3/4 filesystem โ€” using this call on other filesystem types will result in an error โš ๏ธ.
  • $g->set_e2generation ($file, $generation); โ€” sets the ext2 file generation of a file. See $g->get_e2generation.
  • $g->set_e2label ($device, $label); โ€” sets the ext2/3/4 filesystem label of the filesystem on device to label ๐Ÿท๏ธ. Filesystem labels are limited to 16 characters. You can use either $g->tune2fs_l or $g->get_e2label to return the existing label on a filesystem.
Deprecated. In new code, use the set_label call instead. Deprecated functions will not be removed from the API, but the fact that they are deprecated indicates that there are problems with correct use of these functions. ๐Ÿ˜ญ
  • $g->set_e2uuid ($device, $uuid); โ€” sets the ext2/3/4 filesystem UUID of the filesystem on device to uuid ๐Ÿ†”. The format of the UUID and alternatives such as "clear", "random" and "time" are described in the tune2fs(8) manpage. You can use $g->vfs_uuid to return the existing UUID of a filesystem.
Deprecated. In new code, use the set_uuid call instead. Deprecated functions will not be removed from the API, but the fact that they are deprecated indicates that there are problems with correct use of these functions. ๐Ÿซ 
  • $g->set_hv ($hv); โ€” set the hypervisor binary that we will use ๐Ÿ”ฅ. The hypervisor depends on the backend, but is usually the location of the qemu/KVM hypervisor. You can also override this by setting the LIBGUESTFS_HV environment variable.
Okay so this one's got a timing thing ๐Ÿ‘‘ โ€” you should call this function as early as possible after creating the handle. Why? Because some pre-launch operations depend on testing qemu features (by running qemu -help). If the qemu binary changes, we don't retest features, and so you might see inconsistent results ๐Ÿ˜ฌ. Using the environment variable LIBGUESTFS_HV is safest of all since that picks the qemu binary at the same time as the handle is created. Iconic behaviour, honestly.
  • $g->set_identifier ($identifier); โ€” an informative string which the caller may optionally set in the handle ๐ŸŽ€. It's printed in various places, letting the current handle be identified in debugging output. One important place is when tracing is enabled. If the identifier string is not an empty string, then trace messages change from this:
libguestfs: trace: get_tmpdir
libguestfs: trace: get_tmpdir = "/tmp"

to this:

libguestfs: trace: ID: get_tmpdir
libguestfs: trace: ID: get_tmpdir = "/tmp"

where ID is the identifier string set by this call โœจ. The identifier must only contain alphanumeric ASCII characters, underscore and minus sign. The default is the empty string. See also $g->set_program, $g->set_trace, $g->get_identifier.

  • $g->set_label ($mountable, $label); โ€” set the filesystem label on mountable to label ๐Ÿท๏ธ. Only some filesystem types support labels, and libguestfs supports setting labels on only a subset of these:
    • ext2, ext3, ext4 โ€” Labels are limited to 16 bytes.
    • NTFS โ€” Labels are limited to 128 unicode characters.
    • XFS โ€” The label is limited to 12 bytes. The filesystem must not be mounted when trying to set the label โš ๏ธ.
  • btrfs โ€” okay so the label is capped at 255 bytes, and some characters are literally not allowed, periodt. Setting the label on a btrfs subvolume will set the label on its parent filesystem. The filesystem must not be mounted when trying to set the label.
  • fat โ€” label is limited to 11 bytes. Short and sweet ๐ŸŽ€.
  • swap โ€” label is limited to 16 bytes.

If there is no support for changing the label for the type of the specified filesystem, set_label will fail and set errno as ENOTSUP. To read the label on a filesystem, call $g->vfs_label.


๐Ÿ’… $g->set_libvirt_requested_credential ($index, $cred);

After requesting the index'th credential from the user, call this function to pass the answer back to libvirt. Bestie, this is the handoff moment ๐Ÿซถ.

See "LIBVIRT AUTHENTICATION" in guestfs(3) for documentation and example code.

โœจ $g->set_libvirt_supported_credentials (\@creds);

Call this function before setting an event handler for "GUESTFS_EVENT_LIBVIRT_AUTH", to supply the list of credential types that the program knows how to process.

The creds list must be a non-empty list of strings. Possible strings are:

  • "username"
  • "authname"
  • "language"
  • "cnonce"
  • "passphrase"
  • "echoprompt"
  • "noechoprompt"
  • "realm"
  • "external"

See libvirt documentation for the meaning of these credential types.

See "LIBVIRT AUTHENTICATION" in guestfs(3) for documentation and example code.

๐Ÿง  $g->set_memsize ($memsize);

This sets the memory size in megabytes allocated to the hypervisor. This only has any effect if called before $g->launch.

You can also change this by setting the environment variable LIBGUESTFS_MEMSIZE before the handle is created.

For more information on the architecture of libguestfs, see guestfs(3).

๐ŸŒ $g->set_network ($network);

If network is true, then the network is enabled in the libguestfs appliance. The default is false.

This affects whether commands are able to access the network (see "RUNNING COMMANDS" in guestfs(3)).

You must call this before calling $g->launch, otherwise it has no effect.

๐Ÿ›ฃ๏ธ $g->set_path ($searchpath);

Set the path that libguestfs searches for kernel and initrd.img.

The default is $libdir/guestfs unless overridden by setting LIBGUESTFS_PATH environment variable.

Setting path to NULL restores the default path.

๐ŸŽ€ $g->set_pgroup ($pgroup);

If pgroup is true, child processes are placed into their own process group.

The practical upshot of this is that signals like SIGINT (from users pressing ^C) won't be received by the child process.

The default for this flag is false, because usually you want ^C to kill the subprocess. Guestfish sets this flag to true when used interactively, so that ^C can cancel long-running commands gracefully (see $g->user_cancel).

๐Ÿท๏ธ $g->set_program ($program);

Set the program name. This is an informative string which the main program may optionally set in the handle.

When the handle is created, the program name in the handle is set to the basename from argv[0]. The program name can never be NULL.

๐Ÿ’ป $g->set_qemu ($hv);

Set the hypervisor binary (usually qemu) that we will use.

You can also override this by setting the LIBGUESTFS_HV environment variable.

Setting hv to NULL restores the default qemu binary.

Note that you should call this function as early as possible after creating the handle. This is because some pre-launch operations depend on testing qemu features (by running qemu -help). If the qemu binary changes, we don't retest features, and so you might see inconsistent results. Using the environment variable LIBGUESTFS_HV is safest of all since that picks the qemu binary at the same time as the handle is created.

This function is deprecated. In new code, use the set_hv call instead.

Deprecated functions will not be removed from the API, but the fact that they are deprecated indicates that there are problems with correct use of these functions.

๐Ÿš‘ $g->set_recovery_proc ($recoveryproc);

If this is called with the parameter false then $g->launch does not create a recovery process. The purpose of the recovery process is to stop runaway hypervisor processes in the case where the main program aborts abruptly.

This only has any effect if called before $g->launch, and the default is true.

About the only time when you would want to disable this is if the main process will fork itself into the background ("daemonize" itself). In this case the recovery process thinks that the main program has disappeared and so kills the hypervisor, which is not very helpful.

๐Ÿ” $g->set_selinux ($selinux);

This sets the selinux flag that is passed to the appliance at boot time. The default is selinux=0 (disabled).

Note that if SELinux is enabled, it is always in Permissive mode (enforcing=0).

For more information on the architecture of libguestfs, see guestfs(3).

This function is deprecated. In new code, use the setfiles call instead.

Deprecated functions will not be removed from the API, but the fact that they are deprecated indicates that there are problems with correct use of these functions.

โšก $g->set_smp ($smp);

Change the number of virtual CPUs assigned to the appliance. The default is 1. Increasing this may improve performance, though often it has no effect.

This function must be called before $g->launch.

๐Ÿ—‚๏ธ $g->set_tmpdir ($tmpdir);

Set the directory used by the handle to store temporary files.

The environment variables LIBGUESTFS_TMPDIR and TMPDIR control the default value: If LIBGUESTFS_TMPDIR is set, then that is the default. Else if TMPDIR is set, then that is the default. Else /tmp is the default.

๐Ÿ” $g->set_trace ($trace);

If the command trace flag is set to 1, then libguestfs calls, parameters and return values are traced.

If you want to trace C API calls into libguestfs (and other libraries) then possibly a better way is to use the external ltrace(1) command.

Command traces are disabled unless the environment variable LIBGUESTFS_TRACE is defined and set to 1.

Trace messages are normally sent to stderr, unless you register a callback to send them somewhere else (see $g->set_event_callback).

๐Ÿ†” $g->set_uuid ($device, $uuid);

Set the filesystem UUID on device to uuid. If this fails and the errno is ENOTSUP, means that there is no support for changing the UUID for the type of the specified filesystem.

Only some filesystem types support setting UUIDs.

To read the UUID on a filesystem, call $g->vfs_uuid.

๐ŸŽฒ $g->set_uuid_random ($device);

Set the filesystem UUID on device to a random UUID. If this fails and the errno is ENOTSUP, means that there is no support for changing the UUID for the type of the specified filesystem.

Only some filesystem types support setting UUIDs.

To read the UUID on a filesystem, call $g->vfs_uuid.

๐Ÿ“ฃ $g->set_verbose ($verbose);

If verbose is true, this turns on verbose messages.

Verbose messages are disabled unless the environment variable LIBGUESTFS_DEBUG is defined and set to 1.

Verbose messages are normally sent to stderr, unless you register a callback to send them somewhere else (see $g->set_event_callback).

๐Ÿ›ก๏ธ $g->setcon ($context);

This sets the SELinux security context of the daemon to the string context.

See the documentation about SELINUX in guestfs(3).

This function depends on the feature selinux. See also $g->feature-available.

This function is deprecated. In new code, use the setfiles call instead.

Deprecated functions will not be removed from the API, but the fact that they are deprecated indicates that there are problems with correct use of these functions.

๐Ÿงพ $g->setfiles ($specfile, \@paths [, force => $force] [, excludes => $excludes]);

This invokes the SELinux setfiles command which is a low level tool used to relabel parts of the filesystem.

The specfile parameter controls the policy spec file used. You have to parse /etc/selinux/config to find the correct SELinux policy and then pass the spec file, usually: "/etc/selinux/" + selinuxtype + "/contexts/files/file_contexts".

The required paths parameter is the list of top level directories where relabelling starts. setfiles will only relabel up to filesystem boundaries so, for example, passing just / will relabel the whole root filesystem, but no other mounted filesystems. If the list is empty, setfiles is not called.

The optional force boolean controls whether the context is reset for customizable files, and also whether the user, role and range parts of the file context is changed.

The optional excludes list allows you to exclude parts of the directory tree by appending the setfiles -e option.

This function depends on the feature selinuxrelabel. See also $g->feature-available.

๐Ÿงท $g->setxattr ($xattr, $val, $vallen, $path);

This call sets the extended attribute named xattr of the file path to the value val (of length vallen). The value is arbitrary 8 bit data.

See also: $g->lsetxattr, attr(5).

This function depends on the feature linuxxattrs. See also $g->feature-available.

๐Ÿ’ฝ $g->sfdisk ($device, $cyls, $heads, $sectors, \@lines);

This is a direct interface to the sfdisk(8) program for creating partitions on block devices.

device should be a block device, for example /dev/sda.

cyls, heads and sectors are the number of cylinders, heads and sectors on the device, which are passed directly to sfdisk(8) as the -C, -H and -S parameters. If you pass 0 for any of these, then the corresponding parameter is omitted. Usually for โ€˜largeโ€™ disks, you can just pass 0 for these, but for small (floppy-sized) disks, sfdisk(8) (or rather, the kernel) cannot work out the right geometry and you will need to tell it.

lines is a list of lines that we feed to sfdisk(8). For more information refer to the sfdisk(8) manpage. ๐ŸŒˆ

To create a single partition that takes up the whole entire disk, bestie, you'd pass lines as a single-element list where that one element is the string "," โ€” yes, literally just a comma. That's the whole mood. โœจ

See also: $g->sfdisk_l, $g->sfdisk_N, $g->part_init

Sis, this one is deprecated. ๐Ÿšฉ In new code, use the part_add call instead.

Deprecated functions will not be removed from the API, but the fact that they are deprecated indicates that there are problems with correct use of these functions. (They still work, they're just not giving anymore. ๐Ÿ’…)

$g->sfdiskM ($device, \@lines);

This is the simplified interface to the $g->sfdisk command ๐ŸŽ€ โ€” partition sizes are specified in megabytes only (rounded to the nearest cylinder), and you don't need to pass the cyls, heads and sectors parameters, which were rarely if ever used anyway. Iconic laziness, honestly.

See also: $g->sfdisk, the sfdisk(8) manpage and $g->part_disk

Deprecated alert! ๐Ÿ˜ญ In new code, use the part_add call instead.

Deprecated functions will not be removed from the API, but the fact that they are deprecated indicates that there are problems with correct use of these functions.

$g->sfdisk_N ($device, $partnum, $cyls, $heads, $sectors, $line);

This runs the sfdisk(8) option to modify just the single partition "n" (quick note: "n" counts from 1, okay? not zero, don't come for me ๐Ÿซถ).

For the other parameters, see $g->sfdisk. You should usually pass 0 for the cyls/heads/sectors parameters. Like, just zero them out, bestie.

See also: $g->part_add

Deprecated, bestie. ๐Ÿ’€ In new code, use the part_add call instead.

Deprecated functions will not be removed from the API, but the fact that they are deprecated indicates that there are problems with correct use of these functions.

$partitions = $g->sfdisk_disk_geometry ($device);

This displays the disk geometry of "device" read from the partition table ๐ŸŒธ. Especially when the underlying block device has been resized, this can be different from the kernel's idea of the geometry (see $g->sfdisk_kernel_geometry). Two different vibes, lowkey.

The result is in human-readable format, and not designed to be parsed. So admire it, don't script against it, iykyk.

$partitions = $g->sfdisk_kernel_geometry ($device);

This displays the kernel's idea of the geometry of "device" ๐Ÿ‘‘.

The result is in human-readable format, and not designed to be parsed. Pretty to look at, not for your parser.

$partitions = $g->sfdisk_l ($device);

This displays the partition table on "device", in the human-readable output of the sfdisk(8) command. It is not intended to be parsed โ€” it's giving "for your eyes only" energy. ๐Ÿ™ˆ

See also: $g->part_list

Deprecated! In new code, use the part_list call instead. ๐Ÿฆ‹

Deprecated functions will not be removed from the API, but the fact that they are deprecated indicates that there are problems with correct use of these functions.

$output = $g->sh ($command);

This call runs a command from the guest filesystem via the guest's /bin/sh ๐Ÿš.

It's like $g->command, but passes the command to:

 /bin/sh -c "command"

Depending on the guest's shell, this usually results in wildcards being expanded, shell expressions being interpolated and so on. Glow-up for your command strings, fr.

All the provisos about $g->command apply to this call too. Same rules, same energy. ๐Ÿ’œ

@lines = $g->sh_lines ($command);

This is the same as $g->sh, but splits the result into a list of lines โœจ. One line per element, neat and tidy.

See also: $g->command_lines

$g->sh_out ($command, $output);

This is the same as $g->sh, but streams the output back, handling the case where the output from the command is larger than the protocol limit ๐ŸŒŠ. Big-output-friendly, no cap.

See also: $g->command_out

$g->shutdown ();

This is the opposite of $g->launch ๐Ÿ”„. It performs an orderly shutdown of the backend process(es). If the autosync flag is set (which is the default), then the disk image is synchronized. Clean exit, main character energy. ๐Ÿ’…

If the subprocess exits with an error, then this function will return an error, which should not be ignored โ€” it may indicate that the disk image could not be written out properly. So like, actually read the error, bestie. ๐Ÿ˜ญ

It is safe to call this multiple times. Extra calls are ignored. Spam it if you want, it's unbothered. ๐Ÿ˜Œ

This call does not close or free up the handle. You still need to call $g->close afterwards. Two separate steps, don't skip the second one.

$g->close will call this if you don't do it explicitly, but note that any errors are ignored in that case. So if you care about the errors, call it yourself, periodt. ๐ŸŽ€

$g->sleep ($secs);

Sleep for secs seconds ๐Ÿ˜ด. That's it, that's the whole thing. Nap time.

%statbuf = $g->stat ($path);

Returns file information for the given "path" ๐Ÿ“.

This is the same as the stat(2) system call.

Deprecated, babe. In new code, use the statns call instead. ๐Ÿ’€

Deprecated functions will not be removed from the API, but the fact that they are deprecated indicates that there are problems with correct use of these functions.

%statbuf = $g->statns ($path);

Returns file information for the given "path" โœจ.

This is the same as the stat(2) system call. Same facts, fresh function, we love an upgrade. ๐Ÿ’–

%statbuf = $g->statvfs ($path);

Returns file system statistics for any mounted file system. "path" should be a file or directory in the mounted file system โ€” typically it's the mount point itself, but it doesn't need to be ๐ŸŽ€.

This is the same as the statvfs(2) system call.

@stringsout = $g->strings ($path);

This runs the strings(1) command on a file and returns the list of printable strings found ๐Ÿ”โœจ.

The "strings" command has, in the past, had problems with parsing untrusted files. These are mitigated in the current version of libguestfs, but see "CVE-2014-8484" in guestfs(3). So like, stay aware, bestie. ๐Ÿšฉ

Because of the message protocol, there is a transfer limit of somewhere between 2MB and 4MB. See "PROTOCOL LIMITS" in guestfs(3). Don't try to pull a whole gigabyte through there, it's not gonna slay. ๐Ÿ’€

@stringsout = $g->strings_e ($encoding, $path);

This is like the $g->strings command, but lets you specify the encoding of strings that are looked for in the source file "path" ๐ŸŒˆ. Fancy.

Allowed encodings are:

  • s โ€” single 7-bit-byte characters like ASCII and the ASCII-compatible parts of ISO-8859-X (this is what $g->strings uses).
  • S โ€” single 8-bit-byte characters.
  • b โ€” 16-bit big endian strings such as those encoded in UTF-16BE or UCS-2BE.
  • l (lower case letter L) โ€” 16-bit little endian such as UTF-16LE and UCS-2LE. This is useful for examining binaries in Windows guests. ๐ŸชŸ
  • B โ€” 32-bit big endian such as UCS-4BE.
  • L โ€” 32-bit little endian such as UCS-4LE.

The returned strings are transcoded to UTF-8. Glow-up translation, we love to see it. ๐Ÿ’…

The "strings" command has, in the past, had problems with parsing untrusted files. These are mitigated in the current version of libguestfs, but see "CVE-2014-8484" in guestfs(3).

Because of the message protocol, there is a transfer limit of somewhere between 2MB and 4MB. See "PROTOCOL LIMITS" in guestfs(3).

$g->swapoff_device ($device);

This command disables the libguestfs appliance swap device or partition named "device" ๐Ÿ›‘. See $g->swapon_device โ€” it's the undo button for that one.

$g->swapoff_file ($file);

This command disables the libguestfs appliance swap on file ๐Ÿ“„๐Ÿ›‘.

$g->swapoff_label ($label);

This command disables the libguestfs appliance swap on a labeled swap partition ๐Ÿท๏ธ๐Ÿ›‘.

$g->swapoff_uuid ($uuid);

This command disables the libguestfs appliance swap partition with the given UUID ๐Ÿ†”๐Ÿ›‘.

This function depends on the feature "linuxfsuuid". See also $g->feature-available.

$g->swapon_device ($device);

This command enables the libguestfs appliance to use the swap device or partition named "device" ๐Ÿ’พโœจ. The increased memory is made available for all commands, for example those run using $g->command or $g->sh.

Careful, bestie! โš ๏ธ You should not swap to existing guest swap partitions unless you know what you are doing. They may contain hibernation information, or other information that the guest doesn't want you to trash. You also risk leaking information about the host to the guest this way. Instead, attach a new host device to the guest and swap on that. Safer vibes only. ๐Ÿซถ

$g->swapon_file ($file);

This command enables swap to a file ๐Ÿ“„. See $g->swapon_device for the other notes (including the spicy warning).

$g->swapon_label ($label);

This command enables swap to a labeled swap partition ๐Ÿท๏ธ. See $g->swapon_device for the other notes.

$g->swapon_uuid ($uuid);

This command enables swap to a swap partition with the given UUID ๐Ÿ†”. See $g->swapon_device for the other notes.

This function depends on the feature "linuxfsuuid". See also $g->feature-available.

$g->sync ();

This syncs the disk, so that any writes are flushed through to the underlying disk image ๐ŸŒŠ๐Ÿ’พ. Like hitting save on the whole vibe.

You should always call this if you have modified a disk image, before closing the handle. No exceptions, bestie, this is important. ๐Ÿšจ

$g->syslinux ($device [, directory => $directory]);

Install the SYSLINUX bootloader on "device" ๐Ÿฅพโœจ.

The device parameter must be either a whole disk formatted as a FAT filesystem, or a partition formatted as a FAT filesystem. In the latter case, the partition should be marked as "active" ($g->part_set_bootable) and a Master Boot Record must be installed (eg. using $g->pwrite_device) on the first sector of the whole disk. The SYSLINUX package comes with some suitable Master Boot Records. See the syslinux(1) man page for further information. ๐Ÿ‘‘

The optional arguments are:

  • directory โ€” install SYSLINUX in the named subdirectory, instead of in the root directory of the FAT filesystem. ๐Ÿ—‚๏ธ

Additional configuration can be supplied to SYSLINUX by placing a file called syslinux.cfg on the FAT filesystem, either in the root directory, or under directory if that optional argument is being used. For further information about the contents of this file, see syslinux(1). ๐ŸŽ€

See also $g->extlinux.

This function depends on the feature "syslinux". See also $g->feature-available.

@lines = $g->tail ($path);

This command returns up to the last 10 lines of a file as a list of strings ๐Ÿ™โœจ. Just the tail end, get it? ๐Ÿ’…

Because of the message protocol, there is a transfer limit of somewhere between 2MB and 4MB. See "PROTOCOL LIMITS" in guestfs(3).

@lines = $g->tail_n ($nrlines, $path);

If the parameter "nrlines" is a positive number, this returns the last "nrlines" lines of the file "path" ๐Ÿ“–.

If the parameter "nrlines" is a negative number, this returns lines from the file "path", starting with the "-nrlines"'th line. Yes, negative, it's giving backwards energy. ๐Ÿ™ƒ

If the parameter "nrlines" is zero, this returns an empty list. Zero lines, zero drama. ๐Ÿ’€

Because of the message protocol, there is a transfer limit of somewhere between 2MB and 4MB. See "PROTOCOL LIMITS" in guestfs(3).

๐Ÿงš tar_in โ€” upload & unpack a tarball

$g->tar_in ($tarfile, $directory [, compress => $compress] [, xattrs => $xattrs] [, selinux => $selinux] [, acls => $acls] [, keepdirlink => $keepdirlink]);

Okay so this one uploads a local file called tarfile and unpacks it right into directory. Basically yeet the tarball into the guest and let it explode (in the fun way ๐Ÿ’ฅ).

The optional compress flag is the whole compression vibe check. If you don't pass it, the input needs to be an uncompressed tar file, no cap. Otherwise you can hand it one of these strings to tell it what kind of compressed situation you're dealing with: compress, gzip, bzip2, xz, lzop, lzma, zstd. (Heads up though โ€” not every build of libguestfs supports all of these compression types, so likeโ€ฆ don't assume ๐Ÿ‘€.)

The other optional args are:

  • xattrs โ€” set it true and extended attributes get restored from the tar file โœจ
  • selinux โ€” set it true and SELinux contexts get restored from the tar file ๐Ÿ”
  • acls โ€” set it true and POSIX ACLs get restored from the tar file ๐ŸŽ€
  • keepdirlink โ€” set it true and existing symlinks to directories get followed when extracting from the tar file. This one is lowkey important for usrmerge systems where /lib is a symlink to /usr/lib ๐Ÿซถ

๐ŸŒˆ tar_in_opts

$g->tar_in_opts ($tarfile, $directory [, compress => $compress] [, xattrs => $xattrs] [, selinux => $selinux] [, acls => $acls] [, keepdirlink => $keepdirlink]);

This is literally just an alias of tar_in. Same energy, different name ๐Ÿ’…


๐ŸŽ€ tar_out โ€” pack it up & download

$g->tar_out ($directory, $tarfile [, compress => $compress] [, numericowner => $numericowner] [, excludes => $excludes] [, xattrs => $xattrs] [, selinux => $selinux] [, acls => $acls]);

This is the reverse glow-up: it packs the contents of directory and downloads the result to the local file tarfile ๐Ÿ“ฆโœจ

The optional compress flag controls the compression, obviously. Don't pass it and the output is an uncompressed tar file. Otherwise pick one of these strings for the output file's compression type: compress, gzip, bzip2, xz, lzop, lzma, zstd. (Again โ€” not all builds of libguestfs will support all of these compression types, so keep that in mind ๐Ÿง .)

The other optional args are:

  • excludes โ€” a list of wildcards. Files get excluded if they match any of the wildcards ๐Ÿšซ
  • numericowner โ€” set it true and the output tar file contains UID/GID numbers instead of user/group names ๐Ÿ”ข
  • xattrs โ€” set it true and extended attributes get saved in the output tar โœจ
  • selinux โ€” set it true and SELinux contexts get saved in the output tar ๐Ÿ”
  • acls โ€” set it true and POSIX ACLs get saved in the output tar ๐ŸŽ€

๐Ÿฆ‹ tar_out_opts

$g->tar_out_opts ($directory, $tarfile [, compress => $compress] [, numericowner => $numericowner] [, excludes => $excludes] [, xattrs => $xattrs] [, selinux => $selinux] [, acls => $acls]);

Alias of tar_out. That's it. That's the whole tea โ˜•


๐Ÿ’€ tgz_in โ€” the deprecated era

$g->tgz_in ($tarball, $directory);

Uploads and unpacks the local file tarball (a gzip compressed tar file) into directory.

๐Ÿšจ Deprecated alert! This function is deprecated. In new code, use the tar_in call instead, bestie.

And for the record: deprecated functions will not be removed from the API, but the fact that they're deprecated indicates that there are problems with correct use of these functions. So likeโ€ฆ it's still here, but it's giving "red flag" ๐Ÿ™ˆ


๐Ÿ“ tgz_out

$g->tgz_out ($directory, $tarball);

Packs the contents of directory and downloads it to the local file tarball.

๐Ÿšจ Deprecated alert! This function is deprecated. In new code, use the tar_out call instead.

Same deal as above: deprecated functions will not be removed from the API, but the fact that they're deprecated indicates that there are problems with correct use of these functions. Not me warning you twice ๐Ÿ’€


โœจ touch

$g->touch ($path);

Touch acts like the touch(1) command, periodt. You can use it to update the timestamps on a file, or โ€” if the file doesn't exist โ€” to create a brand new zero-length file ๐Ÿ‘‘

โš ๏ธ But listen: this command only works on regular files, and it will fail on other file types such as directories, symbolic links, block special etc. So don't come for it when it doesn't work on your symlink ๐Ÿซ 

๐ŸงŠ truncate

$g->truncate ($path);

Truncates path down to a zero-length file. The file has to exist already โ€” no manifesting files out of nowhere, sorry ๐Ÿ’…


๐Ÿ“ truncate_size

$g->truncate_size ($path, $size);

Truncates path to size bytes. The file must exist already, same rules as above.

If the current file size is less than size, then the file gets extended to the required size with zero bytes. That creates a sparse file (ie. disk blocks are not allocated for the file until you actually write to it). And if you want a non-sparse file of zeroes? Use $g->fallocate64 instead โœจ


๐Ÿ‘‘ tune2fs โ€” glow-up your ext filesystem

$g->tune2fs ($device [, force => $force] [, maxmountcount => $maxmountcount] [, mountcount => $mountcount] [, errorbehavior => $errorbehavior] [, group => $group] [, intervalbetweenchecks => $intervalbetweenchecks] [, reservedblockspercentage => $reservedblockspercentage] [, lastmounteddirectory => $lastmounteddirectory] [, reservedblockscount => $reservedblockscount] [, user => $user]);

This call lets you adjust a bunch of filesystem parameters on an ext2/ext3/ext4 filesystem called device. Think of it as a little makeover for your fs ๐Ÿง–โ€โ™€๏ธ

The optional parameters are:

  • force โ€” forces tune2fs to complete the operation even in the face of errors. Same as the tune2fs(8) -f option ๐Ÿ’ช
  • maxmountcount โ€” sets the number of mounts after which the filesystem gets checked by e2fsck(8). If this is 0 then the number of mounts is disregarded. Same as the tune2fs(8) -c option.
  • mountcount โ€” sets the number of times the filesystem has been mounted. Same as the tune2fs(8) -C option.
  • errorbehavior โ€” changes the behavior of the kernel code when errors are detected. Possible values right now are: continue, remount-ro, panic. In practice these options don't really make any difference, particularly for write errors. Same as the tune2fs(8) -e option ๐Ÿคทโ€โ™€๏ธ
  • group โ€” sets the group which can use reserved filesystem blocks. Same as the tune2fs(8) -g option, except it can only be specified as a number.
  • intervalbetweenchecks โ€” adjusts the maximal time between two filesystem checks (in seconds). If the option is passed as 0 then time-dependent checking is disabled. Same as the tune2fs(8) -i option โฐ
  • reservedblockspercentage โ€” sets the percentage of the filesystem which may only be allocated by privileged processes. Same as the tune2fs(8) -m option.
  • lastmounteddirectory โ€” sets the last mounted directory. Same as the tune2fs(8) -M option.
  • reservedblockscount โ€” sets the number of reserved filesystem blocks. Same as the tune2fs(8) -r option.
  • user โ€” sets the user who can use the reserved filesystem blocks. Same as the tune2fs(8) -u option, except it can only be specified as a number.

To get the current values of filesystem parameters, see $g->tune2fs_l. And for precise details of how tune2fs works, go read the tune2fs(8) man page ๐Ÿ“–


๐Ÿ” tune2fs_l

%superblock = $g->tune2fs_l ($device);

Returns the contents of the ext2, ext3 or ext4 filesystem superblock on device.

It's the same as running tune2fs -l device. See tune2fs(8) manpage for more details. And ngl, the list of fields returned isn't clearly defined โ€” it depends on both the version of tune2fs that libguestfs was built against, and the filesystem itself. So your mileage may vary ๐ŸŽฒ


๐ŸŒ€ txz_in

$g->txz_in ($tarball, $directory);

Uploads and unpacks the local file tarball (an xz compressed tar file) into directory.

This function depends on the feature xz. See also $g->feature-available.

๐Ÿšจ Deprecated alert! This function is deprecated. In new code, use the tar_in call instead.

Deprecated functions will not be removed from the API, but the fact that they're deprecated indicates that there are problems with correct use of these functions ๐Ÿ™ˆ


๐ŸŒธ txz_out

$g->txz_out ($directory, $tarball);

Packs the contents of directory and downloads it to the local file tarball (as an xz compressed tar archive).

This function depends on the feature xz. See also $g->feature-available.

๐Ÿšจ Deprecated alert! This function is deprecated. In new code, use the tar_out call instead.

Deprecated functions will not be removed from the API, but the fact that they're deprecated indicates that there are problems with correct use of these functions ๐Ÿ’€


๐ŸŽญ umask โ€” the permission vibe-setter

$oldmask = $g->umask ($mask);

Sets the mask used for creating new files and device nodes to mask & 0777.

Typical umask values would be 022, which creates new files with permissions like -rw-r--r-- or -rwxr-xr-x, and 002, which creates new files with permissions like -rw-rw-r-- or -rwxrwxr-x ๐Ÿ’…

The default umask is 022. This is important because it means directories and device nodes will be created with 0644 or 0755 mode even if you specify 0777. Like, the umask really said "I'm the main character here" ๐Ÿ‘€

See also $g->get_umask, umask(2), $g->mknod, $g->mkdir.

This call returns the previous umask ๐Ÿซถ


๐Ÿช„ umount

$g->umount ($pathordevice [, force => $force] [, lazyunmount => $lazyunmount]);

Unmounts the given filesystem. You can specify the filesystem either by its mountpoint (path) or by the device which contains the filesystem โ€” dealer's choice โœจ


๐Ÿง umount_opts

$g->umount_opts ($pathordevice [, force => $force] [, lazyunmount => $lazyunmount]);

Alias of umount. Iconic of it to have two names honestly.


๐ŸŒŠ umount_all

$g->umount_all ();

Unmounts all mounted filesystems. Clean slate, no crumbs left ๐Ÿงน

โš ๏ธ Some internal mounts are not unmounted by this call. So don't be shocked when a couple of things are still hanging around.

๐Ÿ  umount_local

$g->umount_local ([retry => $retry]);

If libguestfs is exporting the filesystem on a local mountpoint, then this unmounts it.

See MOUNT LOCAL in guestfs(3) for full documentation ๐Ÿ“š


๐Ÿ“ค upload

$g->upload ($filename, $remotefilename);

Uploads the local file filename to remotefilename on the filesystem.

Oh and filename can also be a named pipe โ€” cute little flex ๐Ÿฅค

See also $g->download.


๐Ÿ“ upload_offset

$g->upload_offset ($filename, $remotefilename, $offset);

Uploads the local file filename to remotefilename on the filesystem.

Here's the twist: remotefilename gets overwritten starting at the byte offset you specified. The intention is to overwrite parts of existing files or devices, although if a non-existent file is specified then it gets created with a hole before offset. And the size of the data written is implicit in the size of the source filename โ€” no, you don't pass it separately, it just knows ๐Ÿง โœจ

Note that there's no cap on how much data you can push up with this call โ€” unlike $g->pwrite, bestie, it just keeps going ๐Ÿซถ โ€” and it always writes the full amount unless something errors out.

See also $g->upload, $g->pwrite. ๐Ÿ’–


$g->user_cancel ();

This one cancels whatever upload or download is happening right now. โœ‹

Unlike most other libguestfs calls, this function is signal safe and thread safe. You can call it from a signal handler or from another thread without needing to do any locking. no cap, it's built different ๐Ÿ’…

The transfer that was in progress (if there is one) will stop shortly afterwards, and will return an error. The errno (see guestfs_last_errno) is set to EINTR, so you can test for this to find out if the operation was cancelled or failed because of another error. ๐Ÿ•ต๏ธโ€โ™€๏ธ

โš ๏ธ No cleanup is performed: for example, if a file was being uploaded then after cancellation there may be a partially uploaded file. It is the caller's responsibility to clean up if necessary. so likeโ€ฆ yeah, you gotta tidy up yourself ๐Ÿงน

There are two common places that you might call $g->user_cancel:

  • In an interactive text-based program, you might call it from a SIGINT signal handler so that pressing ^C cancels the current operation. (You also need to call $g->set_pgroup so that child processes don't receive the ^C signal). โ€” iykyk ๐Ÿ˜Œ
  • In a graphical program, when the main thread is displaying a progress bar with a cancel button, wire up the cancel button to call this function. ๐ŸŽ€

$g->utimens ($path, $atsecs, $atnsecs, $mtsecs, $mtnsecs);

This command sets the timestamps of a file with nanosecond precision โฑ๏ธโœจ

atsecs, atnsecs are the last access time (atime) in secs and nanoseconds from the epoch.

mtsecs, mtnsecs are the last modification time (mtime) in secs and nanoseconds from the epoch.

Two spicy special values for the *nsecs field, bestie:

  • If the *nsecs field contains the special value -1 then the corresponding timestamp is set to the current time. (The *secs field is ignored in this case).
  • If the *nsecs field contains the special value -2 then the corresponding timestamp is left unchanged. (The *secs field is ignored in this case).

%uts = $g->utsname ();

Returns the kernel version of the appliance, where this is available. This info is only useful for debugging ๐Ÿ” โ€” nothing in the returned structure is defined by the API. literally "trust me bro" energy, don't build on it ๐Ÿ’€


%version = $g->version ();

Returns the libguestfs version number that the program is linked against.

Ok so heads up ๐Ÿšจ โ€” because of dynamic linking this is not necessarily the version of libguestfs that you compiled against. You can compile the program, and then at runtime dynamically link against a completely different libguestfs.so library. plot twist ๐Ÿ˜ญ

This call was added in version 1.0.58. In previous versions of libguestfs there was no way to get the version number. From C code you can use dynamic linker functions to find out if this symbol exists (if it doesn't, then it's an earlier version). ๐Ÿ•ฐ๏ธ

The call returns a structure with four elements. The first three (major, minor and release) are numbers and correspond to the usual version triplet. The fourth element (extra) is a string and is normally empty, but may be used for distro-specific information. ๐ŸŒธ

To construct the original version string:

$major.$minor.$release$extra

See also: "LIBGUESTFS VERSION NUMBERS" in guestfs(3).

๐Ÿ’€ Note: Don't use this call to test for availability of features. In enterprise distributions we backport features from later versions into earlier versions, making this an unreliable way to test for features. Use $g->available or $g->feature_available instead. fr fr, use the right tool ๐Ÿ™

$label = $g->vfs_label ($mountable);

Returns the label of the filesystem on mountable. ๐Ÿท๏ธ

If the filesystem is unlabeled, this returns the empty string.

To find a filesystem from the label, use $g->findfs_label. ๐Ÿฆ‹


$sizeinbytes = $g->vfs_minimum_size ($mountable);

Get the minimum size of filesystem in bytes. This is the minimum possible size for filesystem shrinking. ๐Ÿ“‰โœจ

If getting the minimum size of the specified filesystem isn't supported, this will fail and set errno as ENOTSUP. ๐Ÿ˜”

See also ntfsresize(8), resize2fs(8), btrfs(8), xfs_info(8).


$fstype = $g->vfs_type ($mountable);

This command gets the filesystem type corresponding to the filesystem on mountable. ๐Ÿ”Ž

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. slay, simple as that ๐Ÿ’…


$uuid = $g->vfs_uuid ($mountable);

Returns the filesystem UUID of the filesystem on mountable. ๐Ÿ†”

If the filesystem does not have a UUID, this returns the empty string.

To find a filesystem from the UUID, use $g->findfs_uuid. ๐Ÿงš


$g->vg_activate ($activate, \@volgroups);

This command activates or (if activate is false) deactivates all logical volumes in the listed volume groups volgroups. ๐Ÿ”›

This command is the same as running:

vgchange -a y|n volgroups...

Note that if volgroups is an empty list then all volume groups are activated or deactivated. ๐Ÿ‘‘

This function depends on the feature lvm2. See also $g->feature-available.


$g->vg_activate_all ($activate);

This command activates or (if activate is false) deactivates all logical volumes in all volume groups. ๐Ÿ’–

This command is the same as running:

vgchange -a y|n

This function depends on the feature lvm2. See also $g->feature-available.


$g->vgchange_uuid ($vg);

Generate a new random UUID for the volume group vg. ๐ŸŽฒโœจ

This function depends on the feature lvm2. See also $g->feature-available.


$g->vgchange_uuid_all ();

Generate new random UUIDs for all volume groups. ๐ŸŽฒ๐ŸŽฒ๐ŸŽฒ

This function depends on the feature lvm2. See also $g->feature-available.


$g->vgcreate ($volgroup, \@physvols);

This creates an LVM volume group called volgroup from the non-empty list of physical volumes physvols. ๐Ÿ—๏ธ

This function depends on the feature lvm2. See also $g->feature-available.


@uuids = $g->vglvuuids ($vgname);

Given a VG called vgname, this returns the UUIDs of all the logical volumes created in this volume group. ๐Ÿงพ

You can use this along with $g->lvs and $g->lvuuid calls to associate logical volumes and volume groups. ๐Ÿ”—

See also $g->vgpvuuids.


$metadata = $g->vgmeta ($vgname);

vgname is an LVM volume group. This command examines the volume group and returns its metadata. ๐Ÿ“œ

โš ๏ธ Note that the metadata is an internal structure used by LVM, subject to change at any time, and is provided for information only. so don't go depending on it, bestie ๐Ÿ˜ฌ

This function depends on the feature lvm2. See also $g->feature-available.


@uuids = $g->vgpvuuids ($vgname);

Given a VG called vgname, this returns the UUIDs of all the physical volumes that this volume group resides on. ๐Ÿ’พ

You can use this along with $g->pvs and $g->pvuuid calls to associate physical volumes and volume groups. ๐Ÿ”—

See also $g->vglvuuids.


$g->vgremove ($vgname);

Remove an LVM volume group vgname, (for example VG). ๐Ÿ’ฅ

This also forcibly removes all logical volumes in the volume group (if any). yeah, it's giving zero chill ๐Ÿ˜ญ

This function depends on the feature lvm2. See also $g->feature-available.


$g->vgrename ($volgroup, $newvolgroup);

Rename a volume group volgroup with the new name newvolgroup. โœ๏ธโœจ


@volgroups = $g->vgs ();

List all the volume groups detected. This is the equivalent of the vgs(8) command. ๐Ÿ“‹

This returns a list of just the volume group names that were detected (eg. VolGroup00). ๐Ÿท๏ธ

See also $g->vgs_full.

This function depends on the feature lvm2. See also $g->feature-available.


@volgroups = $g->vgs_full ();

List all the volume groups detected. This is the equivalent of the vgs(8) command. The "full" version includes all fields. ๐Ÿ‘‘ the deluxe edition fr

This function depends on the feature lvm2. See also $g->feature-available.


$g->vgscan ();

This rescans all block devices and rebuilds the list of LVM physical volumes, volume groups and logical volumes. ๐Ÿ”„

๐Ÿšฉ This function is deprecated. In new code, use the lvm_scan call instead.

Deprecated functions will not be removed from the API, but the fact that they are deprecated indicates that there are problems with correct use of these functions. ๐Ÿ’€


$uuid = $g->vguuid ($vgname);

This command returns the UUID of the LVM VG named vgname. ๐Ÿ†”


$g->wait_ready ();

This function is a no op. literally does nothing, bestie ๐Ÿซ 

In versions of the API < 1.0.71 you had to call this function just after calling $g->launch to wait for the launch to complete. However this is no longer necessary because $g->launch now does the waiting. โณ

If you see any calls to this function in code then you can just remove them, unless you want to retain compatibility with older versions of the API. ๐Ÿงนโœจ

๐Ÿšฉ This function is deprecated. There is no replacement. Consult the API documentation in guestfs(3) for further information.

Deprecated functions will not be removed from the API, but the fact that they are deprecated indicates that there are problems with correct use of these functions. ๐Ÿ˜”


$chars = $g->wc_c ($path);

This command counts the characters in a file, using the wc -c external command. ๐Ÿ”ค


$lines = $g->wc_l ($path);

This command counts the lines in a file, using the wc -l external command. ๐Ÿ“


$words = $g->wc_w ($path);

This command counts the words in a file, using the wc -w external command. ๐Ÿ“


$g->wipefs ($device);

This command erases filesystem or RAID signatures from the specified device to make the filesystem invisible to libblkid. ๐Ÿ™ˆโœจ

โš ๏ธ This does not erase the filesystem itself nor any other data from the device. it's just hiding the name tag, not the whole personality ๐Ÿ’…

Compare with $g->zero which zeroes the first few blocks of a device.

This function depends on the feature wipefs. See also $g->feature-available.


$g->write ($path, $content);

This call creates a file called path. The content of the file is the string content (which can contain any 8 bit data). ๐Ÿ“โœจ

See also $g->write_append.


$g->write_append ($path, $content);

This call appends content to the end of file path. If path does not exist, then a new file is created. โž•๐Ÿ“„

See also $g->write. ๐Ÿซถ

๐Ÿ’– write_file

$g->write_file ($path, $content, $size);

This call creates a file called path. The contents of the file is the string content (which can contain any 8 bit data), with length size. Slay, very straightforward. โœจ

Special case alert ๐Ÿšจ: if size is 0, then the length is calculated using strlen โ€” which means in this case the content cannot contain embedded ASCII NULs.

NB. Owing to a bug, writing content containing ASCII NUL characters does not work, even if the length is specified. Literally does not work, bestie. ๐Ÿ˜ญ

Because of the message protocol, there is a transfer limit of somewhere between 2MB and 4MB. See PROTOCOL LIMITS in guestfs(3).

This function is deprecated. In new code, use the write call instead.

Deprecated functions will not be removed from the API, but the fact that they are deprecated indicates that there are problems with correct use of these functions. iykyk. ๐Ÿ’…


๐Ÿงš xfs_admin

$g->xfs_admin ($device [, extunwritten => $extunwritten] [, imgfile => $imgfile]
               [, v2log => $v2log] [, projid32bit => $projid32bit]
               [, lazycounter => $lazycounter] [, label => $label] [, uuid => $uuid]);

Change the parameters of the XFS filesystem on device.

Devices that are mounted cannot be modified. Administrators must unmount filesystems before this call can modify parameters. No exceptions, no shortcuts, no "but I'll be careful" ๐Ÿซถ.

Some of the parameters of a mounted filesystem can be examined and modified using the $g->xfs_info and $g->xfs_growfs calls.

Beginning with XFS version 5, it is no longer possible to modify the lazy-counters setting (ie. the lazycounter parameter has no effect). It's giving legacy. ๐Ÿ’€

This function depends on the feature xfs. See also $g->feature-available.


๐ŸŒฑ xfs_growfs

$g->xfs_growfs ($path [, datasec => $datasec] [, logsec => $logsec] [, rtsec => $rtsec]
                [, datasize => $datasize] [, logsize => $logsize] [, rtsize => $rtsize]
                [, rtextsize => $rtextsize] [, maxpct => $maxpct]);

Grow the XFS filesystem mounted at path. Glow-up era โœจ.

This function depends on the feature xfs. See also $g->feature-available.


๐Ÿ” xfs_info

%info = $g->xfs_info ($pathordevice);

pathordevice is a mounted XFS filesystem or a device containing an XFS filesystem. This command returns miscellaneous metadata about the XFS filesystem.

The returned struct contains miscellaneous metadata. Missing fields are returned as -1 (for numeric fields) or empty string. So if you see a -1, that's not a bug, that's the vibe check failing politely. ๐Ÿ™ˆ

This function depends on the feature xfs. See also $g->feature-available.

This function is deprecated. In new code, use the xfs_info2 call instead.

Deprecated functions will not be removed from the API, but the fact that they are deprecated indicates that there are problems with correct use of these functions.


๐Ÿ‘‘ xfs_info2

%info = $g->xfs_info2 ($pathordevice);

pathordevice is a mounted XFS filesystem or a device containing an XFS filesystem. This command returns miscellaneous metadata about the XFS filesystem.

The output is a hash derived from the output of xfs_info(8), and generally looks like:

meta-data: /dev/sda1
meta-data.isize: 512
meta-data.agcount: 4
meta-data.agsize: 65528 blks
meta-data.sectsz: 512
meta-data.attr: 2
meta-data.projid32bit: 1
meta-data.crc: 1
[...]
data.bsize: 4096
data.blocks: 262112
[...]

More information can be found by reading xfs_info(8). Yes, actual homework. ๐Ÿ“š

This function depends on the feature xfs. See also $g->feature-available.


๐Ÿ› ๏ธ xfs_repair

$status = $g->xfs_repair ($device [, forcelogzero => $forcelogzero] [, nomodify => $nomodify]
                          [, noprefetch => $noprefetch] [, forcegeometry => $forcegeometry]
                          [, maxmem => $maxmem] [, ihashsize => $ihashsize]
                          [, bhashsize => $bhashsize] [, agstride => $agstride]
                          [, logdev => $logdev] [, rtdev => $rtdev]);

Repair corrupt or damaged XFS filesystem on device. Main character energy for a broken filesystem ๐Ÿ’ช.

The filesystem is specified using the device argument which should be the device name of the disk partition or volume containing the filesystem. If given the name of a block device, xfs_repair will attempt to find the raw device associated with the specified block device and will use the raw device instead.

Regardless, the filesystem to be repaired must be unmounted, otherwise, the resulting filesystem may be inconsistent or corrupt. Do not skip this, bestie, fr fr ๐Ÿ’€.

The returned status indicates whether filesystem corruption was detected (returns 1) or was not detected (returns 0).

This function depends on the feature xfs. See also $g->feature-available.


๐Ÿฆ‹ yara_destroy

$g->yara_destroy ();

Destroy previously loaded Yara rules in order to free libguestfs resources.

This function depends on the feature libyara. See also $g->feature-available.


๐ŸŽ€ yara_load

$g->yara_load ($filename);

Upload a set of Yara rules from local file filename.

Yara rules allow to categorize files based on textual or binary patterns within their content. See $g->yara_scan to see how to scan files with the loaded rules.

Rules can be in binary format, as when compiled with yarac command, or in source code format. In the latter case, the rules will be first compiled and then loaded.

Rules in source code format cannot include external files. In such cases, it is recommended to compile them first.

Previously loaded rules will be destroyed.

This function depends on the feature libyara. See also $g->feature-available.


๐ŸŒธ yara_scan

@detections = $g->yara_scan ($path);

Scan a file with the previously loaded Yara rules.

For each matching rule, a yara_detection structure is returned.

The yara_detection structure contains the following fields.

  • yara_name โ€” Path of the file matching a Yara rule.
  • yara_rule โ€” Identifier of the Yara rule which matched against the given file.

This function depends on the feature libyara. See also $g->feature-available.


๐Ÿ“ zegrep

@lines = $g->zegrep ($regex, $path);

This calls the external zegrep program and returns the matching lines.

Because of the message protocol, there is a transfer limit of somewhere between 2MB and 4MB. See PROTOCOL LIMITS in guestfs(3).

This function is deprecated. In new code, use the grep call instead.

Deprecated functions will not be removed from the API, but the fact that they are deprecated indicates that there are problems with correct use of these functions.


๐Ÿ“ zegrepi

@lines = $g->zegrepi ($regex, $path);

This calls the external zegrep -i program and returns the matching lines. Case-insensitive era ๐Ÿ’….

Because of the message protocol, there is a transfer limit of somewhere between 2MB and 4MB. See PROTOCOL LIMITS in guestfs(3).

This function is deprecated. In new code, use the grep call instead.

Deprecated functions will not be removed from the API, but the fact that they are deprecated indicates that there are problems with correct use of these functions.


โšซ zero

$g->zero ($device);

This command writes zeroes over the first few blocks of device.

How many blocks are zeroed isn't specified (but itโ€™s not enough to securely wipe the device). It should be sufficient to remove any partition tables, filesystem superblocks and so on.

If blocks are already zero, then this command avoids writing zeroes. This prevents the underlying device from becoming non-sparse or growing unnecessarily.

See also: $g->zero_device, $g->scrub_device, $g->is_zero_device


๐ŸŒ‘ zero_device

$g->zero_device ($device);

This command writes zeroes over the entire device. Compare with $g->zero which just zeroes the first few blocks of a device.

If blocks are already zero, then this command avoids writing zeroes. This prevents the underlying device from becoming non-sparse or growing unnecessarily.


๐Ÿงน zero_free_space

$g->zero_free_space ($directory);

Zero the free space in the filesystem mounted on directory. The filesystem must be mounted read-write.

The filesystem contents are not affected, but any free space in the filesystem is freed.

Free space is not "trimmed". You may want to call $g->fstrim either as an alternative to this, or after calling this, depending on your requirements.


๐Ÿซง zerofree

$g->zerofree ($device);

This runs the zerofree program on device. This program claims to zero unused inodes and disk blocks on an ext2/3 filesystem, thus making it possible to compress the filesystem more effectively.

You should not run this program if the filesystem is mounted. And heads up: it is possible that using this program can damage the filesystem or data on the filesystem. Not me delivering bad news ๐Ÿ˜ญ

This function depends on the feature zerofree. See also $g->feature-available.


๐Ÿงต zfgrep

@lines = $g->zfgrep ($pattern, $path);

This calls the external zfgrep program and returns the matching lines.

Because of the message protocol, there is a transfer limit of somewhere between 2MB and 4MB. See PROTOCOL LIMITS in guestfs(3).

This function is deprecated. In new code, use the grep call instead.

Deprecated functions will not be removed from the API, but the fact that they are deprecated indicates that there are problems with correct use of these functions.


๐Ÿงต zfgrepi

@lines = $g->zfgrepi ($pattern, $path);

This calls the external zfgrep -i program and returns the matching lines.

Because of the message protocol, there is a transfer limit of somewhere between 2MB and 4MB. See PROTOCOL LIMITS in guestfs(3).

This function is deprecated. In new code, use the grep call instead.

Deprecated functions will not be removed from the API, but the fact that they are deprecated indicates that there are problems with correct use of these functions.


๐Ÿ—‚๏ธ zfile

$description = $g->zfile ($meth, $path);

This command runs file(1) after first decompressing path using meth.

meth must be one of gzip, compress or bzip2.

Since 1.0.63, use $g->file instead which can now process compressed files.

This function is deprecated. In new code, use the file call instead.

Deprecated functions will not be removed from the API, but the fact that they are deprecated indicates that there are problems with correct use of these functions.


๐ŸŒˆ zgrep

@lines = $g->zgrep ($regex, $path);

This calls the external zgrep(1) program and returns the matching lines.

Because of the message protocol, there is a transfer limit of somewhere between 2MB and 4MB. See PROTOCOL LIMITS in guestfs(3).

zgrep is deprecated, bestie. In new code, use the grep call instead. ๐Ÿ’…

Deprecated functions don't get yeeted from the API (they stay, fr fr), but the fact that they're marked deprecated is a lil red flag ๐Ÿšฉ telling you there are problems with using them correctly.


  • @lines = $g->zgrepi ($regex, $path); โ€” this one calls the external zgrep -i program and hands you back the matching lines. ๐Ÿ”
Because of the message protocol, there is a transfer limit of somewhere between 2MB and 4MB. See "PROTOCOL LIMITS" in guestfs(3). ๐Ÿ’€

This function is deprecated. In new code, use the grep call instead.

Deprecated functions will not be removed from the API, but the fact that they are deprecated indicates that there are problems with correct use of these functions.


โœจ AVAILABILITY โœจ

Okay so here's the tea โ˜• โ€” from time to time we add new libguestfs APIs. And also, some libguestfs APIs won't be available in all builds of libguestfs (the Fedora build is full-featured, but other builds may disable features ๐Ÿ‘€). So how do you test whether the APIs your Perl program needs are actually available in the version of Sys::Guestfs you're using? Great question, bestie ๐Ÿซถ

To test if a particular function is available in the Sys::Guestfs class, use the ordinary Perl UNIVERSAL method can(METHOD) (see perlobj(1)). Like, for example:

 use Sys::Guestfs;
 if (defined (Sys::Guestfs->can ("set_verbose"))) {
   print "\$g->set_verbose is available\n";
 }

To test if particular features are supported by the current build, use the feature_available method like the example below. Note that the appliance must be launched first ๐Ÿ”ฅ

 $g->feature_available ( ["augeas"] );

For further discussion on this topic, refer to "AVAILABILITY" in guestfs(3).


๐ŸŽ€ STORING DATA IN THE HANDLE ๐ŸŽ€

The handle returned from new is a hash reference. The hash normally contains some elements:

 {
   _g => [private data used by libguestfs],
   _flags => [flags provided when creating the handle]
 }

Callers can add other elements to this hash to store data for their own purposes ๐Ÿ’– The data lasts for the lifetime of the handle โ€” iconic, honestly.

Any fields whose names begin with an underscore are reserved for private use by libguestfs. We may add more in future ๐Ÿ™ˆ

It is recommended that callers prefix the name of their field(s) with some unique string, to avoid conflicts with other users. (Vibe check: don't collide with strangers, it's giving bad manners ๐Ÿ’…)


Copyright (C) 2009-2025 Red Hat Inc.


๐ŸŒธ LICENSE ๐ŸŒธ

Please see the file COPYING.LIB for the full license.


๐ŸŒˆ SEE ALSO ๐ŸŒˆ


aaaand that's a wrap on the whole page, bestie! ๐Ÿฆ‹ This little scroll was brought to you by perl v5.40.2, dated 2026-09-16, and it's the Sys::Guestfs(3pm) manpage โ€” go forth and slay your guests, mwah ๐Ÿ’‹โœจ

๐Ÿ“ฆ where this page comes from