Python interface¶
While imount heavily utilizes the Python API of imagemounter
, this API is also available for other classes.
Data structure¶
The basic structure of imagemounter
is the imagemounter.ImageParser
class, which provides access to underlying imagemounter.Disk
and imagemounter.Volume
objects. Each file name passed to a new imagemounter.ImageParser
object results in one imagemounter.Disk
object. imagemounter.Volume
objects are created by analysis of the Disk
object (each volume generates one object, even if it is not mountable), and each imagemounter.Volume
can have one or more subvolumes.
For instance, a LUKS volume may contain a LVM system that contains a Ext volume. This would create a Disk
with a Volume
containing a Volume
which contains the actual Ext Volume
. Subvolumes are managed through imagemounter.VolumeSystem`s, which is used by both the :class:`Volume
and Disk
classes.
Most operations are managed on a Volume
level, although individual disk file mounting (and volume detection) is performed on a Disk
level and reconstruction is performed on a ImageParser
level. This means the following main parts make up the Python package:
imagemounter.ImageParser
, maintaining a list of Disks, providing several methods that are carried out on all disks (e.g. mount) and reconstruct.imagemounter.Disk
, which represents a single disk iamge and can be mounted, and maintain volumes. It is also responsible for maintaining the write cache. Although a Disk is able to detect volumes, a Volume has similar capabilities.imagemounter.Volume
, which can detect its own type and fill its stats, can be mounted, and maintain subvolumes.imagemounter.VolumeSystem
, which is used to manage subvolumes and can detect volumes from a volume system.
All three classes maintain an init()
method that yields the volumes below it. You should call clean()
on the parser as soon as you are done; you may also call unmount()
on separate volumes or disks, which will also unmount all volumes below it. Warning: unmounting one of the RAID volumes in a RAID array, causes the entire array to be unmounted.
Reference¶
If you utilize the API, you typically only require the ImageParser
object, e.g.:
parser = ImageParser(['/path/to/disk'])
for v in parser.init():
print v.size
root = parser.reconstruct()
print root.mountpoint
parser.clean()
The best example of the use of the Python interface is the imount command. The entirety of all methods and attributes is documented below.
ImageParser¶
-
class
imagemounter.
ImageParser
(paths=(), force_disk_indexes=False, casename=None, read_write=False, disk_mounter=u'auto', volume_detector=u'auto', vstypes=None, fstypes=None, keys=None, mountdir=None, pretty=False, **args)¶ Root object of the
imagemounter
Python interface. This class should be sufficient allowing access to the underlying functions of this module.Instantiation of this class does not automatically mount, detect or analyse
Disk
s, though it initialises each provided path as a newDisk
object.Parameters: - paths (iterable) – list of paths to base images that should be mounted
- force_disk_indexes – if True, a Disk index is always included. If False, will only use Disk indexes if more than 1 Disk is provided to the paths
- casename – the name of the case, used when prettifying names
- read_write (bool) – indicates whether disks should be mounted with a read-write cache enabled
- disk_mounter (str) – the method to mount the base images with
- fstypes (dict) – dict mapping volume indices to file system types to use; use * and ? as volume indexes for additional control. Only when ?=none, unknown will not be used as fallback.
- keys (dict) – dict mapping volume indices to key material
- mountdir (str) – location where mountpoints are created, defaulting to a temporary location
- pretty (bool) – indicates whether pretty names should be used for the mountpoints
- args – ignored
-
add_disk
(path, force_disk_indexes=True, **args)¶ Adds a disk specified by the path to the ImageParser.
Parameters: - path – The path to the disk volume
- force_disk_indexes – If true, always uses disk indexes. If False, only uses disk indexes if this is the second volume you add. If you plan on using this method, always leave this True. If you add a second disk when the previous disk has no index, an error is raised.
- args – Arguments to pass to the constructor of the Disk.
-
init
(single=None, swallow_exceptions=True)¶ Handles all important disk-mounting tasks, i.e. calls the
Disk.init()
function on all underlying disks. It yields every volume that is encountered, including volumes that have not been mounted.Parameters: - single (bool|None) – indicates whether the
Disk
should be mounted as a single disk, not as a single disk or whether it should try both (defaults toNone
) - swallow_exceptions – specify whether you want the init calls to swallow exceptions
Return type: generator
- single (bool|None) – indicates whether the
-
init_volumes
(single=None, only_mount=None, swallow_exceptions=True)¶ Detects volumes (as volume system or as single volume) in all disks and yields the volumes. This calls
Disk.init_volumes()
on all disks and should be called aftermount_disks()
.Return type: generator
-
reconstruct
()¶ Reconstructs the filesystem of all volumes mounted by the parser by inspecting the last mount point and bind mounting everything.
Raises: NoRootFoundError if no root could be found Returns: the root Volume
-
clean
(remove_rw=False, allow_lazy=False)¶ Cleans all volumes of all disks (
Volume.unmount()
) and all disks (Disk.unmount()
). Volume errors are ignored, but returns immediately on disk unmount error.Parameters: - remove_rw (bool) – indicates whether a read-write cache should be removed
- allow_lazy (bool) – indicates whether lazy unmounting is allowed
Returns: whether the command completed successfully
Return type: boolean
Raises: - SubsystemError – when one of the underlying commands fails. Some are swallowed.
- CleanupError – when actual cleanup fails. Some are swallowed.
Most methods above, especially
init()
, handle most complicated tasks. However, you may need some more fine-grained control over the mount process, which may require you to use the following methods. Each of these methods passes their activities down to all disks in the parser and return whether it succeeded.-
rw_active
()¶ Indicates whether a read-write cache is active in any of the disks.
Return type: bool
-
get_volumes
()¶ Gets a list of all volumes of all disks, concatenating
Disk.get_volumes()
of all disks.Return type: list
-
get_by_index
(index)¶ Returns a Volume or Disk by its index.
-
mount_disks
()¶ Mounts all disks in the parser, i.e. calling
Disk.mount()
on all underlying disks. You probably want to useinit()
instead.Returns: whether all mounts have succeeded Return type: bool
For completeness, this is a list of all attributes of
ImageParser
:
Disk¶
-
class
imagemounter.
Disk
(parser, path, index=None, offset=0, block_size=512, read_write=False, vstype=u'', disk_mounter=u'auto', volume_detector=u'auto')¶ Representation of a disk, image file or anything else that can be considered a disk.
Instantiation of this class does not automatically mount, detect or analyse the disk. You will need the
init()
method for this.Only use arguments offset and further as keyword arguments.
Parameters: - parser (
ImageParser
) – the parent parser - path (str) – the path of the Disk
- index (str) – the base index of this Disk
- offset (int) – offset of the disk where the volume (system) resides
- block_size (int) –
- read_write (bool) – indicates whether the disk should be mounted with a read-write cache enabled
- vstype (str) – the volume system type to use.
- disk_mounter (str) – the method to mount the base image with
- volume_detector (str) – the volume system detection method to use
-
init
(single=None, only_mount=None, swallow_exceptions=True)¶ Calls several methods required to perform a full initialisation:
mount()
, andmount_volumes()
and yields all detected volumes.Parameters: single (bool|None) – indicates whether the disk should be mounted as a single disk, not as a single disk or whether it should try both (defaults to None
)Return type: generator
-
mount
()¶ Mounts the base image on a temporary location using the mount method stored in
method
. If mounting was successful,mountpoint
is set to the temporary mountpoint.If
read_write
is enabled, a temporary read-write cache is also created and stored inrwpath
.Returns: whether the mounting was successful Return type: bool
-
detect_volumes
(single=None)¶ Generator that detects the volumes from the Disk, using one of two methods:
- Single volume: the entire Disk is a single volume
- Multiple volumes: the Disk is a volume system
Parameters: single – If single is True
, this method will callinit_single_volumes()
. If single is False, onlyinit_multiple_volumes()
is called. If single is None,init_multiple_volumes()
is always called, being followed byinit_single_volume()
if no volumes were detected.
-
init_volumes
(single=None, only_mount=None, swallow_exceptions=True)¶ Generator that detects and mounts all volumes in the disk.
Parameters: - single – If single is
True
, this method will callinit_single_volumes()
. If single is False, onlyinit_multiple_volumes()
is called. If single is None,init_multiple_volumes()
is always called, being followed byinit_single_volume()
if no volumes were detected. - only_mount (list) – If set, must be a list of volume indexes that are only mounted.
- swallow_exceptions (bool) – If True, Exceptions are not raised but rather set on the instance.
- single – If single is
-
unmount
(remove_rw=False, allow_lazy=False)¶ Removes all ties of this disk to the filesystem, so the image can be unmounted successfully.
Raises: - SubsystemError – when one of the underlying commands fails. Some are swallowed.
- CleanupError – when actual cleanup fails. Some are swallowed.
The following methods are only required if you want some fine-grained control, typically if you are not using
init()
.-
get_disk_type
()¶
-
rw_active
()¶ Indicates whether anything has been written to a read-write cache.
-
get_fs_path
()¶ Returns the path to the filesystem. Most of the times this is the image file, but may instead also return the MD device or loopback device the filesystem is mounted to.
Return type: str
-
get_raw_path
()¶ Returns the raw path to the mounted disk image, i.e. the raw
.dd
,.raw
orewf1
file.Return type: str
-
get_volumes
()¶ Gets a list of all volumes in this disk, including volumes that are contained in other volumes.
The following attributes are also available:
-
index
¶ Disk index. May be None if it is the only disk of this type.
-
volumes
¶ VolumeSystem
of all direct child volumes of this disk, excluding all subvolumes. Seeget_volumes()
.
- parser (
Volume¶
-
class
imagemounter.
Volume
(disk, parent=None, index=u'0', size=0, offset=0, flag=u'alloc', slot=0, fstype=u'', key=u'', vstype=u'', volume_detector=u'auto')¶ Information about a volume. Note that every detected volume gets their own Volume object, though it may or may not be mounted. This can be seen through the
mountpoint
attribute – if it is not set, perhaps theexception
attribute is set with an exception.Creates a Volume object that is not mounted yet.
Only use arguments as keyword arguments.
Parameters: - disk (
Disk
) – the parent disk - parent – the parent volume or disk.
- index (str) – the volume index within its volume system, see the attribute documentation.
- size (int) – the volume size, see the attribute documentation.
- offset (int) – the volume offset, see the attribute documentation.
- flag (str) – the volume flag, see the attribute documentation.
- slot (int) – the volume slot, see the attribute documentation.
- fstype (str) – the fstype you wish to use for this Volume. May be ?<fstype> as a fallback value. If not specified, will be retrieved from the ImageParser instance instead.
- key (str) – the key to use for this Volume.
- vstype (str) – the volume system type to use.
- volume_detector (str) – the volume system detection method to use
-
init
(only_mount=None, swallow_exceptions=True)¶ Generator that mounts this volume and either yields itself or recursively generates its subvolumes.
More specifically, this function will call
load_fsstat_data()
(iff no_stats is False), followed bymount()
, followed by a call todetect_mountpoint()
, after whichself
is yielded, or the result of theinit()
call on each subvolume is yieldedParameters: - only_mount – if specified, only volume indexes in this list are mounted. Volume indexes are strings.
- swallow_exceptions – if True, any error occuring when mounting the volume is swallowed and added as an exception attribute to the yielded objects.
-
init_volume
(fstype=None)¶ Initializes a single volume. You should use this method instead of
mount()
if you want some sane checks before mounting.
-
unmount
(allow_lazy=False)¶ Unounts the volume from the filesystem.
Raises: - SubsystemError – if one of the underlying processes fails
- CleanupError – if the cleanup fails
The following methods offer some more information about the volume:
-
get_description
(with_size=True, with_index=True)¶ Obtains a generic description of the volume, containing the file system type, index, label and NTFS version. If with_size is provided, the volume size is also included.
-
get_safe_label
()¶ Returns a label that is safe to add to a path in the mountpoint for this volume.
-
get_formatted_size
()¶ Obtains the size of the volume in a human-readable format (i.e. in TiBs, GiBs or MiBs).
-
get_volumes
()¶ Recursively gets a list of all subvolumes and the current volume.
These functions offer access to some internals:
-
determine_fs_type
()¶ Determines the FS type for this partition. This function is used internally to determine which mount system to use, based on the file system description. Return values include ext, ufs, ntfs, lvm and luks.
Note: does not do anything if fstype is already set to something sensible.
-
get_raw_path
(include_self=False)¶ Retrieves the base mount path of the volume. Typically equals to
Disk.get_fs_path()
but may also be the path to a logical volume. This is used to determine the source path for a mount call.The value returned is normally based on the parent’s paths, e.g. if this volume is mounted to a more specific path, only its children return the more specific path, this volume itself will keep returning the same path. This makes for consistent use of the offset attribute. If you do not need this behaviour, you can override this with the include_self argument.
This behavior, however, is not retained for paths that directly affect the volume itself, not the child volumes. This includes VSS stores and LV volumes.
-
mount
(fstype=None)¶ Based on the file system type as determined by
determine_fs_type()
, the proper mount command is executed for this volume. The volume is mounted in a temporary path (or a pretty path ifpretty
is enabled) in the mountpoint as specified bymountpoint
.If the file system type is a LUKS container or LVM, additional methods may be called, adding subvolumes to
volumes
Raises: - NotMountedError – if the parent volume/disk is not mounted
- NoMountpointAvailableError – if no mountpoint was found
- NoLoopbackAvailableError – if no loopback device was found
- UnsupportedFilesystemError – if the fstype is not supported for mounting
- SubsystemError – if one of the underlying commands failed
-
bindmount
(mountpoint)¶ Bind mounts the volume to another mountpoint. Only works if the volume is already mounted.
Raises: - NotMountedError – when the volume is not yet mounted
- SubsystemError – when the underlying command failed
-
carve
(freespace=True)¶ Call this method to carve the free space of the volume for (deleted) files. Note that photorec has its own interface that temporarily takes over the shell.
Parameters: freespace (bool) – indicates whether the entire volume should be carved (False) or only the free space (True)
Returns: string to the path where carved data is available
Raises: - CommandNotFoundError – if the underlying command does not exist
- SubsystemError – if the underlying command fails
- NoMountpointAvailableError – if there is no mountpoint available
- NoLoopbackAvailableError – if there is no loopback available (only when volume has no slot number)
-
detect_volume_shadow_copies
()¶ Method to call vshadowmount and mount NTFS volume shadow copies.
Returns: iterable with the
Volume
objects of the VSSRaises: - CommandNotFoundError – if the underlying command does not exist
- SubSystemError – if the underlying command fails
- NoMountpointAvailableError – if there is no mountpoint available
-
detect_mountpoint
()¶ Attempts to detect the previous mountpoint if this was not done through
load_fsstat_data()
. This detection does some heuristic method on the mounted volume.
The following details may also be available as attributes:
-
size
¶ The size of the volume in bytes.
-
offset
¶ The offset of the volume in the disk in bytes.
-
index
¶ The index of the volume in the disk. If there are subvolumes, the index is separated by periods, though the exact format depends on the detection method and its format.
-
slot
¶ Internal slot number of the volume.
-
flag
¶ Indicates whether this volume is allocated (alloc), unallocated (unalloc) or a meta volume (meta).
-
block_size
¶ The block size of this volume.
-
fstype
¶ The volume file system type used internally as determined by
determine_fs_type()
.
-
key
¶ The key used by some crypto methods.
-
info
¶ A dict containing information about the volume. Not all keys are always available. Some common keys include:
- fsdescription – A description of the file system type, usually set by the detection method
- lastmountpoint – The last mountpoint of this volume. Set by
load_fsstat_data()
ordetect_mountpoint()
and only available for UFS and Ext volumes - label – The volume label as detected by
load_fsstat_data()
- version – The volume version as detected by
load_fsstat_data()
- statfstype – The volume file system type as detected by
load_fsstat_data()
- guid – The volume GUID
- volume_group – Used for LVM support
The contents of the info dict are not considered part of a stable API and are subject to change in the future.
-
loopback
¶ The loopback device used by the volume after
mount()
(or related methods) has been called.
-
was_mounted
¶ -
is_mounted
¶ Booleans indicating that the volume has successfully been mounted during its lifetime, and is currently mounted
-
volumes
¶ -
parent
¶ volumes
contains aVolumeSystem
of all subvolumes of this volume;parent
contains the parent volume (if any).
- disk (
VolumeSystem¶
-
class
imagemounter.
VolumeSystem
(parent, vstype=u'', volume_detector=u'')¶ A VolumeSystem is a collection of volumes. Every
Disk
contains exactly one VolumeSystem. Each system contains severalVolumes
, which, in turn, may contain additional volume systems.Creates a VolumeSystem.
Parameters: -
detect_volumes
(vstype=None, method=None, force=False)¶ Iterator for detecting volumes within this volume system.
Parameters:
-
preload_volume_data
()¶ Preloads volume data. It is used to call internal methods that contain information about a volume.
-
__iter__
()¶
-
__getitem__
(item)¶
-
volumes
¶ The list of all volumes in this system.
-
volume_source
¶ The source of the volumes of this system, either single or multi.
-
has_detected
¶ Boolean indicating whether this volume already ran its detection.
-
vstype
¶ -
detection
¶ -
args
¶ See the constructor of
VolumeSystem
.
-
Unmounter¶
-
class
imagemounter.
Unmounter
(casename=None, pretty=False, mountdir=None, allow_greedy=True, *args, **kwargs)¶ Allows easy unmounting of left-overs of ImageParser calls.
Instantiation of this class automatically indexes the mountpoints and loopbacks currently on the system. However, in the time between calling any
find
function and actually unmounting anything, the system may change. This can be especially painful when usingpreview_unmount()
.Parameters: - casename (str) – The casename to be unmounted, see
ImageParser
- pretty (bool) – Whether the volumes were mounted using pretty mount, see
Volume
- mountdir (str) – The mountdir wheret he volumes were mounted, see
Volume
- allow_greedy (bool) – When none of the parameters are specified, by default, a greedy method will try to find as much possible mount points as possible.
-
preview_unmount
()¶ Returns a list of all commands that would be executed if the
unmount()
method would be called.Note: any system changes between calling this method and calling
unmount()
aren’t listed by this command.
-
unmount
()¶ Calls all unmount methods in the correct order.
-
find_bindmounts
()¶ Finds all bind mountpoints that are inside mounts that match the
re_pattern
-
find_mounts
()¶ Finds all mountpoints that are mounted to a directory matching
re_pattern
or originate from a directory matchingorig_re_pattern
.
-
find_base_images
()¶ Finds all mountpoints that are mounted to a directory matching
orig_re_pattern
.
-
find_volume_groups
()¶ Finds all volume groups that are mounted through a loopback originating from
orig_re_pattern
.Generator yields tuples of vgname, pvname
-
find_loopbacks
()¶ Finds all loopbacks originating from
orig_re_pattern
.Generator yields device names
-
find_clean_dirs
()¶ Finds all (temporary) directories according to the glob and re patterns that should be cleaned.
-
unmount_bindmounts
()¶ Unmounts all bind mounts identified by
find_bindmounts()
-
unmount_mounts
()¶ Unmounts all mounts identified by
find_mounts()
-
unmount_base_images
()¶ Unmounts all mounts identified by
find_base_images()
-
unmount_volume_groups
()¶ Unmounts all volume groups and related loopback devices as identified by
find_volume_groups()
-
unmount_loopbacks
()¶ Unmounts all loopback devices as identified by
find_loopbacks()
-
clean_dirs
()¶ Does a final cleaning of the (temporary) directories according to
find_clean_dirs()
.
-
re_pattern
¶ The regex pattern used to look for volume mountpoints.
-
glob_pattern
¶ The glob pattern used to look for volume mountpoints. Always used in conjunction with the
re_pattern
.
-
orig_re_pattern
¶ The regex pattern used to look for base mountpoints.
-
orig_glob_pattern
¶ The glob pattern used to look for base mountpoints. Always used in conjunction with the
orig_re_pattern
.
-
be_greedy
¶ If set, some more volumes and mountpoints may be found.
- casename (str) – The casename to be unmounted, see