qubesadmin.tools package

Submodules

qubesadmin.tools.dochelpers module

Documentation helpers.

This module contains classes and functions which help to maintain documentation, particularly our custom Sphinx extension.

class qubesadmin.tools.dochelpers.CommandCheckVisitor(command, sub_commands, document)[source]

Bases: SparseNodeVisitor

Checks if the visited sub command section nodes and the specified sub command args are in sync.

check_undocumented_sub_commands()[source]

Call this to check if any undocumented sub_commands are left.

While the documentation talks about a ‘SparseNodeVisitor.depart_document()’ function, this function does not exists. (For details see implementation of NodeVisitor.dispatch_departure()) So we need to manually call this.

visit_Text(node)[source]

If the visited text node starts with ‘alias: ‘, all the provided comma separted alias in this node, are removed from self.sub_commands

visit_section(node)[source]

Checks if the visited sub-command section nodes exists and it options are in sync.

Uses OptionsCheckVisitor for checking sub-commands options

class qubesadmin.tools.dochelpers.ManpageCheckVisitor(app, command, document)[source]

Bases: SparseNodeVisitor

Checks if the sub-commands and options specified in the ‘COMMAND’ and ‘OPTIONS’ (case insensitve) sections in sync the command parser.

visit_section(node)[source]

If section title is OPTIONS or COMMANDS dispatch the apropriate NodeVisitor.

class qubesadmin.tools.dochelpers.OptionsCheckVisitor(command, args, document)[source]

Bases: SparseNodeVisitor

Checks if the visited option nodes and the specified args are in sync.

check_undocumented_arguments(ignored_options=None)[source]

Call this to check if any undocumented arguments are left.

While the documentation talks about a ‘SparseNodeVisitor.depart_document()’ function, this function does not exists. (For details see implementation of NodeVisitor.dispatch_departure()) So we need to manually call this.

visit_desc(node)[source]

Skips all but ‘option’ elements

visit_desc_name(node)[source]

Checks if the option is defined self.args

qubesadmin.tools.dochelpers.break_to_pdb(app, *_dummy)[source]

DEBUG

qubesadmin.tools.dochelpers.check_man_args(app, doctree, docname)[source]

Checks the manpage for undocumented or obsolete sub-commands and options.

qubesadmin.tools.dochelpers.make_rst_section(heading, char)[source]

Format a section header in rst

qubesadmin.tools.dochelpers.prepare_manpage(command)[source]

Build a man page skeleton

qubesadmin.tools.dochelpers.setup(app)[source]

Setup Sphinx extension

qubesadmin.tools.qubes_prefs module

Manipulate global properties.

qubesadmin.tools.qubes_prefs.get_parser()[source]

Prepare argument parser

qubesadmin.tools.qubes_prefs.main(args=None, app=None)[source]

qubesadmin.tools.qvm_backup module

qvm-backup tool

qubesadmin.tools.qvm_backup.main(args=None, app=None)[source]

Main function of qvm-backup tool

qubesadmin.tools.qvm_backup.print_progress(expected_profile, _subject, _event, backup_profile, progress)[source]

Event handler for reporting backup progress

qubesadmin.tools.qvm_backup.write_backup_profile(output_stream, args, passphrase=None)[source]

Format backup profile and print it to output_stream (a file or stdout)

Parameters:
  • output_stream – file-like object ro print the profile to

  • args – parsed arguments

  • passphrase – passphrase to use

qubesadmin.tools.qvm_backup_restore module

Console frontend for backup restore code

qubesadmin.tools.qvm_backup_restore.handle_broken(app, args, restore_info)[source]

Display information about problems with VMs selected for resetore

qubesadmin.tools.qvm_backup_restore.main(args=None, app=None)[source]

Main function of qvm-backup-restore

qubesadmin.tools.qvm_backup_restore.print_backup_log(backup_log)[source]

Print a log on stdout, coloring it red if it’s a terminal

qubesadmin.tools.qvm_check module

Exits sucessfull if the provided domain(s) exist, else returns failure

class qubesadmin.tools.qvm_check.QvmCheckArgumentParser(description)[source]

Bases: QubesArgumentParser

Extended argument parser for qvm-check to collect invalid domains

class qubesadmin.tools.qvm_check.QvmCheckVmNameAction(option_strings, nargs=1, dest='vmnames', help=None, **kwargs)[source]

Bases: VmNameAction

Action for parsing one or multiple valid/invalid VMNAMEs

parse_qubes_app(parent_parser, namespace)[source]

Set namespace.domains to values

qubesadmin.tools.qvm_check.get_filters(args)[source]

Get status and check functions

qubesadmin.tools.qvm_check.main(args=None, app=None)[source]

Main function of qvm-check tool

qubesadmin.tools.qvm_check.print_msg(log, domains, status)[source]

Print message in appropriate form about given valid domain(s)

qubesadmin.tools.qvm_clone module

Clone a domain

qubesadmin.tools.qvm_clone.main(args=None, app=None)[source]

Clones an existing VM by copying all its disk files

qubesadmin.tools.qvm_create module

qvm-create tool

qubesadmin.tools.qvm_create.main(args=None, app=None)[source]

Main function of qvm-create tool

qubesadmin.tools.qvm_device module

Qubes volume and block device management

class qubesadmin.tools.qvm_device.DeviceAction(help='A backend, port & device id combination', required=True, allow_unknown=False, only_port=False, **kwargs)[source]

Bases: QubesAction

Action for argument parser that gets the :py:class:qubesadmin.device_protocol.VirtualDevice from a BACKEND:PORT_ID:DEVICE_ID string.

parse_qubes_app(parser, namespace)[source]

This method is called by qubes.tools.QubesArgumentParser after namespace.app is instantiated.

Used to initialize values based on namespace.app.

class qubesadmin.tools.qvm_device.Line(device: DeviceInfo, assignment=False)[source]

Bases: object

Helper class to hold single device info for listing

property assignments

list of frontends the device is assigned to

qubesadmin.tools.qvm_device.assign_device(args)[source]

Called by the parser to execute the qvm-devices assign subcommand.

qubesadmin.tools.qvm_device.attach_device(args)[source]

Called by the parser to execute the qvm-devices attach subcommand.

qubesadmin.tools.qvm_device.detach_device(args)[source]

Called by the parser to execute the qvm-devices detach subcommand.

qubesadmin.tools.qvm_device.get_parser(device_class=None)[source]

Create argparse.ArgumentParser suitable for qvm-block.

qubesadmin.tools.qvm_device.info_device(args)[source]

Called by the parser to execute the qvm-devices info subcommand.

qubesadmin.tools.qvm_device.init_list_parser(sub_parsers)[source]

Configures the parser for the qvm-devices list subcommand

qubesadmin.tools.qvm_device.is_on_deny_list(device, dest_vm)[source]

Checks if any interface of the device is on the deny list for dest_vm vm.

qubesadmin.tools.qvm_device.list_devices(args)[source]

Called by the parser to execute the qubes-devices list subcommand.

qubesadmin.tools.qvm_device.main(args=None, app=None)[source]

Main routine of qvm-block.

qubesadmin.tools.qvm_device.parse_ro_option_as_read_only(options)[source]

For backward compatibility.

Read-only option could be represented as –ro, -o read-only=yes or -o ro=True etc.

qubesadmin.tools.qvm_device.prepare_table(dev_list, with_sbdf=False)[source]

Converts a list of qubes.devices.DeviceInfo objects to a list of tuples for the qubes.tools.print_table().

If qvm-devices is running in a TTY, it will omit duplicate data.

Parameters:
  • dev_list (iterable) – List of qubes.devices.DeviceInfo objects.

  • with_sbdf (bool) – when True, include SBDF identifier of PCI device

Returns:

list of tuples

qubesadmin.tools.qvm_device.unassign_device(args)[source]

Called by the parser to execute the qvm-devices unassign subcommand.

qubesadmin.tools.qvm_features module

qvm-features - Manage domain’s features

qubesadmin.tools.qvm_features.main(args=None, app=None)[source]

Main routine of qvm-features.

Parameters:

args (list) – Optional arguments to override those delivered from command line.

qubesadmin.tools.qvm_firewall module

qvm-firewall tool

class qubesadmin.tools.qvm_firewall.RuleAction(option_strings, dest, nargs=None, const=None, default=None, type=None, choices=None, required=False, help=None, metavar=None)[source]

Bases: Action

Parser action for a single firewall rule. It accept syntax:
  • <action> [<dsthost> [<proto> [<dstports>|<icmptype>]]]

  • action=<action> [specialtarget=dns] [dsthost=<dsthost>] [proto=<proto>] [dstports=<dstports>] [icmptype=<icmptype>]

Or a mix of them.

qubesadmin.tools.qvm_firewall.main(args=None, app=None)[source]

Main routine of qvm-firewall.

qubesadmin.tools.qvm_firewall.rules_add(vm, args)[source]

Add a rule defined by args.rule

qubesadmin.tools.qvm_firewall.rules_del(vm, args)[source]

Delete a rule according to args.rule/args.rule_no

qubesadmin.tools.qvm_firewall.rules_list_raw(vm)[source]

Print rules in machine-readable form (as specified in Admin API)

Parameters:

vm – VM object

Returns:

None

qubesadmin.tools.qvm_firewall.rules_list_table(vm)[source]

Print rules to stdout in human-readable form (table)

Parameters:

vm – VM object

Returns:

None

qubesadmin.tools.qvm_kill module

Immediately terminate a qube without a graceful shutdown sequence.

qubesadmin.tools.qvm_kill.main(args=None, app=None)[source]
async qubesadmin.tools.qvm_kill.run_async(args=None, app=None)[source]

qubesadmin.tools.qvm_ls module

qvm-ls - List available domains

class qubesadmin.tools.qvm_ls.Column(head: str, attr: str | Callable[[QubesVM], object], doc: str | None = None)[source]

Bases: object

A column in qvm-ls output.

Parameters:
  • head (str) – Column head (usually uppercase).

  • attr – Attribute path (dotted string) or callable (vm) -> value.

  • doc (str) – Description of column (will be visible in –help-columns).

cell(vm, insertion=0)[source]

Format one cell, handling tree indentation for the NAME column.

Parameters:
  • vm – Domain to get a value from.

  • insertion – Tree depth; shifts NAME value to the right.

Returns:

string to display

columns = {'CLASS': Column(head='CLASS'), 'DISK': Column(head='DISK'), 'FLAGS': Column(head='FLAGS'), 'GATEWAY': Column(head='GATEWAY'), 'MEMORY': Column(head='MEMORY'), 'PRIV-CURR': Column(head='PRIV-CURR'), 'PRIV-MAX': Column(head='PRIV-MAX'), 'PRIV-POOL': Column(head='PRIV-POOL'), 'PRIV-USED': Column(head='PRIV-USED'), 'ROOT-CURR': Column(head='ROOT-CURR'), 'ROOT-MAX': Column(head='ROOT-MAX'), 'ROOT-POOL': Column(head='ROOT-POOL'), 'ROOT-USED': Column(head='ROOT-USED'), 'STATE': Column(head='STATE')}

collection of all columns

format(vm: QubesVM) str | None[source]

Return the cell value for vm, or None if not applicable.

class qubesadmin.tools.qvm_ls.PropertyColumn(name)[source]

Bases: Column

Column that displays a VM property by name.

Parameters:

name – Name of VM property.

class qubesadmin.tools.qvm_ls.Table(domains, colnames, spinner, *, raw_data=False, tree_sorted=False, sort_order='NAME', reverse_sort=False, ignore_case=False)[source]

