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
environmentis false, then theGUESTFS_CREATE_NO_ENVIRONMENTflag is set. - If the optional argument
close_on_exitis false, then theGUESTFS_CREATE_NO_CLOSE_ON_EXITflag 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 callingclosethe program must not call any method (includingclose) on the handle (but the implicit call toDESTROYthat happens when the final reference is cleaned up is OK). bestie, do not touch it afterclose, that's the vibe check ๐
๐ฆ event constants ๐ฆ
$Sys::Guestfs::EVENT_CLOSEโ SeeGUESTFS_EVENT_CLOSEinguestfs(3).$Sys::Guestfs::EVENT_SUBPROCESS_QUITโ SeeGUESTFS_EVENT_SUBPROCESS_QUITinguestfs(3).$Sys::Guestfs::EVENT_LAUNCH_DONEโ SeeGUESTFS_EVENT_LAUNCH_DONEinguestfs(3).$Sys::Guestfs::EVENT_PROGRESSโ SeeGUESTFS_EVENT_PROGRESSinguestfs(3).$Sys::Guestfs::EVENT_APPLIANCEโ SeeGUESTFS_EVENT_APPLIANCEinguestfs(3).$Sys::Guestfs::EVENT_LIBRARYโ SeeGUESTFS_EVENT_LIBRARYinguestfs(3).$Sys::Guestfs::EVENT_TRACEโ SeeGUESTFS_EVENT_TRACEinguestfs(3).$Sys::Guestfs::EVENT_ENTERโ SeeGUESTFS_EVENT_ENTERinguestfs(3).$Sys::Guestfs::EVENT_LIBVIRT_AUTHโ SeeGUESTFS_EVENT_LIBVIRT_AUTHinguestfs(3).$Sys::Guestfs::EVENT_WARNINGโ SeeGUESTFS_EVENT_WARNINGinguestfs(3).$Sys::Guestfs::EVENT_ALLโ SeeGUESTFS_EVENT_ALLinguestfs(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 ifpathis 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 ifpathis 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
readonlyis false:- The whole call is aborted with an error if any disk with the
<readonly/>flag is found.
- The whole call is aborted with an error if any disk with the
- If
readonlyis true:- Disks with the
<readonly/>flag are added read-only.
- Disks with the
- If
readonlydisk = "read"โ- If
readonlyis false:- Disks with the
<readonly/>flag are added read-only. Other disks are added read/write.
- Disks with the
- If
readonlyis true:- Disks with the
<readonly/>flag are added read-only.
- Disks with the
- If
readonlydisk = "write"(default) โ- If
readonlyis false:- Disks with the
<readonly/>flag are added read/write.
- Disks with the
- If
readonlyis true:- Disks with the
<readonly/>flag are added read-only.
- Disks with the
- If
readonlydisk = "ignore"โ- If
readonlyis true or false:- Disks with the
<readonly/>flag are skipped.
- Disks with the
- If
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_driveor$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_ifcall (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->fstrimwill 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 are512(the default if the parameter is omitted) or4096. Use4096when 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.augsaveextension.AUG_SAVE_NEWFILE= 2 โ Save changes into a file with extension.augnew, and do not overwrite original. OverridesAUG_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 theLIBGUESTFS_MEMSIZEenvironment 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_availableis 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->launchbefore 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 examplefilesystemorraid.
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/LVform 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,modeby default would be decimal โ unless you prefix it with0to get octal, ie. use0700not700. 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 between2MBand4MB. 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 between2MBand4MB. 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 fromsourcetodestination. Only the UNIX permissions and the sticky/setuid/setgid bits can be copied.xattributesโ Copy the Linux extended attributes (xattrs) fromsourcetodestination. This flag does nothing if the linuxxattrs feature is not available (see$g->feature_available).ownershipโ Copy the owner uid and the group gid ofsourcetodestination.allโ Copy all the attributes fromsourcetodestination. 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_aand$g->mvfor 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 string1.1to 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 filesfile1andfile2and 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 givenpathname. Anything. A file, a dir, a weird little guy โ if the name's there, it'strue. โจ
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->syslinuxwhich 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) namedpathof sizelenbytes. 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) namedpathof sizelenbytes. 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, justtrueorfalse. ๐
For other documentation see $g->available.
@lines = $g->fgrep ($pattern, $path);โ this calls the externalfgrep(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 externalfgrep -iprogram and returns the matching lines. Yes, the-iis 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 standardfile(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".
- Win32 binaries and DLLs return
- 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 argumentfilesystemis 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 be0if 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-1if 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 functiondownload_inodecan 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-print0iykyk. - 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-Eflag.fixedโ match fixed (donโt use regular expressions). this is the same as using the-Fflag.insensitiveโ match case-insensitive. this is the same as using the-iflag.compressedโ usezgrep(1)instead ofgrep(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-installreports the error"No suitable drive was found in the generated device map."it may be that you need to create a/boot/grub/device.mapfile 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
nrlinesis a positive number, this returns the firstnrlineslines of the filepath. - If the parameter
nrlinesis a negative number, this returns lines from the filepath, excluding the lastnrlineslines. - If the parameter
nrlinesis 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_reador$g->inotify_files. Pass it as0and 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 flagIN_Q_OVERFLOWin 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 useapp_nameinstead.app_epochโ for package managers which use epochs, this contains the epoch of the package (an integer). If unavailable, this is returned as0.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 useapp2_nameinstead.app2_epochโ for package managers which use epochs, this contains the epoch of the package (an integer). If unavailable, this is returned as0.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.
$flag = $g->is_fifo_opts ($path [, followsymlinks => $followsymlinks]);
Literally just an alias of is_fifo. Same vibe, different name. ๐
$fileflag = $g->is_file ($path [, followsymlinks => $followsymlinks]);
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.
$fileflag = $g->is_file_opts ($path [, followsymlinks => $followsymlinks]);
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).
$flag = $g->is_socket ($path [, followsymlinks => $followsymlinks]);
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.
$flag = $g->is_socket_opts ($path [, followsymlinks => $followsymlinks]);
Alias of is_socket. Zero new info, all the same vibes. ๐ฆ
$flag = $g->is_symlink ($path);
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: ifkeyslotalready contains a key, this command will fail. No cap. You have to use$g->luks_kill_slotfirst 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 ofdevices+ the number of bits set inmissingbitmapmust equalnrdevices+spare.
nrdevicesโ the number of active RAID devices. If not set, this defaults to the length ofdevicesplus the number of bits set inmissingbitmap. โจspareโ the number of spare devices. If not set, this defaults to0.chunkโ the chunk size in bytes. lowkey important: thechunkparameter does not make sense, and should not be specified, whenlevelisraid1(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 toraid1. ๐
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-mostlyFโ device is faulty ๐Sโ device is a RAID spareRโ 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 are1024,2048or4096for 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-Oparameter 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 thegfsorgfs2filesystem type. like, just don't.
inodeโ this one gets passed straight through as the-Iflag 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-Sflag 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 with0to get octal, ie. use0700not700. 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->ntfsresizemultiple 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 featuregdisk. 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 thembrformat ๐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 usinggpt๐ฆ
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 usegpt.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 between2MBand4MB. 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 between2MBand4MB. 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 featurelvm2. 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 featurelvm2. 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 featurelvm2. 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 between2MBand4MB. See the PROTOCOL LIMITS section inguestfs(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 between2MBand4MB. See the PROTOCOL LIMITS section inguestfs(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_filefunction 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'?'โ Thereaddir(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"rwparameter. 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--archiveflag 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_networkor the--networkoption to various tools likeguestfish(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_networkor the--networkoption to various tools likeguestfish(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 overdeviceso 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 directorydirand 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 containingdir. 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 ๐. Thespecfileparameter controls which policy spec file gets used โ you have to parse/etc/selinux/configto find the correct SELinux policy and then pass the spec file, usually:/etc/selinux/+ selinuxtype +/contexts/files/file_contexts. The requiredpathparameter is the top level directory where relabelling starts; normally you passpathas/to relabel the whole guest filesystem. The optionalforceboolean 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 isNULLunless it's overridden by setting theLIBGUESTFS_APPENDenvironment variable. SettingappendtoNULLmeans 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);โ ifautosyncis 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);โ appendsname=valueto the backend settings string list ๐. BUT if a string already exists matchingnameor beginning withname=, 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 variableLIBGUESTFS_BACKEND_SETTINGSwas 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 variablesLIBGUESTFS_CACHEDIRandTMPDIRcontrol the default value: ifLIBGUESTFS_CACHEDIRis set, then that's the default. Else ifTMPDIRis set, then that's the default. Else/var/tmpis 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 attributesattrsassociated with the inode file ๐.attrsis a string of characters representing file attributes โ see$g->get_e2attrsfor a list of possible attributes, and note that not all attributes can be changed. If the optional booleanclearis not present or is false, then theattrslisted are set in the inode. Ifclearis true, then theattrslisted are cleared in the inode. In both cases, other attributes not present in theattrsstring 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 ondevicetolabel๐ท๏ธ. Filesystem labels are limited to 16 characters. You can use either$g->tune2fs_lor$g->get_e2labelto 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 ondevicetouuid๐. 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_uuidto 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 theLIBGUESTFS_HVenvironment 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 runningqemu -help). If the qemu binary changes, we don't retest features, and so you might see inconsistent results ๐ฌ. Using the environment variableLIBGUESTFS_HVis 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 onmountabletolabel๐ท๏ธ. 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 at255bytes, 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 to11bytes. Short and sweet ๐.swapโ label is limited to16bytes.
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->stringsuses).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/libis 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)-foption ๐ชmaxmountcountโ sets the number of mounts after which the filesystem gets checked by e2fsck(8). If this is0then the number of mounts is disregarded. Same as the tune2fs(8)-coption.mountcountโ sets the number of times the filesystem has been mounted. Same as the tune2fs(8)-Coption.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)-eoption ๐คทโโ๏ธgroupโ sets the group which can use reserved filesystem blocks. Same as the tune2fs(8)-goption, 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 as0then time-dependent checking is disabled. Same as the tune2fs(8)-ioption โฐreservedblockspercentageโ sets the percentage of the filesystem which may only be allocated by privileged processes. Same as the tune2fs(8)-moption.lastmounteddirectoryโ sets the last mounted directory. Same as the tune2fs(8)-Moption.reservedblockscountโ sets the number of reserved filesystem blocks. Same as the tune2fs(8)-roption.userโ sets the user who can use the reserved filesystem blocks. Same as the tune2fs(8)-uoption, 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
SIGINTsignal handler so that pressing^Ccancels the current operation. (You also need to call$g->set_pgroupso that child processes don't receive the^Csignal). โ 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
*nsecsfield contains the special value-1then the corresponding timestamp is set to the current time. (The*secsfield is ignored in this case). - If the
*nsecsfield contains the special value-2then the corresponding timestamp is left unchanged. (The*secsfield 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->availableor$g->feature_availableinstead. 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 externalzgrep -iprogram 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 ๐
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
- centos-stream 10: perl-Sys-Guestfs 1:1.61.3-1.el10 ยท LGPL-2.1-or-later
- ๐ girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms