The Linux kernel exposes hundreds of tunables — socket backlog, swappiness, inotify limits, anti-spoofing flags — as files under /proc/sys, and the sysctl command line is the ordinary way to read and write them. A runtime change made with sysctl -w is lost on reboot; persistence lives in /etc/sysctl.conf and the drop-ins under /etc/sysctl.d, and only a reload bridges the files and the running kernel. Managing that triangle — live values, config files, and the reload that reconciles them — is exactly what configuration management is for.

Reemote is a pure-Python configuration-management library. Instead of a domain-specific language, you write an ordinary Python generator that yields operations against a host, gather typed facts from the target, and await a two-phase run that previews the whole plan before it changes anything. It needs no agent, no interpreter and no template file on the managed machine — only the procps tools every Linux base image already ships, plus a POSIX shell and an SSH connection.

Two modules cover the space, and the split is deliberate. The sysctl module manages the parameter: sysctl.setting treats one kernel key as the resource, gating a runtime half (sysctl -w, compared against the live Sysctl fact) and a persistence half (one keyed line in a config file, compared against SysctlFile) independently; sysctl.conf owns a whole config file as an ordered set of assignments. The sysctl_d module manages the drop-in file in /etc/sysctl.d: sysctl_d.file owns a named file end to end, sysctl_d.setting edits a single assignment inside one while preserving comments and foreign lines, sysctl_d.reload is the explicit activation step, and sysctl_d.prune retires everything outside an allowlist. Use sysctl when you care about a value and where it persists; use sysctl_d when you care about the file — its layout, its ownership, its place in the merge order, and when the kernel should read it.

Try the canonical example first

Install Python 3.13 or newer and Docker or Podman. The connector requires you to name the CLI explicitly; there is no default.

uv venv .venv source .venv/bin/activate uv pip install reemote 

Save this as hello.py. It is the canonical example configured for Podman. The offline pytest suite simulates the connector, and the example was also verified live with Podman. Change both docker_cmd values to "docker" if that is your local CLI.

# hello.py import asyncio from reemote import files, format_log, format_plan, op, run INVENTORY = [ { "host": "demo0", "family": "Alpine", "connection": { "connector": "docker", "identifier": "alpine:3.20", "docker_cmd": "podman", }, }, { "host": "demo1", "family": "Alpine", "connection": { "connector": "docker", "identifier": "alpine:3.20", "docker_cmd": "podman", }, }, ] def deploy(host): yield op( files.install, name="Write a greeting", content="Hello from reemote!\n", dest="/tmp/reemote-hello.txt", mode="0644", ) yield op( files.install, name="Record the host name", content=f"written on {host.name}\n", dest="/tmp/reemote-host.txt", mode="0644", ) async def main(): plans, report, _ = await run(INVENTORY, deploy, dry=True) print("== Dry run ==") print(format_plan(plans)) assert report is None _, report, _ = await run(INVENTORY, deploy) print("\n== Applied ==") assert report is not None print(format_log(report)) asyncio.run(main()) 

Run it with python hello.py. The dry run connects to both containers and reads real state, but sends no mutating deploy commands inside them. The connector may still create, commit, and remove its temporary containers. The apply then advances through the two operations in lockstep: both hosts finish writing the greeting before either starts recording its name.

Verified output from Podman is shown below. The dry-run plan is host-major, while the apply log is step-major: both Write a greeting entries appear before either Record the host name entry.

== Dry run == demo0: Write a greeting [changed: content /tmp/reemote-hello.txt is absent, will install] demo0: Record the host name [changed: content /tmp/reemote-host.txt is absent, will install] demo1: Write a greeting [changed: content /tmp/reemote-hello.txt is absent, will install] demo1: Record the host name [changed: content /tmp/reemote-host.txt is absent, will install] == Applied == demo0: Write a greeting [changed: content /tmp/reemote-hello.txt is absent, will install] $ scp <files install> -> /tmp/reemote-install-2e52d4f8373a608a/content $ sh -c 'mkdir -p /tmp && cp /tmp/reemote-install-2e52d4f8373a608a/content /tmp/reemote-hello.txt && chmod 644 /tmp/reemote-hello.txt && rm -rf /tmp/reemote-install-2e52d4f8373a608a' demo1: Write a greeting [changed: content /tmp/reemote-hello.txt is absent, will install] $ scp <files install> -> /tmp/reemote-install-2e52d4f8373a608a/content $ sh -c 'mkdir -p /tmp && cp /tmp/reemote-install-2e52d4f8373a608a/content /tmp/reemote-hello.txt && chmod 644 /tmp/reemote-hello.txt && rm -rf /tmp/reemote-install-2e52d4f8373a608a' demo0: Record the host name [changed: content /tmp/reemote-host.txt is absent, will install] $ scp <files install> -> /tmp/reemote-install-8c7265455d37e471/content $ sh -c 'mkdir -p /tmp && cp /tmp/reemote-install-8c7265455d37e471/content /tmp/reemote-host.txt && chmod 644 /tmp/reemote-host.txt && rm -rf /tmp/reemote-install-8c7265455d37e471' demo1: Record the host name [changed: content /tmp/reemote-host.txt is absent, will install] $ scp <files install> -> /tmp/reemote-install-8c7265455d37e471/content $ sh -c 'mkdir -p /tmp && cp /tmp/reemote-install-8c7265455d37e471/content /tmp/reemote-host.txt && chmod 644 /tmp/reemote-host.txt && rm -rf /tmp/reemote-install-8c7265455d37e471' 

An image identifier creates a throwaway container for each host. On close, Reemote commits it to a new image and removes the container. That makes every run start fresh; idempotence is demonstrated later against an existing container instead.

Unlike the throwaway-container quickstart, the migration examples below reuse the same Ubuntu hosts, so repeated runs demonstrate convergence against persistent host state.

How sysctl configures the kernel

