Built-in Tools

class rmote.tools.Apt[source]

Bases: Tool

Manage Debian/Ubuntu packages via apt-get. Requires root on the remote host.

classmethod converge(*packages)[source]

Ensure all packages are present, reading dpkg status once for efficiency.

Parameters:

*packages (Text | Package) – Package names, name=version strings, or Package instances.

Return type:

list[Result]

Returns:

List of Result objects, one per package, in the same order as the input.

classmethod package(package, state=State.PRESENT)[source]

Install, remove, or upgrade a single package.

Parameters:
  • package (Text | Package) – Package name, name=version string, or a Package instance.

  • state (State | int) – Desired state - State.PRESENT (install if absent), State.ABSENT (purge if installed), or State.LATEST (install or upgrade to candidate version).

Return type:

Result

Returns:

Result with the package name, installed version, and whether the system was changed.

Raises:

RuntimeError – If the underlying apt-get invocation fails.

static update(ttl=-1)[source]

Run apt-get update, with optional TTL-based skipping.

Parameters:

ttl (int | float) – Minimum age in seconds of the last successful update before re-running. -1 (default) always runs the update.

Return type:

bool

Returns:

True if apt-get update was executed, False if the cache is fresher than ttl seconds.

Raises:

RuntimeError – If apt-get update exits with a non-zero status.

class rmote.tools.AptRepository[source]

Bases: Tool

Manage APT repository sources and GPG keys on Debian/Ubuntu.

Repository sources are written as DEB822 .sources files under /etc/apt/sources.list.d/. GPG keyrings are stored in /etc/apt/keyrings/. All operations are idempotent and require root.

static absent(name)[source]

Remove the DEB822 .sources file for name, if it exists.

Parameters:

name (Text) – Repository label (the {name}.sources filename stem).

Return type:

Result

Returns:

Result indicating whether the file was removed.

static key(name, data)[source]

Install a GPG signing key to /etc/apt/keyrings/{name}.

The operation is idempotent — if the file already contains identical bytes it is left untouched.

Parameters:
  • name (Text) – Filename to write the key under (e.g. "docker.gpg").

  • data (bytes) – Raw key bytes (binary DER or ASCII-armoured GPG key).

Return type:

Result

Returns:

Result indicating whether the key was written.

static present(name, *, types=('deb',), uris, suites, components, signed_by='')[source]

Ensure a DEB822 .sources file is configured for name.

Writes /etc/apt/sources.list.d/{name}.sources. The operation is idempotent — if the file already contains the expected content it is left untouched.

Parameters:
  • name (Text) – Repository label used as the filename stem.

  • types (Iterable[Text]) – Package types — typically ("deb",) for binary packages or ("deb-src",) for source packages.

  • uris (Iterable[Text]) – Repository base URIs (e.g. ("https://download.docker.com/linux/ubuntu",)).

  • suites (Iterable[Text]) – Distribution suites (e.g. ("noble",)).

  • components (Iterable[Text]) – Repository components (e.g. ("stable",)).

  • signed_by (Text) – Absolute path to the GPG keyring that signs this repository.

Return type:

Result

Returns:

Result indicating whether the file was created or updated.

class rmote.tools.Exec[source]

Bases: Tool

Run commands and shell expressions on the remote host.

static command(*args, check=True, env=None, cwd=None, stdin=None)[source]

Run a command with explicit argument list.

Parameters:
  • *args (Text) – Command and its arguments (e.g. "ls", "-la").

  • check (bool) – Raise subprocess.CalledProcessError on non-zero exit.

  • env (WSGIEnvironment[Text, Text] | None) – Override environment variables for the subprocess.

  • cwd (None | Text | Path) – Working directory; defaults to the remote process’s cwd.

  • stdin (None | Text | bytes) – Data written to stdin before the command reads it.

Return type:

CompletedProcess[Any]

Returns:

subprocess.CompletedProcess with returncode, stdout, and stderr.

static shell(expression, check=True, env=None, cwd=None, stdin=None)[source]

Run expression through the remote shell (/bin/sh -c).

Parameters:
  • expression (Text) – Shell expression, including pipes, redirects, etc.

  • check (bool) – Raise subprocess.CalledProcessError on non-zero exit.

  • env (WSGIEnvironment[Text, Text] | None) – Override environment variables for the subprocess.

  • cwd (None | Text | Path) – Working directory; defaults to the remote process’s cwd.

  • stdin (None | Text | bytes) – Data written to stdin before the command reads it.

Return type:

CompletedProcess[Any]

Returns:

subprocess.CompletedProcess with returncode, stdout, and stderr.

class rmote.tools.FileSystem[source]

Bases: Tool

Remote filesystem operations - read, glob, and idempotent line-in-file.

static glob(path, pattern)[source]

Return all paths under path that match pattern.

Parameters:
  • path (Text | Path) – Directory to search in.

  • pattern (Text) – Glob pattern relative to path (e.g. "*.conf").

Return type:

list[Text]

Returns:

Sorted list of matching paths as strings.

static line_in_file(path, *, line, regexp=None, strip=True, create=False, match=LineInFileMatch.FIRST)[source]

Ensure line is present in the file at path, idempotently.

If regexp is given, replace the first (or all, with match=ALL) lines that match the pattern with line. If no line matches, or if regexp is not given and line is not found, line is appended.

Parameters:
  • path (Text) – Path to the file to modify.

  • line (Text) – The desired line content to insert or substitute.

  • regexp (Text | None) – A regex pattern to match against existing lines. When a match is found, the matching line(s) are replaced with line.

  • strip (bool) – Compare lines after stripping whitespace when looking for an exact match (no regexp). Default True.

  • create (bool) – Create the file if it does not exist. Default False.

  • match (LineInFileMatch) – Whether to replace the FIRST matching line or ALL matching lines.

Return type:

Text

Returns:

A unified diff string describing the change, or an empty string if the file was already in the desired state.

Raises:

FileNotFoundError – If path does not exist and create is False.

static read_bytes(path)[source]

Read path and return its raw contents.

Parameters:

path (Text) – Absolute or relative path on the remote filesystem.

Return type:

bytes

Returns:

File contents as bytes.

static read_str(path)[source]

Read path and return its contents decoded as UTF-8.

Parameters:

path (Text) – Absolute or relative path on the remote filesystem.

Return type:

Text

Returns:

File contents as str.

class rmote.tools.Logger[source]

Bases: Tool

Control logging on the remote side and forward records to the local process.

Log records emitted on the remote side are forwarded over the protocol channel and appear locally under the rmote.remote.<name> logger hierarchy.

classmethod log(level, message, *args)[source]

Emit a log record on the remote side.

The record is forwarded to the local logging system via the protocol’s LOG packet and appears under the rmote.remote.<name> logger.

Parameters:
  • level (Text) – Log level name (e.g. "INFO", "DEBUG").

  • message (Text) – Log message format string (%-style).

  • *args (Any) – Arguments merged into message.

Raises:

ValueError – If level is not a recognised level name.

Return type:

None

classmethod set_log_level(level)[source]

Set the root logger level on the remote side.

Parameters:

level (Text) – One of "NOTSET", "DEBUG", "INFO", "WARNING", "ERROR", or "CRITICAL" (case-insensitive).

Raises:

ValueError – If level is not a recognised level name.

Return type:

None

class rmote.tools.Pacman[source]

Bases: Tool

Manage Arch Linux packages via pacman. Requires root on the remote host.

classmethod converge(*packages)[source]

Ensure all packages are present.

Parameters:

*packages (Text | Package) – Package names or Package instances.

Return type:

list[Result]

Returns:

List of Result objects, one per package, in the same order as the input.

static package(package, state=State.PRESENT)[source]

Install, remove, or upgrade a single package.

Parameters:
  • package (Text | Package) – Package name or a Package instance. Version pinning (name=version) is parsed but ignored by pacman.

  • state (State | int) – Desired state - State.PRESENT (install if absent), State.ABSENT (remove if installed), or State.LATEST (install or upgrade).

Return type:

Result

Returns:

Result with the package name, installed version, and whether the system was changed.

Raises:

RuntimeError – If the underlying pacman invocation fails.

static update(ttl=-1)[source]

Synchronise the package database (pacman -Sy), with optional TTL-based skipping.

Parameters:

ttl (int | float) – Minimum age in seconds of the last sync before re-running. -1 (default) always synchronises.

Return type:

bool

Returns:

True if pacman -Sy was executed, False if the database is fresher than ttl seconds.

Raises:

RuntimeError – If pacman -Sy exits with a non-zero status.

class rmote.tools.PacmanRepository[source]

Bases: Tool

Manage Arch Linux repository sections and GPG keys.

Repository sections are read from and written to /etc/pacman.conf. GPG key files are stored in /etc/pacman.d/. All operations are idempotent and require root.

static absent(name)[source]

Remove the repository section name from /etc/pacman.conf.

Parameters:

name (Text) – Repository section name to remove.

Return type:

Result

Returns:

Result indicating whether pacman.conf was modified.

static key(name, data)[source]

Write a GPG key to /etc/pacman.d/{name}.

Idempotent — the file is left untouched if it already contains identical bytes.

Parameters:
  • name (Text) – Filename to write the key under (e.g. "blackarch.gpg").

  • data (bytes) – Raw key bytes.

Return type:

Result

Returns:

Result indicating whether the key was written.

static present(name, *, servers, sig_level='Optional TrustAll')[source]

Ensure a repository section is present in /etc/pacman.conf.

If the section already exists with the same content it is left unchanged. If it exists with different content it is updated in-place. Otherwise it is appended at the end of the file.

Parameters:
  • name (Text) – Repository section name (e.g. "blackarch").

  • servers (list[Text]) – One or more server URLs for the repository.

  • sig_level (Text) – pacman SigLevel value. Defaults to "Optional TrustAll".

Return type:

Result

Returns:

Result indicating whether pacman.conf was modified.

class rmote.tools.Quit[source]

Bases: Tool

Signal the remote process to exit cleanly.

async static exit(code=0)[source]

Exit the remote process with code.

Parameters:

code (int) – Exit status code passed to sys.exit(). Defaults to 0.

Return type:

None

class rmote.tools.Service[source]

Bases: Tool

Manage systemd services on the remote host. Requires systemd and root.

static converge(name, *, started=True, enabled=True)[source]

Idempotently ensure a service is in the desired state.

Parameters:
  • name (Text) – Service unit name (e.g. “nginx”, “nginx.service”)

  • started (bool) – Whether the service should be running

  • enabled (bool) – Whether the service should start on boot

Return type:

Result

static daemon_reload()[source]

Reload systemd manager configuration.

Return type:

None

static disable(name)[source]

Disable a service at boot. No-op if already disabled.

Return type:

Result

static enable(name)[source]

Enable a service at boot. No-op if already enabled.

Return type:

Result

static reload(name)[source]

Reload a service unconditionally (SIGHUP).

Return type:

Result

static restart(name)[source]

Restart a service unconditionally.

Return type:

Result

static start(name)[source]

Start a service. No-op if already running.

Return type:

Result

static status(name)[source]

Return current active/enabled status of a service.

Return type:

Result

static stop(name)[source]

Stop a service. No-op if already stopped.

Return type:

Result

class rmote.tools.Template[source]

Bases: Tool

Built-in tool that renders Mako-like templates on the remote side.

All three methods execute on the remote process. See Templating for a full description of the template syntax.

static render(template, **kwargs)[source]

Compile template and render it with kwargs as the variable namespace.

Parameters:
  • template (Text) – Template source string.

  • **kwargs (object) – Variables available inside the template.

Return type:

Text

Returns:

The rendered string.

static render_compiled(template, **kwargs)[source]

Render a pre-compiled Template instance.

Use this method when the template was compiled locally and passed as an argument to avoid re-compiling it on the remote side.

Parameters:
  • template (Template) – A Template instance (picklable).

  • **kwargs (object) – Variables available inside the template.

Return type:

Text

Returns:

The rendered string.

static render_file(path, **kwargs)[source]

Read the template file at path on the remote host and render it.

Parameters:
  • path (Text) – Absolute path to the template file on the remote filesystem.

  • **kwargs (object) – Variables available inside the template.

Return type:

Text

Returns:

The rendered string.

class rmote.tools.User[source]

Bases: Tool

Manage users, groups, SSH keys, and sudoers on the remote host. Requires root.

static absent(name, *, remove_home=False)[source]

Ensure a user does not exist. Returns True if user was removed.

Parameters:
  • name (Text) – Username

  • remove_home (bool) – Also remove the user’s home directory

Return type:

bool

static authorized_key(name, key, *, exclusive=False)[source]

Ensure an SSH public key is present in ~/.ssh/authorized_keys.

Parameters:
  • name (Text) – Username

  • key (Text) – SSH public key string

  • exclusive (bool) – If True, replace the entire authorized_keys with only this key

Return type:

bool

Returns:

True if file was changed.

static group_absent(name)[source]

Ensure a group does not exist. Returns True if group was removed.

Return type:

bool

static group_present(name, *, gid=None, system=False)[source]

Ensure a group exists. Idempotent.

Return type:

GroupResult

static present(name, *, uid=None, gid=None, comment='', home=None, shell='/bin/bash', groups=None, append_groups=True, system=False, create_home=True)[source]

Ensure a user exists with the given attributes. Idempotent.

Parameters:
  • name (Text) – Username

  • uid (int | None) – Numeric UID (optional)

  • gid (int | None) – Primary GID or group name (optional)

  • comment (Text) – GECOS field

  • home (Text | None) – Home directory path (default: /home/<name>)

  • shell (Text) – Login shell

  • groups (list[Text] | None) – Supplementary groups

  • append_groups (bool) – If True, add to groups without removing existing ones

  • system (bool) – Create as system user (no home, lower UID range)

  • create_home (bool) – Create home directory if it does not exist

Return type:

Result

static sudoer(name, *, nopasswd=True, absent=False)[source]

Manage a sudoers drop-in for a user in /etc/sudoers.d/.

Parameters:
  • name (Text) – Username

  • nopasswd (bool) – Grant passwordless sudo

  • absent (bool) – Remove the sudoers entry instead

Return type:

bool

Returns:

True if file was changed.