Bases: object

Table that is displayed to the user.

Parameters:
  • domains – Domains to include in the table.

  • colnames (list) – Names of the columns (need not to be uppercase).

get_head()[source]

Get table head data (all column heads).

get_row(vm, insertion=0)[source]

Get single table row data (all columns for one domain).

sort_to_tree(domains)[source]

Sort the domains as a network tree. It returns a list of sets. Each tuple stores the insertion of the cell name and the vm object.

Parameters:

domains (list()) – The domains which will be sorted

Return list(tuple()) tree:

returns a list of tuple(insertion, vm)

tree_append_child(parent, level)[source]

Concatenate the network children of the vm to a list.

Parameters:

qubes.vm.qubesvm.QubesVM – Parent vm of the children VMs

write_table(stream=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]

Sort & write whole table to file-like object.

Parameters:

stream (file) – Stream to write the table to.

qubesadmin.tools.qvm_ls.calc_size(vm, volume_name)[source]

Calculates the volume size in MiB

qubesadmin.tools.qvm_ls.calc_usage(vm, volume_name)[source]

Calculates the volume usage in MiB

qubesadmin.tools.qvm_ls.calc_used(vm, volume_name)[source]

Calculates the volume usage in percent

qubesadmin.tools.qvm_ls.formats = {'disk': ('name', 'state', 'disk', 'priv-curr', 'priv-max', 'priv-used', 'root-curr', 'root-max', 'root-used'), 'full': ('name', 'state', 'class', 'label', 'qid', 'xid', 'uuid'), 'kernel': ('name', 'state', 'class', 'template', 'kernel', 'kernelopts'), 'network': ('name', 'state', 'netvm', 'ip', 'ipback', 'gateway'), 'prefs': ('name', 'label', 'template', 'netvm', 'vcpus', 'initialmem', 'maxmem', 'virt_mode'), 'simple': ('name', 'state', 'class', 'label', 'template', 'netvm')}

Available formats. Feel free to plug your own one.

qubesadmin.tools.qvm_ls.get_parser()[source]

Create argparse.ArgumentParser suitable for qvm-ls.

qubesadmin.tools.qvm_ls.main(args=None, app=None)[source]

Main routine of qvm-ls.

Parameters:
  • args (list) – Optional arguments to override those delivered from command line.

  • app – Operate on given app object instead of instantiating new one.

qubesadmin.tools.qvm_ls.matches_power_states(domain, **states)[source]

Filter domains by their power state

qubesadmin.tools.qvm_pause module

qvm-pause - Pause a domain

qubesadmin.tools.qvm_pause.main(args=None, app=None)[source]

Main routine of qvm-pause.

Parameters:

args (list) – Optional arguments to override those delivered from command line.

qubesadmin.tools.qvm_pool module

Manages Qubes pools and their options

qubesadmin.tools.qvm_pool.add_pool(args)[source]

Adds a new pool

qubesadmin.tools.qvm_pool.get_parser()[source]

Creates argparse.ArgumentParser suitable for qvm-pool.

qubesadmin.tools.qvm_pool.info_pools(args)[source]

Prints info about the specified pools

qubesadmin.tools.qvm_pool.init_add_parser(sub_parsers)[source]

Adds ‘add’ action related options

qubesadmin.tools.qvm_pool.init_info_parser(sub_parsers)[source]

Adds ‘info’ action related options

qubesadmin.tools.qvm_pool.init_list_parser(sub_parsers)[source]

Adds ‘list’ action related options

qubesadmin.tools.qvm_pool.init_remove_parser(sub_parsers)[source]

Adds ‘remove’ action related options

qubesadmin.tools.qvm_pool.init_set_parser(sub_parsers)[source]

Adds ‘set’ action related options

qubesadmin.tools.qvm_pool.list_drivers(args)[source]

Lists all drivers with their options

qubesadmin.tools.qvm_pool.list_pools(args)[source]

Lists all available pools

qubesadmin.tools.qvm_pool.main(args=None, app=None)[source]

Main routine of qvm-pool.

qubesadmin.tools.qvm_pool.remove_pools(args)[source]

Removes the specified pools

qubesadmin.tools.qvm_pool.set_pool(args)[source]

Modifies driver options for a pool

qubesadmin.tools.qvm_pool.uses_legacy_options(args, app)[source]

Checks if legacy options and used, and invokes the legacy tool

qubesadmin.tools.qvm_prefs module

Manipulate VM properties.

qubesadmin.tools.qvm_prefs.get_parser(vmname_nargs=1)[source]

Return argument parser for generic property-related tool

qubesadmin.tools.qvm_prefs.main(args=None, app=None)[source]
qubesadmin.tools.qvm_prefs.process_actions(parser, args, target)[source]

Handle actions for generic property-related tool

Parameters:
  • parser – argument parser used to produce args

  • args – arguments to handle

  • target – object on which actions should be performed

qubesadmin.tools.qvm_remove module

Remove domains from the system

qubesadmin.tools.qvm_remove.main(args=None, app=None)[source]

qubesadmin.tools.qvm_run module

qvm-run tool

qubesadmin.tools.qvm_run.has_gui(qube) bool[source]

Returns True if qube can have a GUI.

qubesadmin.tools.qvm_run.main(args=None, app=None)[source]

Main function of qvm-run tool

qubesadmin.tools.qvm_run.print_no_color(msg, file, color)[source]

Print a msg to file without coloring it. Namely reset to base color first, print a message, then restore color.

qubesadmin.tools.qvm_run.run_command_single(args, vm)[source]

Handle a single VM to run the command in

qubesadmin.tools.qvm_service module

qvm-service - Manage domain’s services

qubesadmin.tools.qvm_service.main(args=None, app=None)[source]

Main routine of qvm-features.

Parameters:

args (list) – Optional arguments to override those delivered from command line.

qubesadmin.tools.qvm_service.parse_bool(value)[source]