The sysctl -a dump is the kernel talking; everything else is an approximation of it. Five properties of that arrangement decide how an automation tool has to treat it.

  • Runtime is the truth, files are intent. /proc/sys holds the live values; /etc/sysctl.conf and /etc/sysctl.d/*.conf hold what the host wants at boot. sysctl -w key=value changes the former, a reload (sysctl -p <file> or sysctl --system) bridges file to kernel, and nothing at all reconciles them continuously. A deploy has to read both sides and act on the difference.
  • Persistence is spread across files, and order decides. Modern procps loads /etc/sysctl.d in lexicographic order, then /run/sysctl.d, /usr/local/lib/sysctl.d, /usr/lib/sysctl.d and /lib/sysctl.d — where a file is masked by an earlier file of the same basename — and applies the legacy /etc/sysctl.conf last. Inside one file, the last assignment of a key wins. That is why local policy belongs in a higher-numbered drop-in such as 99-…: it overwrites rather than competes.
  • Values are strings, and some hold several tokens. net.ipv4.ip_local_port_range is 10240 65535, and a few keys print space- or tab-separated lists. The dump can also format a value differently from the file that set it, so comparing wanted against actual has to parse assignments — splitting tokens and coercing integers — rather than diff bytes.
  • Reading is cheap, writing is root. The whole dump and every config file are world-readable on most hosts, while sysctl -w and writes under /etc need elevation. A tool can preview an unlimited number of facts unprivileged and elevate only the mutations.
  • A kernel parameter cannot be unset. Removing a line from a config file changes what the next reload applies; the live value stays until something writes over it or the host reboots. The honest form of "absent" is therefore file-level: drop the assignment and leave the runtime alone.

The Reemote sysctl modules

The sysctl module answers the parameter's two questions — what does the kernel run, and what does the file say — with three facts. Sysctl is the live dump as a key -> value dict with simple values int-coerced, SysctlFile is the raw text of one named config file, and SysctlFiles is every administrator-managed file (/etc/sysctl.conf plus /etc/sysctl.d/*.conf) parsed into path -> {key: value}. Its two operations consume them per half: sysctl.setting gates a runtime sysctl -w against Sysctl and a keyed line edit against SysctlFile, so a value that is live but unpersisted gets only a file write, and a line that is on disk but drifted gets only a reload; sysctl.conf owns a whole file from an ordered tuple of (key, value) pairs, compares it through the same read-back, and reloads the file when an unchanged file still disagrees with the runtime. Flags follow the sysctl CLI: persist=False skips the file, sysctl_set=False skips the direct write, reload=False defers activation, and present=False means "remove the key's line" or "uninstall the file".

The sysctl_d module manages the drop-in itself as the resource. Its facts are directory-shaped: SysctlDropInFiles lists the *.conf files in a directory in merge order, SysctlDropInConfig parses the assignments of one named file, and SysctlEffective is the runtime dump kept as raw strings so it can be compared with file content without coercion games. sysctl_d.file writes a whole drop-in deterministically — a # Managed by reemote header plus one key = value line per setting, sorted by key — and, because it compares parsed assignments, a changed comment or reordered line never provokes a rewrite; sysctl_d.setting edits one key inside a file while preserving comments and foreign lines; sysctl_d.reload applies one file (sysctl -p) or the whole system configuration (sysctl --system) as a stateless request that always reports a change; and sysctl_d.prune removes every drop-in in a directory outside an explicit allowlist. The apply=False flag on the write operations is what makes staging possible: the file lands, and activation happens when you schedule the reload.

The split to keep in mind: sysctl keys a request on a parameter name, sysctl_d keys it on a file path. Neither module installs procps, neither manages the kernel itself, and neither writes to /run or the vendor directories — pair them with the apt module for packages, and use when=is_ubuntu so a mixed inventory skips hosts the family guard excludes rather than failing on them.

Managing kernel parameters in Python

Every shape the article needs is one request long:

  • Set one parameter live and persist one line: op(sysctl.setting, key=..., value=..., sudo=True).
  • Own a whole tuning file: op(sysctl.conf, settings=(...), sysctl_file=..., sudo=True).
  • Own a numbered drop-in with a deterministic render: op(sysctl_d.file, path=..., settings=(...), sudo=True).
  • Edit one assignment inside a drop-in, keeping its comments: op(sysctl_d.setting, file=..., key=..., value=..., sudo=True).
  • Stage a file without touching the running kernel: apply=False (or sysctl_set=False, reload=False in the sysctl namespace).
  • Activate deliberately: op(sysctl_d.reload, sudo=True), or file=... for a scoped reload.
  • Remove a line or retire a file: present=False on the same operations.
  • Read back either side: the Sysctl, SysctlFile, SysctlFiles, SysctlDropInConfig and SysctlEffective facts, gathered fleet-wide with gather_fact.

Two conventions carry through every example below. Arguments passed to op() must stay hashable, so a profile is a tuple of (key, value) pairs rather than a dict — and the order of that tuple is the order written to the file. And the escalation flag belongs to the request (sudo=True) while the run-as user stays a property of the inventory: the spool transfer to /tmp always runs as the login user, and only the install step and the sysctl invocations are elevated.

Inventory for the sysctl hosts

The examples use the repository's real Ubuntu SSH host. Save an equivalent inventory as inventory.json:

[ { "host": "ubuntu", "family": "Ubuntu", "connection": { "connector": "ssh", "address": "192.168.0.251", "port": 22, "username": "supervisor", "key_path": "~/.ssh/id_ed25519" }, "tags": ["ubuntu_host", "apt_package_manager"] } ] 

Replace the address, user and key path with your own. Every managed request writes under /etc, so the login needs passwordless sudo; verify the host key and populate ~/.ssh/known_hosts rather than disabling host-key checking, as the SSH connector reference describes. Check what the host already has before you start, because the existing drop-ins are not yours to overwrite:

ssh supervisor@192.168.0.251 'sysctl vm.swappiness; ls -l /etc/sysctl.conf /etc/sysctl.d' 

Runnable examples for the inventory Ubuntu host

Clone the repository and edit its inventory.json, or replace that file with the inventory above:

git clone https://github.com/kimjarvis/reemote.git cd reemote 

The scripts under examples/articles/sysctl/ load that inventory, select only entries whose family is Ubuntu, and use sudo for the root-owned state. Mutating scripts preview by default and require --apply; the inspection script is read-only. They share one helper, sysctl_article_common.py, which holds the managed paths and the preview/apply driver.

Example Article concept
sysctl_hello.py The canonical two operations against persistent SSH hosts
sysctl_one_parameter.py One parameter live and persisted, with sysctl.setting
sysctl_network_profile.py A whole ordered tuning file with sysctl.conf
sysctl_security_profile.py A deterministic hardening drop-in owned by sysctl_d.file
sysctl_dropin_edit.py Two keyed edits that share one drop-in and still converge
sysctl_staged_apply.py Stage a file with apply=False, activate later with sysctl_d.reload
sysctl_inspect.py Read back runtime, files and config/runtime drift
sysctl_cleanup.py Remove every setting the article manages

Every parameter this article sets is safe on a host you are logged into: none changes routing, disables a protocol, or touches the address carrying the session. Run a read-only preview from the repository root:

uv run python examples/articles/sysctl/sysctl_one_parameter.py 

Run the canonical pair on a real host

The first script is the quickstart's two files.install operations, kept as the article's baseline against a persistent host: same requests, same preview-then-apply shape, SSH instead of a container, and a family guard so a RedHat host in the same inventory is skipped rather than failing.

# sysctl_hello.py # Copyright (c) 2026 Kim Jarvis. # SPDX-License-Identifier: EPL-2.0 """Run the canonical two operations against persistent Ubuntu SSH hosts.""" import asyncio import sys from pathlib import Path from reemote import files, op sys.path.insert(0, str(Path(__file__).resolve().parent)) from sysctl_article_common import execute, is_ubuntu, load_inventory, parser def deploy(host): yield op( files.install, name="Write a greeting", content="Hello from reemote!\n", dest="/tmp/reemote-hello.txt", mode="0644", when=is_ubuntu, ) yield op( files.install, name="Record the host name", content=f"written on {host.name}\n", dest="/tmp/reemote-host.txt", mode="0644", when=is_ubuntu, ) async def main(argv=None): args = parser(__doc__).parse_args(argv) await execute(load_inventory(args.inventory), deploy, apply_changes=args.apply) if __name__ == "__main__": asyncio.run(main()) 

The preview reads the host and reports what it would write, without sending a mutating command:

== Preview == ubuntu: Write a greeting [changed: content /tmp/reemote-hello.txt is absent, will install] ubuntu: Record the host name [changed: content /tmp/reemote-host.txt is absent, will install] Preview only; pass --apply to change the hosts. 

Because the host persists between runs, a second pass has something to be up to date about: both requests report no change and send no commands — the convergence behaviour every later example relies on.

Set one parameter live and in the config file

sysctl.setting is the module's single-parameter operation, and one request carries both halves of the job: it applies sysctl -w vm.swappiness=10 only when the live value differs, and it edits the keyed line in the persistence file only when the file's text lacks it. The write is a spool transfer plus an elevated install, followed by a scoped sysctl -p, so the file and the kernel are reconciled through the same command the administrator would type.

# sysctl_one_parameter.py # Copyright (c) 2026 Kim Jarvis. # SPDX-License-Identifier: EPL-2.0 """Set one kernel parameter end to end with ``sysctl.setting``. The example manages ``vm.swappiness`` in the legacy ``/etc/sysctl.conf``. ``sysctl.setting`` is the module's single-parameter operation, and it runs two independent halves gated by two different facts: the runtime half compares the live value from the ``Sysctl`` fact and applies ``sysctl -w`` only on a real difference; the persistence half reads the file's raw text with ``SysctlFile`` and rewrites it only when the keyed line is missing or wrong. The write spools the new text to ``/tmp`` as the login user, then one elevated ``sh -c`` installs it ``0644`` and a scoped ``sysctl -p`` follows. Because the file edit is keyed rather than appended, re-running the deploy converges: the line is replaced in place, duplicate assignments collapse, and a third pass sends no commands at all. Both halves write or apply root-owned state, so the request elevates with ``sudo=True``. Run it with:: uv run python examples/articles/sysctl/sysctl_one_parameter.py uv run python examples/articles/sysctl/sysctl_one_parameter.py --apply """ import asyncio import sys from pathlib import Path from reemote import op, sysctl sys.path.insert(0, str(Path(__file__).resolve().parent)) from sysctl_article_common import ( SWAPPINESS_KEY, execute, is_ubuntu, load_inventory, parser, ) SWAPPINESS_VALUE = 10 def deploy(host): yield op( sysctl.setting, name="Set vm.swappiness to 10", key=SWAPPINESS_KEY, value=SWAPPINESS_VALUE, sudo=True, when=is_ubuntu, ) async def main(argv=None): args = parser(__doc__).parse_args(argv) await execute(load_inventory(args.inventory), deploy, apply_changes=args.apply) if __name__ == "__main__": asyncio.run(main()) 

The preview already reads both halves and names each one's verdict in a single reason, joined by semicolons:

== Preview == ubuntu: Set vm.swappiness to 10 [changed: vm.swappiness not set to 10 at runtime, will apply; /etc/sysctl.conf missing or differs for vm.swappiness, will write] Preview only; pass --apply to change the hosts. 

The apply shows all four commands the request expanded into — the direct runtime write, the spool transfer, the elevated install, and the scoped reload that confirms the file through the same path sysctl --system would take at boot:

== Applied == ubuntu: Set vm.swappiness to 10 [changed: vm.swappiness not set to 10 at runtime, will apply; /etc/sysctl.conf missing or differs for vm.swappiness, will write] $ sudo sysctl -w vm.swappiness=10 $ scp <sysctl conf> -> /tmp/reemote-sysctl-4bac2aa6ea0d0640/sysctl.conf $ sudo sh -c 'mkdir -p /etc && cp /tmp/reemote-sysctl-4bac2aa6ea0d0640/sysctl.conf /etc/sysctl.conf && chmod 0644 /etc/sysctl.conf && rm -rf /tmp/reemote-sysctl-4bac2aa6ea0d0640' $ sudo sysctl -p /etc/sysctl.conf 

Running the same script again sends nothing, and each half reports its own agreement:

== Preview == ubuntu: Set vm.swappiness to 10 [no change: vm.swappiness already set to 10 at runtime; /etc/sysctl.conf already up to date for vm.swappiness] == Applied == ubuntu: Set vm.swappiness to 10 [no change: vm.swappiness already set to 10 at runtime; /etc/sysctl.conf already up to date for vm.swappiness] 

The two halves are why the operation exists at all. Hand-editing vm.swappiness on the host leaves the file current and the runtime drifted, and the next pass repairs only the runtime; adding the line to the file by hand leaves the runtime alone and the next pass issues only a reload. That gating is invisible in the second-pass output above, where both sides already agree.

Write an ordered network tuning profile

A profile is a list of decisions, not a bag of keys: which backlog to accept, which port range to allocate from, which timeout to shorten. sysctl.conf takes the whole ordered tuple and owns one file outright — the tuple's order is the file's order, and a multi-word value such as the local port range is written verbatim. The 99- prefix sorts after every vendor drop-in, so the profile wins for the keys it declares and never fights the distribution's own files.

# sysctl_network_profile.py # Copyright (c) 2026 Kim Jarvis. # SPDX-License-Identifier: EPL-2.0 """Write an ordered network tuning profile with ``sysctl.conf``. The example owns ``/etc/sysctl.d/99-reemote-network.conf`` as a whole file from one tuple of ``(key, value)`` pairs. ``sysctl.conf`` is the file-oriented counterpart of ``setting``: it renders the entire content from the settings and compares that text against ``SysctlFile``, so a changed write is one spool transfer plus one elevated install, followed by a scoped ``sysctl -p``. An unchanged file is reloaded only when a managed runtime value still differs, which is how a reboot or a hand-edit is pulled back into line without ever touching a key the file does not own. The settings are a tuple, not a dict, because ``op()`` arguments must be hashable, and their order is the order written to the file. A multi-word value such as the local port range is written verbatim. The default ``reload`` applies the profile on a changed write; every value here is safe on a host you are logged into, and none of it changes routing or the address carrying the session. Run it with:: uv run python examples/articles/sysctl/sysctl_network_profile.py uv run python examples/articles/sysctl/sysctl_network_profile.py --apply """ import asyncio import sys from pathlib import Path from reemote import op, sysctl sys.path.insert(0, str(Path(__file__).resolve().parent)) from sysctl_article_common import ( NETWORK_DROPIN, execute, is_ubuntu, load_inventory, parser, ) NETWORK_PROFILE = ( ("net.core.somaxconn", 65535), ("net.core.netdev_max_backlog", 65535), ("net.ipv4.tcp_fastopen", 3), ("net.ipv4.ip_local_port_range", "10240 65535"), ("net.ipv4.tcp_fin_timeout", 15), ("net.ipv4.tcp_window_scaling", 1), ("net.core.rmem_max", 16777216), ("net.core.wmem_max", 16777216), ) def deploy(host): yield op( sysctl.conf, name="Apply the network tuning profile", settings=NETWORK_PROFILE, sysctl_file=NETWORK_DROPIN, sudo=True, when=is_ubuntu, ) async def main(argv=None): args = parser(__doc__).parse_args(argv) await execute(load_inventory(args.inventory), deploy, apply_changes=args.apply) if __name__ == "__main__": asyncio.run(main()) 

One request, three commands: the spool transfer, the elevated install, and the scoped reload of exactly this file — no --system, so a tuned profile never re-applies configuration it does not own:

== Applied == ubuntu: Apply the network tuning profile [changed: sysctl config /etc/sysctl.d/99-reemote-network.conf missing or differs from the settings] $ scp <sysctl conf> -> /tmp/reemote-sysctl-b5ef0e99861c8662/sysctl.conf $ sudo sh -c 'mkdir -p /etc/sysctl.d && cp /tmp/reemote-sysctl-b5ef0e99861c8662/sysctl.conf /etc/sysctl.d/99-reemote-network.conf && chmod 0644 /etc/sysctl.d/99-reemote-network.conf && rm -rf /tmp/reemote-sysctl-b5ef0e99861c8662' $ sudo sysctl -p /etc/sysctl.d/99-reemote-network.conf 

The file on disk holds the tuple in the order it was declared:

net.core.somaxconn = 65535 net.core.netdev_max_backlog = 65535 net.ipv4.tcp_fastopen = 3 net.ipv4.ip_local_port_range = 10240 65535 net.ipv4.tcp_fin_timeout = 15 net.ipv4.tcp_window_scaling = 1 net.core.rmem_max = 16777216 net.core.wmem_max = 16777216 

A second pass reports sysctl config already up to date (/etc/sysctl.d/99-reemote-network.conf) and sends nothing — including no reload, because the runtime values the first pass applied still hold. Drift is what summons the sysctl -p back: reboot the host, or overwrite a key by hand, and the unchanged file reloads itself on the next run without rewriting a byte.

Own a hardening drop-in with sysctl_d.file

Security baselines are the other half of sysctl work: martian logging, source-route rejection, reverse-path filtering, SYN cookies. The values matter, but so does the file — reviewers want to read one deterministic drop-in and see the policy, not infer it from a pile of keyed edits. That is sysctl_d's shape, and sysctl_d.file is its workhorse: the settings tuple is the file, rendered with a management header and one sorted key = value line per setting.

# sysctl_security_profile.py # Copyright (c) 2026 Kim Jarvis. # SPDX-License-Identifier: EPL-2.0 """Harden the kernel with one whole-file drop-in from ``sysctl_d.file``. The example owns ``/etc/sysctl.d/99-reemote-security.conf`` through the `sysctl_d` namespace's file-oriented operation: the settings tuple is the file. ``sysctl_d.file`` parses the existing drop-in and compares *assignments*, so a changed comment or a reordered line never provokes a rewrite, and the rendered content is deterministic — a ``# Managed by reemote`` header followed by the settings sorted by key. A changed write spools the text to ``/tmp``, installs it ``0644`` in one elevated step, and follows it with a scoped ``sysctl -p`` of exactly this file. Anti-spoofing and ICMP-hardening parameters are safe to set on a host you are logged into: none of them changes routing, disables a protocol, or touches the address carrying the session. Writing under ``/etc`` and reloading need root, so the request carries ``sudo=True``. Run it with:: uv run python examples/articles/sysctl/sysctl_security_profile.py uv run python examples/articles/sysctl/sysctl_security_profile.py --apply """ import asyncio import sys from pathlib import Path from reemote import Source:https://dev.to/kimbofab/how-to-use-python-to-manage-sysctl-parameters-1d8g

Related posts