Fail2ban is an open-source intrusion prevention framework written in Python: it watches server logs for repeated authentication failures and other suspicious patterns, then temporarily bans the source addresses through the local firewall. Reemote is a pure-Python configuration-management library that lets you install Fail2ban, manage its configuration, inspect its jails and apply targeted ban changes using ordinary Python generators over SSH. Fail2ban needs Python on the server; Reemote itself needs only a POSIX shell and a connection to execute its remote commands.
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. The existing-container demonstration mentioned above belongs to the Alpine walkthrough; this article continues over SSH.
Inventory for real Ubuntu hosts
The remaining examples target booted Ubuntu servers with systemd, SSH key access and passwordless sudo for the deployment account. Use a maintained Ubuntu release with Fail2ban 1.x, the systemd journal and a netfilter-capable kernel. They are not container simulations and do not need Docker. This mirrors the repository's Ubuntu lab entry, adjusted to the recommended connection form that keeps SSH host-key verification enabled:
[ { "host": "ubuntu", "family": "Ubuntu", "connection": { "connector": "ssh", "address": "192.168.0.251", "username": "supervisor", "key_path": "~/.ssh/id_ed25519" }, "group": "ubuntu", "tags": ["ubuntu_host", "apt_package_manager"] } ] That private address is a lab machine, not a public test service. Replace it, the login and the key path with your own real server's values. Add more Ubuntu entries with distinct host names to manage several machines. Verify each SSH host fingerprint and populate ~/.ssh/known_hosts; do not disable host-key checking to make the first connection pass. The SSH connector and host inventory documentation explain connection and privilege settings.
Keep a working console or another out-of-band recovery route. Know the source address seen by the server, including any NAT, VPN and IPv6 path, before supplying the management allowlist. Do not whitelist all private networks merely because a stock jail template does so. Ubuntu's package scripts may start Fail2ban during installation, before your custom allowlist exists. Use a tested key login and keep console access throughout that first installation.
Runnable examples and their order
Clone the Reemote repository and configure its root inventory.json with the inventory above:
git clone https://github.com/kimjarvis/reemote.git cd reemote uv sync --group dev The scripts are in examples/articles/crowdsec/. Despite the directory name, these fail2ban_ scripts manage Fail2ban, not CrowdSec. Their shared helper reads the repository-root inventory, validates it, selects only the Ubuntu family and rejects container connections. Group names do not select the operating system. Run the scripts from this checkout so they use the API described here.
| Index | Real-host script | Purpose |
|---|---|---|
| 1 | fail2ban_hello.py | The canonical two-file deploy, adapted to persistent SSH hosts |
| 2 | fail2ban_install.py | Install Fail2ban, journal bindings and nftables |
| 3 | fail2ban_configure.py | Render defaults and jails, install filters, validate and activate |
| 4 | fail2ban_check_filters.py | Exercise both custom filters against isolated log fixtures |
| 5 | fail2ban_inspect.py | Read active jails, failure counters and banned addresses |
| 6 | fail2ban_bans.py | Explicitly ban or unban one documentation-only test address |
fail2ban_article_common.py supplies the inventory, preview/apply runner and checked read-only actions. Every numbered example has offline pytest coverage. Mutating scripts preview by default; --apply previews and then applies. A preview opens SSH connections and reads facts, but does not install packages, write files or reload services. Example 5 is read-only. The Python excerpts below are taken from these scripts; run the indexed files to include their imports and entrypoints.
Example 1 is a low-risk connection and convergence check before managing the firewall:
uv run python examples/articles/crowdsec/fail2ban_hello.py uv run python examples/articles/crowdsec/fail2ban_hello.py --apply uv run python examples/articles/crowdsec/fail2ban_hello.py --apply The second apply should leave both files unchanged. Unlike the canonical image inventory, these hosts survive between invocations.
One workflow, several ordinary Python parts
This workflow combines package installation, default variables, per-service jails, custom filters, handlers and reporting. All of it is an ordinary Python renderer plus ordinary Python deploys — no new module to write and no template files to ship. Each concern has its own explicit Reemote expression:
| Concern | Reemote implementation |
|---|---|
| Privileged package installation | apt.packages with sudo=True |
| Shared defaults and jail settings | Explicit Python arguments and an INI renderer |
| Looping over managed files | A Python loop yielding files.install requests |
| Restart/reload on change | changed_hosts from the apply report, followed by a reload deploy |
| Running a check command and reading its result | A Shell action and an explicit exit-status check |
| Status reporting | Typed jail facts returned as Python data |
| Preview without mutation | run(..., dry=True) |
The Fail2ban module handles runtime inspection and targeted ban or reload requests. Installation, root-owned configuration and boot-time service state remain the jobs of the APT, files and systemd modules. This separation matters: a ban operation cannot configure a missing jail or install a missing daemon.
Understand the policy before installing it
The daemon, fail2ban-server, watches events; fail2ban-client configures and queries it. Four pieces turn an event into a ban:
- A filter under
/etc/fail2ban/filter.d/identifies failures and extracts an address using regular expressions. - A backend supplies events:
systemdreads the journal throughpython3-systemd; file backends includepyinotifyandpolling. - A jail binds a filter, event source, action and thresholds.
maxretrymatching failures withinfindtimetrigger a ban lastingbantime. - An action under
/etc/fail2ban/action.d/applies and removes the ban, commonly using nftables, iptables, UFW or firewalld. Other actions can send notifications or abuse reports.
A configuration walkthrough explains the journal-versus-file distinction and configuration precedence. Fail2ban reads jail.conf, jail.d/*.conf, jail.local, then jail.d/*.local, with later settings overriding earlier ones. We own only jail.d/90-reemote.local and two uniquely named custom filters; package-owned defaults and unrelated local files remain untouched. Review any later-sorting .local overrides before assuming our values win.
Example 2 installs the needed tools without upgrading the whole server:
# fail2ban_install.py: deploy def deploy(host, refresh=False): if refresh: yield op(apt.update, name="Refresh APT indexes", sudo=True, when=is_ubuntu) yield op( apt.packages, name="Install Fail2ban dependencies", packages=("fail2ban", "python3-systemd", "nftables"), sudo=True, when=is_ubuntu, ) uv run python examples/articles/crowdsec/fail2ban_install.py --refresh uv run python examples/articles/crowdsec/fail2ban_install.py --refresh --apply Use the distribution's updates repository, particularly on early Ubuntu 24.04 installations whose original Fail2ban package had Python compatibility issues. Package presence is the desired state here, not a request to upgrade an already installed version. Handle package upgrades through your normal maintenance policy. --refresh is deliberately separate: refreshing APT indexes is stateless and reports a change every time. Omit it when checking package convergence.
Installing nftables does not replace the machine's base firewall, enable nftables.service or flush any rules. These examples explicitly choose Fail2ban's nftables-multiport action. Confirm that choice fits the existing firewall, including any UFW/firewalld integration, before applying.
Configure SSH and the management allowlist
Example 3 replaces the usual in-place configuration editor with a deterministic RawConfigParser renderer. Raw mode preserves Fail2ban's own %(action_)s interpolation. The CLI requires at least one --admin-network, validates addresses/CIDRs, and accepts --ssh-port for a nonstandard SSH listener. It does not change sshd's listening port.
Its baseline includes these settings (the displayed administration address is documentation-only):
[DEFAULT] ignoreip = 127.0.0.1/8 ::1 198.51.100.10/32 bantime = 1h findtime = 10m maxretry = 5 usedns = no banaction = nftables-multiport action = %(action_)s bantime.increment = false bantime.maxtime = 1w [sshd] enabled = true filter = sshd backend = systemd port = 22 maxretry = 3 bantime = 2h The SSH jail reads journald, not an assumed /var/log/auth.log. The installed sshd filter provides its journal match. The port controls which traffic the firewall action blocks; it is not the log source. Three matched failure records need not equal three password prompts: one connection can produce several matching records.
The deploy installs the two filters before the jail policy:
# fail2ban_configure.py: deploy def deploy(host, admin_networks=(), ssh_port=22, nginx=False, app_log=None, incremental=False): content = render_jails(admin_networks, ssh_port, nginx, app_log, incremental) for name, dest, text in ( (CONFIG_NAMES[0], APP_FILTER_PATH, APP_FILTER), (CONFIG_NAMES[1], NGINX_FILTER_PATH, NGINX_FILTER), (CONFIG_NAMES[2], JAIL_PATH, content), ): yield op( files.install, name=name, content=text, dest=dest, user="root", group="root", mode="0644", sudo=True, when=is_ubuntu, ) files.install compares existing content and metadata, transfers changed content to a spool, and installs it with elevation. It creates missing parent directories. A second apply with the same arguments should leave the files alone. Direct library callers must supply their management networks too; the empty tuple in the deploy signature is not a safe production allowlist.
Replace 198.51.100.10/32 with your actual trusted source before running:
uv run python examples/articles/crowdsec/fail2ban_configure.py --admin-network 198.51.100.10/32 uv run python examples/articles/crowdsec/fail2ban_configure.py --admin-network 198.51.100.10/32 --apply Repeat --admin-network for additional trusted IPv4 or IPv6 sources. Keep the set narrow. An allowlist prevents automatic bans for those sources; it is neither an authentication mechanism nor permission to trust arbitrary traffic from them.
Validate first, then reload only changed hosts
An operations walkthrough highlights an easy operational mistake: starting an already-running daemon does not load new jail settings. Example 3 therefore has three explicit boundaries after the file deploy:
- Run the read-only
fail2ban-client -taction on every selected host, and stop on any nonzero exit. - Ensure the service is running and enabled with a separate stateful deploy.
- Reload only hosts whose named configuration operations changed.
The handler itself is small:
# fail2ban_configure.py: reload_changed def reload_changed(host, notified=frozenset()): if host.name in notified: yield op( fail2ban.reload_config, name="Reload changed jail policy", sudo=True, when=is_ubuntu, ) The caller obtains notified from changed_hosts(report, CONFIG_NAMES) after apply, not from the speculative preview. A global reload includes newly enabled jails. reload_config is stateless: it always changes when requested. The notification set supplies convergence by requesting it only when necessary. See handlers, actions and the two-phase driver.
Validation happens after installing the files but before activating them. Fail2ban validates a configuration directory tree, not a single spooled jail fragment. This is not a transactional deployment: invalid files remain on disk, and an already-running daemon keeps its previously loaded policy. Do not reboot or independently restart it while repairing the configuration. Fix the input or conflicting local file, then rerun example 3 with the same desired options plus --apply --reload. The explicit reload also recovers after an interrupted or failed handler when file contents already match. A preview prints the file plan and explains the later validation/service steps; it cannot certify uninstalled configuration.
Add web and application protection deliberately
An optional web-server jail becomes the explicit --nginx option. It enables the packaged nginx-http-auth and nginx-limit-req filters plus our reemote-nginx-probe access-log filter. The script requires both nginx logs to be readable before writing configuration. It does not install nginx, enable basic authentication or configure nginx rate limits: these are prerequisites of the web service being protected, not effects of enabling a jail.
Every web jail uses backend = polling, overriding journal defaults. Basic-auth failures and rate-limit rejections come from /var/log/nginx/error.log; the narrow probe filter reads /var/log/nginx/access.log. It matches rejected requests for selected sensitive paths, not every 403 or 404. A legitimate missing page must not ban its visitor. The custom filter expects nginx's standard combined-log shape; a JSON log needs a different filter.
uv run python examples/articles/crowdsec/fail2ban_configure.py --admin-network 198.51.100.10/32 --nginx uv run python examples/articles/crowdsec/fail2ban_configure.py --admin-network 198.51.100.10/32 --nginx --apply For an application with its own authentication log, the second custom filter is:
[Definition] failregex = ^\s*auth failed client=<HOST> user=\S+$ ignoreregex = It expects a date followed by a server-generated record such as the following; Fail2ban removes the recognized timestamp before matching:
2026-01-01 12:00:00 auth failed client=192.0.2.123 user=alice Use --app-log /var/log/myapp/auth.log to enable this jail on ports 80 and 443. The log must already exist and be readable. The application must write the address from a trusted connection context and escape user-controlled fields so they cannot forge records. These scripts do not deploy an application or manufacture a production log to satisfy a missing prerequisite. Optional jails are written as disabled when their flags are omitted: repeat all desired flags on every run, including when recovering with --reload.
For a reverse proxy or CDN, logging an original client address is not enough: the firewall must also be able to block that address at the enforcement point. Do not ban your proxy fleet, and do not trust an arbitrary forwarded header. Apache and Caddy authentication logs, Postfix, Dovecot and OpenVPN can use the same jail pattern, but each needs its own verified filter, log source, ports and service prerequisites. This article does not enable those jails automatically.
Test filters without attacking the SSH connection
Example 4 installs fixtures under /var/lib/reemote-fail2ban-examples/, outside every enabled log path. It runs the real remote fail2ban-regex executable against each installed custom filter and requires exactly two matches and two misses. The application cases include IPv4, IPv6, a successful login and a non-authentication message; the nginx cases distinguish rejected probes from ordinary missing pages and successful responses.
uv run python examples/articles/crowdsec/fail2ban_check_filters.py uv run python examples/articles/crowdsec/fail2ban_check_filters.py --apply Run examples 2 and 3 first. Example 4 writes only isolated fixtures and never injects them into production logs or triggers the daemon's ban actions. Its apply flag authorizes fixture installation and the subsequent regex checks; its preview does neither. Repeated fixture writes converge, while the read-only regex checks still run on every explicit apply.
Those fixtures establish a small contract, not universal log-format compatibility. Before enabling an application jail, use representative failure and success records from that application as additional test cases. Test date recognition and extracted addresses, not merely whether the regex compiles. Do not generate failed SSH logins from the only address that can administer the host.
Inspect jails and exercise ban convergence
Example 5 replaces shell-output parsing with typed facts:
# fail2ban_inspect.py: inspect_hosts async def inspect_hosts(): await checked_action("fail2ban-client ping") hosts = [Host.from_inventory(entry) for entry in INVENTORY] try: jails = await gather_fact(hosts, fail2ban.Fail2banJails, sudo=True) rows = [] for host in hosts: details = {} for jail in jails[host.name]: status = await gather_fact( [host], fail2ban.Fail2banJailStatus, jail, sudo=True ) details[jail] = status[host.name] rows.append({"host": host.name, "jails": details}) return rows finally: for host in hosts: await host.aclose() uv run python examples/articles/crowdsec/fail2ban_inspect.py The initial jail-list read fans out across hosts; detail reads then visit each host's active jails. The resulting JSON carries current and total failure/ban counters plus banned addresses. gather_fact does not own the connections, so the finally block closes them. The initial checked ping fails visibly if the daemon is unavailable. Treat a missing expected jail as an operational problem, not as proof that no one is attacking.
For a controlled runtime test, example 6 is deliberately restricted to 192.0.2.123, an address reserved for documentation. It never accepts your management IP as a CLI argument:
# fail2ban_bans.py: deploy def deploy(host, banned=False): operation = fail2ban.ensure_ip_banned if banned else fail2ban.ensure_ip_unbanned yield op( operation, name="Set test address ban state", jail="sshd", ip=TEST_IP, sudo=True, when=is_ubuntu, ) uv run python examples/articles/crowdsec/fail2ban_bans.py ban uv run python examples/articles/crowdsec/fail2ban_bans.py ban --apply uv run python examples/articles/crowdsec/fail2ban_bans.py ban --apply uv run python examples/articles/crowdsec/fail2ban_inspect.py uv run python examples/articles/crowdsec/fail2ban_bans.py unban --apply uv run python examples/articles/crowdsec/fail2ban_bans.py unban --apply Run this only after the SSH jail is active, and finish with unban. Both operations read current ban state; a repeated ban or unban is a no-op while that state still holds. An expired ban makes a later ban request a real change again. This is a real firewall mutation, not proof that an authentication failure reaches the filter or that traffic is blocked on every network path. Verify enforcement separately from a controlled client with console recovery available. Never flush the entire firewall as a troubleshooting shortcut.
Escalation, notifications and operating limits
Pass --incremental to example 3 to enable bantime.increment with a one-week maximum. Repeated bans can then grow according to Fail2ban's ban history. Keep the SQLite database persistent and review its retention policy; this example leaves dbfile and dbpurgeage at the distribution's values rather than claiming to establish indefinite ban history. Recidive is another approach, but requires Fail2ban's own log and can impose all-port bans. It is not enabled here.
Published guides also discuss mail alerts. This policy deliberately uses action_, the ban-only action. action_mwl additionally sends mail with whois/log information and requires a working MTA, correct sender/recipient settings and consideration of sensitive log contents. A step-by-step server guide covers SSH/Postfix and email configuration; do not turn its optional mail action on without provisioning and testing those dependencies. Setting an email address alone does not send alerts or preserve bans.
Fail2ban is reactive: enough failures must reach the logs before a ban happens. Distributed password guessing can stay below each address's threshold. Keep SSH keys, authentication rate limits, updates and a restrictive base firewall. Local ban state is not a shared reputation service; unlike CrowdSec's collaborative intelligence, another server normally has no knowledge of this host's bans.
When a jail is quiet, verify that its service is emitting the expected records and that its backend and filter match them. When a ban appears ineffective, check the selected action and the actual firewall layer. For nftables actions, inspect nftables rather than assuming an iptables listing is authoritative. A configuration syntax check cannot prove kernel support or packet filtering. A cloud-provider Fail2ban tutorial is additional background on installation and operation; exact package defaults vary by distribution and release.
Verify the implementation
The focused suite imports all six real-host scripts and their shared helper, exercises the deploys through SimulatedHost, and checks the article's canonical copy and code excerpts:
uv run pytest -q tests/test_fail2ban_article_examples.py Coverage includes inventory selection, hashable/elevated requests, dry-run non-mutation, package/file/service convergence, optional-jail enable/disable behavior, validation failures that prevent activation, changed-host reloads, forced activation recovery, filter fixtures, fact cleanup and repeated ban/unban behavior. Offline simulation does not certify the target's journal, nginx log format or firewall kernel; example 4 supplies the real-host regex check and example 5 supplies runtime visibility.
For a live convergence check, apply example 2 without --refresh twice, then example 3 twice with identical arguments, then example 4 twice. Packages, files and service state should settle; the unchanged policy should not reload. Validation and fixture checks remain read-only actions, not spurious configuration changes. No live deployment result is claimed here: review the inventory and run the opt-in sequence on your own hosts. The Podman transcript in the canonical section is copied from the Alpine article.
Implementation summary
The migration turns package tasks, templates, loops, handlers and status commands into a small set of importable Python scripts. Reemote installs Fail2ban's dependencies, writes owned fil...