Convert string value to bool according to well known representations

It accepts (case-insensitive) '0', 'no' and false as

False and '1', 'yes' and 'true' as True.

qubesadmin.tools.qvm_shutdown module

Shutdown a qube

qubesadmin.tools.qvm_shutdown.main(args=None, app=None)[source]
async qubesadmin.tools.qvm_shutdown.run_async(args=None, app=None)[source]
async qubesadmin.tools.qvm_shutdown.shutdown(domains, **shutdown_kwargs)[source]

qubesadmin.tools.qvm_start module

qvm-start - start a domain

qubesadmin.tools.qvm_start.main(args=None, app=None)[source]

Main routine of qvm-start.

Parameters:

args (list) – Optional arguments to override those delivered from command line.

async qubesadmin.tools.qvm_start.run_async(args=None, app=None)[source]

qubesadmin.tools.qvm_start_daemon module

GUI/AUDIO daemon launcher tool

class qubesadmin.tools.qvm_start_daemon.DAEMONLauncher(app: QubesBase, enabled_services, vm_names=None, kde=False)[source]

Bases: object

Launch GUI/AUDIO daemon for VMs

cleanup_guid(xid)[source]

Clean up after qubes-guid.

Removes the auto-generated configuration file, if any.

cleanup_pacat_process(xid)[source]

Clean up after pacat-simple-vchan.

Removes the auto-generated configuration file, if any.

common_guid_args(vm)[source]

Common qubes-guid arguments for PV(H), HVM and Stubdomain

static guid_config_file(xid)[source]

Helper function to construct a GUI configuration file path

static guid_pidfile(xid)[source]

Helper function to construct a GUI pidfile path

is_watched(vm)[source]

Should we watch this VM for changes

static kde_guid_args(vm)[source]

Return KDE-specific arguments for gui-daemon, if applicable

on_connection_established(_subject, _event, **_kwargs)[source]

Handler of ‘connection-established’ event, used to launch GUI/AUDIO daemon for domains started before this tool.

on_domain_spawn(vm, _event, **kwargs)[source]

Handler of ‘domain-spawn’ event, starts GUI daemon for stubdomain

on_domain_start(vm, _event, **kwargs)[source]

Handler of ‘domain-start’ event, starts GUI/AUDIO daemon for actual VM

on_domain_stopped(vm, _event, **_kwargs)[source]

Handler of ‘domain-stopped’ event, cleans up

on_property_audiovm_set(vm, event, **kwargs)[source]

Handler for catching event related to dynamic AudioVM set/unset

on_property_preload_set(vm, _event, **_kwargs)[source]

Handler of ‘property-reset:is_preload’ event, used to launch GUI/AUDIO daemon after preload is marked as used.

static pacat_domid(vm)[source]

Determine target domid for an AUDIO daemon

static pacat_pidfile(xid)[source]

Helper function to construct an AUDIO pidfile path

register_events(events)[source]

Register domain startup events in app.events dispatcher

async send_monitor_layout(vm, layout=None, startup=False)[source]

Send monitor layout to a given VM

This function is a coroutine.

Parameters:
  • vm – VM to which send monitor layout

  • layout – monitor layout to send; if None, fetch it from local X server.

  • startup

Returns:

None

send_monitor_layout_all()[source]

Send monitor layout to all (running) VMs

async start_audio(vm)[source]

Start AUDIO daemon regardless of start event.

This function is a coroutine.

Parameters:

vm – VM for which AUDIO daemon should be started

async start_audio_for_vm(vm)[source]

Start AUDIO daemon (pacat-simple-vchan) connected directly to a VM

This function is a coroutine.

Parameters:

vm – VM for which start AUDIO daemon

async start_gui(vm, force_stubdom=False, monitor_layout=None)[source]

Start GUI daemon regardless of start event.

This function is a coroutine.

Parameters:
  • vm – VM for which GUI daemon should be started

  • force_stubdom – Force GUI daemon for stubdomain, even if the one for target AppVM is running.

  • monitor_layout – monitor layout configuration

async start_gui_for_stubdomain(vm, force=False)[source]

Start GUI daemon (qubes-guid) connected to a stubdomain

This function is a coroutine.

async start_gui_for_vm(vm, monitor_layout=None)[source]

Start GUI daemon (qubes-guid) connected directly to a VM

This function is a coroutine.

Parameters:
  • vm – VM for which start GUI daemon

  • monitor_layout – monitor layout to send; if None, fetch it from local X server.

static write_guid_config(config_path, config)[source]

Write guid configuration to a file

class qubesadmin.tools.qvm_start_daemon.KeyboardLayout(binary_string)[source]

Bases: object

Class to store and parse X Keyboard layout data

get_property(layout_num)[source]

Return the selected keyboard layout as formatted for keyboard_layout property.

class qubesadmin.tools.qvm_start_daemon.XWatcher(conn, app)[source]

Bases: object

Watch and react for X events related to the keyboard layout changes.

event_reader(callback)[source]

Poll for X events related to keyboard layout

get_keyboard_layout()[source]

Check what is current keyboard layout definition

get_selected_layout()[source]

Check which keyboard layout is currently selected

initialize_extension()[source]

Initialize XKB extension (not supported by xcffib by default

update_keyboard_layout()[source]

Update current vm’s keyboard_layout property

qubesadmin.tools.qvm_start_daemon.escape_config_string(value)[source]

Convert a string to libconfig format.

Format specification: http://www.hyperrealm.com/libconfig/libconfig_manual.html#String-Values

See dump_string() for python-libconf: https://github.com/Grk0/python-libconf/blob/master/libconf.py

qubesadmin.tools.qvm_start_daemon.get_monitor_layout()[source]

Get list of monitors and their size/position

qubesadmin.tools.qvm_start_daemon.main()[source]

Main function of qvm-start-daemon tool

qubesadmin.tools.qvm_start_daemon.retrieve_gui_daemon_options(vm, guivm)[source]

Construct a list of GUI daemon options based on VM features.

This checks ‘gui-’ features on the VM, and if they’re absent, ‘gui-default-’ features on the GuiVM.

qubesadmin.tools.qvm_start_daemon.serialize_gui_daemon_options(options)[source]

Prepare configuration file content for GUI daemon. Currently, uses libconfig format.

qubesadmin.tools.qvm_start_daemon.validator_color(color: str) bool[source]

xside.c parse_color validation code is replicated here

qubesadmin.tools.qvm_start_daemon.validator_key_sequence(sequence: str) bool[source]

xside.c key sequence validation is not case sensitive and supports more choices than Global Config’s limited choices, so we replicate it here

qubesadmin.tools.qvm_start_daemon.validator_trayicon_mode(mode: str) bool[source]

xside.c tray mode validation is replicated here

qubesadmin.tools.qvm_tags module

qvm-tags - Manage domain’s tags

qubesadmin.tools.qvm_tags.get_parser()[source]

Return qvm-tags tool command line parser

qubesadmin.tools.qvm_tags.main(args=None, app=None)[source]

Main routine of qvm-tags.

Parameters:

args (list) – Optional arguments to override those delivered from command line.

qubesadmin.tools.qvm_tags.mode_add(args)[source]

Add tag

qubesadmin.tools.qvm_tags.mode_del(args)[source]

Delete tag

qubesadmin.tools.qvm_tags.mode_query(args)[source]

Query/list tags

qubesadmin.tools.qvm_template module

Tool for managing VM templates.

exception qubesadmin.tools.qvm_template.AlreadyRunning[source]

Bases: Exception

Another qvm-template is already running

class qubesadmin.tools.qvm_template.DlEntry(evr: Tuple[str, str, str], reponame: str, dlsize: int)[source]

Bases: NamedTuple

Information about a template to be downloaded.

dlsize: int

Alias for field number 2

evr: Tuple[str, str, str]

Alias for field number 0

reponame: str

Alias for field number 1

class qubesadmin.tools.qvm_template.RepoOptCallback(option_strings, dest, nargs=None, const=None, default=None, type=None, choices=None, required=False, help=None, metavar=None)[source]

Bases: Action

Parser action for storing repository related options, like –enablerepo, –disablerepo, etc. Store them in a single list, to preserve relative order.

exception qubesadmin.tools.qvm_template.SignatureVerificationError[source]

Bases: Exception

Package signature is invalid or missing

class qubesadmin.tools.qvm_template.Template(name: str, epoch: str, version: str, release: str, reponame: str, dlsize: int, buildtime: datetime, licence: str, url: str, summary: str, description: str)[source]

Bases: NamedTuple

Details of a template.

buildtime: datetime

Alias for field number 6

description: str

Alias for field number 10

dlsize: int

Alias for field number 5

epoch: str

Alias for field number 1

property evr

Return a tuple of (EPOCH, VERSION, RELEASE)

licence: str

Alias for field number 7

name: str

Alias for field number 0

release: str

Alias for field number 3

reponame: str

Alias for field number 4

summary: str

Alias for field number 9

url: str

Alias for field number 8

version: str

Alias for field number 2

class qubesadmin.tools.qvm_template.TemplateState(value)[source]

Bases: Enum

Enum representing the state of a template.

AVAILABLE = 'available'
EXTRA = 'extra'
INSTALLED = 'installed'
UPGRADABLE = 'upgradable'
title() str[source]

Return a long description of the state. Can be used as headings.

class qubesadmin.tools.qvm_template.VersionSelector(value)[source]

Bases: Enum

Enum representing how the candidate template version is chosen.

LATEST = 1

Install latest version.

LATEST_HIGHER = 4

Upgrade to the highest version that is higher than the current one.

LATEST_LOWER = 3

Downgrade to the highest version that is lower than the current one.

REINSTALL = 2

Reinstall current version.

qubesadmin.tools.qvm_template.build_version_str(evr: Tuple[str, str, str]) str[source]

Return version string described by evr, which is in (epoch, version, release) format.

qubesadmin.tools.qvm_template.clean(args: Namespace, app: QubesBase) None[source]

Command that cleans the local package cache.

Parameters:
  • args – Arguments received by the application.

  • app – Qubes application object

qubesadmin.tools.qvm_template.confirm_action(msg: str, affected: List[str]) None[source]

Confirm user action.

qubesadmin.tools.qvm_template.download(args: Namespace, app: QubesBase, path_override: str | None = None, dl_list: Dict[str, DlEntry] | None = None, version_selector: VersionSelector = VersionSelector.LATEST) Dict[str, rpm.hdr][source]

Command that downloads template packages.

Parameters:
  • args – Arguments received by the application.

  • app – Qubes application object

  • path_override – Override path to store downloads. If not set or set to None, args.downloaddir is used. Optional

  • dl_list – Override list of templates to download. If not set or set to None, get_dl_list is called, which generates the list from args. Optional

  • version_selector – Specify algorithm to select the candidate version of a package. Defaults to VersionSelector.LATEST

Returns:

package headers of downloaded templates

qubesadmin.tools.qvm_template.extract_rpm(name: str, path: str, target: str) bool[source]
Extract a template RPM package.

If the package contains root.img file split across multiple parts, only the first 512 bytes of the 00 part is retained (tar header) and a symlink to the rpm file is created in target directory.

Parameters:
  • name – Name of the template

  • path – Location of the RPM package

  • target – Target path to extract to

Returns:

Whether the extraction succeeded

qubesadmin.tools.qvm_template.filter_version(query_res, app: QubesBase, version_selector: VersionSelector = VersionSelector.LATEST)[source]

Select only one version for given template name

qubesadmin.tools.qvm_template.get_dl_list(args: Namespace, app: QubesBase, version_selector: VersionSelector = VersionSelector.LATEST) Dict[str, DlEntry][source]

Return list of templates that needs to be downloaded.

Parameters:
  • args – Arguments received by the application.

  • app – Qubes application object

  • version_selector – Specify algorithm to select the candidate version of a package. Defaults to VersionSelector.LATEST

Returns:

Dictionary that maps to DlEntry the names of templates that needs to be downloaded

qubesadmin.tools.qvm_template.get_keys_for_repos(repo_files: List[str], releasever: str) Dict[str, str][source]

List gpg keys

Returns a dict reponame -> key path

qubesadmin.tools.qvm_template.get_managed_template_vm(app: QubesBase, name: str) QubesVM[source]

Return the QubesVM object associated with the given name if it exists and is managed by qvm-template, otherwise raise a parser error.

qubesadmin.tools.qvm_template.get_parser() ArgumentParser[source]

Generate argument parser for the application.

qubesadmin.tools.qvm_template.install(args: Namespace, app: QubesBase, version_selector: VersionSelector = VersionSelector.LATEST, override_existing: bool = False) None[source]

Command that installs template packages.

This command creates a lock file to ensure that two instances are not running at the same time.

Parameters:
  • args – Arguments received by the application.

  • app – Qubes application object

  • version_selector – Specify algorithm to select the candidate version of a package. Defaults to VersionSelector.LATEST

  • override_existing – Whether to override existing packages. Used for reinstall, upgrade, and downgrade operations

qubesadmin.tools.qvm_template.is_managed_template(vm: QubesVM) bool[source]

Return whether the VM is managed by qvm-template.

qubesadmin.tools.qvm_template.is_match_spec(name: str, epoch: str, version: str, release: str, spec: str) Tuple[bool, float][source]

Check whether (name, epoch, version, release) matches the spec string.

For the algorithm, refer to section “NEVRA Matching” in the DNF documentation.

Note that currently arch is ignored as the templates should be of noarch.

Returns:

A tuple. The first element indicates whether there is a match; the second element represents the priority of the match (lower is better)

qubesadmin.tools.qvm_template.list_templates(args: Namespace, app: QubesBase, command: str) None[source]

Command that lists templates.

Parameters:
  • args – Arguments received by the application.

  • app – Qubes application object

  • command – If set to list, display a listing similar to dnf list. If set to info, display detailed template information similar to dnf info. Otherwise, an AssertionError is raised.

qubesadmin.tools.qvm_template.locked(func)[source]

Execute given function under a lock in LOCK_FILE

qubesadmin.tools.qvm_template.main(args: Sequence[str] | None = None, app: QubesBase | None = None) int[source]

Main routine of qvm-template.

Parameters:
  • args – Override arguments received by the application. Optional

  • app – Override Qubes application object. Optional

Returns:

Return code of the application

qubesadmin.tools.qvm_template.migrate_from_rpmdb(app)[source]

Migrate templates stored in rpmdb, into ‘features’ set on the VM itself.

qubesadmin.tools.qvm_template.qrexec_download(args: Namespace, app: QubesBase, spec: str, path: str, key: str, dlsize: int | None = None, refresh: bool = False) None[source]

Download a template from repositories.

Parameters:
  • args – Arguments received by the application. Specifically, args.{enablerepo,disablerepo,repoid,releasever,repo_files,updatevm, quiet} are used

  • app – Qubes application object

  • spec – Package spec to query (refer to <package-name-spec> in the DNF documentation)

  • path – Path to place the downloaded template

  • dlsize – Size of template to be downloaded. Used for the progress bar. Optional

  • refresh – Whether to force refresh repo metadata. Defaults to False

Raises:

ConnectionError – if the qrexec call fails

qubesadmin.tools.qvm_template.qrexec_payload(args: Namespace, app: QubesBase, spec: str, refresh: bool) str[source]

Return payload string for the qubes.Template* qrexec calls.

Parameters:
  • args – Arguments received by the application. Specifically, args.{enablerepo,disablerepo,repoid,releasever,repo_files} are used

  • app – Qubes application object

  • spec – Package spec to query (refer to <package-name-spec> in the DNF documentation)

  • refresh – Whether to force refresh repo metadata

Returns:

Payload string

Raises:

Parser error if spec equals --- or input contains \n

qubesadmin.tools.qvm_template.qrexec_popen(args: Namespace, app: QubesBase, service: str, stdout: int | IO = -1, filter_esc: bool = True) Popen[source]

Return Popen object that communicates with the given qrexec call in args.updatevm.

Note that this falls back to invoking /etc/qubes-rpc/* directly if args.updatevm is empty string.

Parameters:
  • args – Arguments received by the application. args.updatevm is used

  • app – Qubes application object

  • service – The qrexec call to invoke

  • stdout

    Where the process stdout points to. This is passed directly to subprocess.Popen. Defaults to subprocess.PIPE

    Note that stderr is always set to subprocess.PIPE

  • filter_esc – Whether to filter out escape sequences from stdout/stderr. Defaults to True

Returns:

Popen object that communicates with the given qrexec call

qubesadmin.tools.qvm_template.qrexec_repoquery(args: Namespace, app: QubesBase, spec: str = '*', refresh: bool = False) List[Template][source]

Query template information from repositories.

Parameters:
  • args – Arguments received by the application. Specifically, args.{enablerepo,disablerepo,repoid,releasever,repo_files,updatevm} are used

  • app – Qubes application object

  • spec – Package spec to query (refer to <package-name-spec> in the DNF documentation). Defaults to *

  • refresh – Whether to force refresh repo metadata. Defaults to False

Raises:

ConnectionError – if the qrexec call fails

Returns:

List of Template objects representing the result of the query

qubesadmin.tools.qvm_template.qubes_release() str[source]

Return the Qubes release.

qubesadmin.tools.qvm_template.query_local(vm: QubesVM) Template[source]

Return Template object associated with vm.

Requires the VM to be managed by qvm-template.

qubesadmin.tools.qvm_template.query_local_evr(vm: QubesVM) Tuple[str, str, str][source]

Return the (epoch, version, release) of vm.

Requires the VM to be managed by qvm-template.

qubesadmin.tools.qvm_template.remove(args: Namespace, app: QubesBase, disassoc: bool = False, purge: bool = False, dummy: str = 'dummy') None[source]

Command that remove templates.

Parameters:
  • args – Arguments received by the application.

  • app – Qubes application object

  • disassoc – Whether to disassociate VMs from the templates

  • purge – Whether to remove VMs based on the templates

  • dummy – Name of dummy VM if disassoc is used

qubesadmin.tools.qvm_template.repolist(args: Namespace, app: QubesBase) None[source]

Command that lists configured repositories.

Parameters:
  • args – Arguments received by the application.

  • app – Qubes application object

qubesadmin.tools.qvm_template.search(args: Namespace, app: QubesBase) None[source]

Command that searches template details for given patterns.

Parameters:
  • args – Arguments received by the application.

  • app – Qubes application object

qubesadmin.tools.qvm_template.verify_rpm(path: str, key: str, *, nogpgcheck: bool = False, template_name: str | None = None) rpm.hdr[source]

Verify the digest and signature of a RPM package and return the package header.

Note that verifying RPMs this way is prone to TOCTOU. This is okay for local files, but may create problems if multiple instances of qvm-template are downloading the same file, so a lock is needed in that case.

Parameters:
  • path – Location of the RPM package

  • nogpgcheck – Whether to allow invalid GPG signatures

  • template_name – expected template name - if specified, verifies if the package name matches expected template name

Returns:

RPM package header. If verification fails, raises an exception.

qubesadmin.tools.qvm_template_postprocess module

Tool for importing rpm-installed template

async qubesadmin.tools.qvm_template_postprocess.call_postinstall_service(vm)[source]

Call qubes.PostInstall service

And adjust related settings (netvm, features).

qubesadmin.tools.qvm_template_postprocess.get_root_img_size(source_dir)[source]

Extract size of root.img to be imported

qubesadmin.tools.qvm_template_postprocess.import_appmenus(vm, source_dir, skip_generate=True)[source]

Import appmenus settings into VM object (later: GUI VM)

Parameters:
  • vm – QubesVM object of just imported template

  • source_dir – directory with source files

  • skip_generate – do not generate actual menu entries, only set item lists

qubesadmin.tools.qvm_template_postprocess.import_root_img(vm, source_dir)[source]

Import root.img into VM object

qubesadmin.tools.qvm_template_postprocess.import_template_config(args, conf_path, vm)[source]

Parse template.conf and apply its content to the just installed TemplateVM

Parameters:
  • args – arguments for qvm-template-postprocess (used for –allow-pv option and possibly some other in the future)

  • conf_path – path to the template.conf

  • vm – Template to operate on

Returns:

qubesadmin.tools.qvm_template_postprocess.is_chroot()[source]

Detect if running inside chroot

qubesadmin.tools.qvm_template_postprocess.main(args=None, app=None)[source]

Main function of qvm-template-postprocess

qubesadmin.tools.qvm_template_postprocess.parse_template_config(path)[source]

Parse template.conf from template package. (KEY=VALUE format)

async qubesadmin.tools.qvm_template_postprocess.post_install(args)[source]

Handle post-installation tasks

qubesadmin.tools.qvm_template_postprocess.pre_remove(args)[source]

Handle pre-removal tasks

qubesadmin.tools.qvm_template_postprocess.reset_private_img(vm)[source]

Clear private volume

qubesadmin.tools.qvm_template_postprocess.validate_ip(ip)[source]

Check if given string has a valid IP address syntax

qubesadmin.tools.qvm_unpause module

qvm-unpause - Unpause a domain

qubesadmin.tools.qvm_unpause.main(args=None, app=None)[source]

Main routine of qvm-unpause.

Parameters:

args (list) – Optional arguments to override those delivered from command line.

qubesadmin.tools.qvm_volume module

Qubes volume management

class qubesadmin.tools.qvm_volume.VolumeData(volume)[source]

Bases: object

Wrapper object around qubes.storage.Volume, mainly to track the domains a volume is attached to.

qubesadmin.tools.qvm_volume.clear_volume(args)[source]

Clear the volume data.

qubesadmin.tools.qvm_volume.clone_volume(args)[source]

Clone source volume data into destination volume.

qubesadmin.tools.qvm_volume.config_volume(args)[source]

Change property of selected volume

qubesadmin.tools.qvm_volume.get_parser()[source]

Create argparse.ArgumentParser suitable for qvm-volume.

qubesadmin.tools.qvm_volume.import_volume(args)[source]

Import a file into volume

qubesadmin.tools.qvm_volume.info_volume(args)[source]

Show info about selected volume

qubesadmin.tools.qvm_volume.init_clear_parser(sub_parsers)[source]

Add ‘clear’ action related options

qubesadmin.tools.qvm_volume.init_clone_parser(sub_parsers)[source]

Add ‘clone’ action related options

qubesadmin.tools.qvm_volume.init_config_parser(sub_parsers)[source]

Add ‘info’ action related options

qubesadmin.tools.qvm_volume.init_import_parser(sub_parsers)[source]

Add ‘import’ action related options

qubesadmin.tools.qvm_volume.init_info_parser(sub_parsers)[source]

Add ‘info’ action related options

qubesadmin.tools.qvm_volume.init_list_parser(sub_parsers)[source]

Configures the parser for the qvm-volume list subcommand

qubesadmin.tools.qvm_volume.init_resize_parser(sub_parsers)[source]

Add ‘resize’ action related options

qubesadmin.tools.qvm_volume.init_revert_parser(sub_parsers)[source]

Add ‘revert’ action related options

qubesadmin.tools.qvm_volume.list_volumes(args)[source]

Called by the parser to execute the qvm-volume list subcommand.

qubesadmin.tools.qvm_volume.main(args=None, app=None)[source]

Main routine of qvm-volume.

qubesadmin.tools.qvm_volume.prepare_table(vd_list, full=False)[source]

Converts a list of VolumeData objects to a list of tupples for the qubes.tools.print_table().

If qvm-volume is running in a TTY, it will ommit duplicate data.

Parameters:
  • vd_list (list) – List of VolumeData objects.

  • full (bool) – If set to true duplicate data is printed even when running from TTY.

Returns:

list of tupples

qubesadmin.tools.qvm_volume.resize_volume(args)[source]

Called by the parser to execute the qvm-volume resize subcommand

qubesadmin.tools.qvm_volume.revert_volume(args)[source]

Revert volume to previous state

Module contents

Qubes’ command line tools

class qubesadmin.tools.AliasedSubParsersAction(option_strings, prog, parser_class, dest='==SUPPRESS==', required=False, help=None, metavar=None)[source]

Bases: _SubParsersAction

SubParser with support for action aliases

add_parser(name, **kwargs)[source]
class qubesadmin.tools.PoolsAction(option_strings, dest, nargs=None, const=None, default=None, type=None, choices=None, required=False, help=None, metavar=None)[source]

Bases: QubesAction

Action for argument parser to gather multiple pools

parse_qubes_app(parser, namespace)[source]

This method is called by qubes.tools.QubesArgumentParser after namespace.app is instantiated.

Used to initialize values based on namespace.app.

class qubesadmin.tools.PropertyAction(option_strings: list[str], dest: str, *, metavar: str = 'NAME=VALUE', required: bool = False, help: str = 'set property to a value')[source]

Bases: Action

Action for argument parser that stores a property. Format: –<option_name> property=value

class qubesadmin.tools.QubesAction(option_strings, dest, nargs=None, const=None, default=None, type=None, choices=None, required=False, help=None, metavar=None)[source]

Bases: Action

Custom Action for Qubes

parse_qubes_app(parser, namespace)[source]

This method is called by qubes.tools.QubesArgumentParser after namespace.app is instantiated.

Used to initialize values based on namespace.app.

class qubesadmin.tools.QubesArgumentParser(vmname_nargs=None, show_forceroot=False, version=None, **kwargs)[source]

Bases: ArgumentParser

Parser preconfigured for use in most of the Qubes command-line tools.

Parameters:
  • vmname_nargs (mixed) – The number of VMNAME arguments that should be consumed. Values include: * N (an integer) consumes N arguments (and produces a list) * ‘?’ consumes zero or one arguments * ‘*’ consumes zero or more arguments (and produces a list) * ‘+’ consumes one or more arguments (and produces a list)

  • show_forceroot – don’t hide –force-root parameter, prevent running as root unless it is given

kwargs are passed to argparser.ArgumentParser.

Currenty supported options:

--force-root (optional, ignored, help is suppressed) --offline-mode do not talk to hypervisor (help is suppressed) --verbose and --quiet

Calling program should set the version argument for --version option

The default is extracted from qubesadmin package information. Setting version argument to ‘’ will disable --version option.

error_runtime(message, exit_code=1)[source]

Runtime error, without showing usage.

Parameters:

message (str) – message to show

static get_loglevel_from_verbosity(namespace)[source]

Return loglevel calculated from quiet and verbose arguments

parse_args(*args, **kwargs)[source]
print_error(*args, **kwargs)[source]

Print to sys.stderr

static set_qubes_verbosity(namespace)[source]

Apply a verbosity setting.

This is done by configuring global logging. :param argparse.Namespace args: args as parsed by parser

class qubesadmin.tools.RunningVmNameAction(option_strings, nargs=1, dest='vmnames', help=None, **kwargs)[source]

Bases: VmNameAction

Action for argument parser that gets a running domain from VMNAME

parse_qubes_app(parser, namespace)[source]

Set namespace.domains to values

class qubesadmin.tools.SinglePropertyAction(option_strings, dest, *, metavar: str = 'VALUE', const: object = None, nargs: int | str | None = None, required: bool = False, help: str | None = None)[source]

Bases: Action

Action for argument parser that stores a property. Format: –property_name value or –property_name

class qubesadmin.tools.SubParsersHelpAction(option_strings, dest='==SUPPRESS==', default='==SUPPRESS==', help=None)[source]

Bases: _HelpAction

Print help for all options and all subparsers

class qubesadmin.tools.VMVolumeAction(help='A VM & volume id combination', required=True, **kwargs)[source]

Bases: QubesAction

Action for argument parser that gets the :py:class:qubes.storage.Volume from a VM:VOLUME string.

parse_qubes_app(parser, namespace)[source]

Acquire the :py:class:qubes.storage.Volume object from namespace.app.

class qubesadmin.tools.VmNameAction(option_strings, nargs=1, dest='vmnames', help=None, **kwargs)[source]

Bases: QubesAction

Action for parsing one or multiple domains from provided VMNAMEs

parse_qubes_app(parser, namespace)[source]

Set namespace.domains to values

class qubesadmin.tools.VmNameGroup(container, required, vm_action=<class 'qubesadmin.tools.VmNameAction'>, help=None)[source]

Bases: _MutuallyExclusiveGroup

Adds an a VMNAME, –all & –exclude parameters to a :py:class:argparse.ArgumentParser`.

qubesadmin.tools.get_parser_for_command(command)[source]

Get parser for given qvm-tool.

Parameters:

command (str) – command name

Return type:

argparse.ArgumentParser

Raises:
qubesadmin.tools.print_table(table, stream=None)[source]

Uses the unix column command to print pretty table.

Parameters:

text (str) – list of lists/sets