Claude Code for Fabric: Remote SSH Automation in Python — Claude Skills 360 Blog
Blog / AI / Claude Code for Fabric: Remote SSH Automation in Python
AI

Claude Code for Fabric: Remote SSH Automation in Python

Published: May 7, 2028
Read time: 5 min read
By: Claude Skills 360

Fabric automates remote SSH tasks. pip install fabric. Connect: from fabric import Connection; c = Connection("user@host"). Run: c.run("ls -la"). Sudo: c.sudo("systemctl restart nginx"). Upload: c.put("local.txt", "/remote/path/file.txt"). Download: c.get("/remote/log.txt", "local_log.txt"). Local: c.local("pytest tests/"). cd context: with c.cd("/var/www"): c.run("git pull"). Prefix: with c.prefix("source venv/bin/activate"): c.run("pip install -r requirements.txt"). Config: Connection("host", connect_kwargs={"key_filename": "~/.ssh/id_rsa"}). Password: connect_kwargs={"password": "pw"}. Port: Connection("host", port=2222). Gateway (jump host): Connection("target", gateway=Connection("bastion")). Group serial: from fabric import SerialGroup; g = SerialGroup("h1","h2"); g.run("uptime"). Group threaded: from fabric import ThreadedGroup; ThreadedGroup("h1","h2").run("df -h"). Result: r = c.run("pwd"); r.stdout.strip(). Warn only: c.run("cmd", warn=True). Hide output: c.run("cmd", hide=True). Responder (interactive): from fabric import Responder; c.sudo("cmd", watchers=[Responder(r"password:", "mypass\n")]). Context manager: with Connection("host") as c: c.run("..."). fabfile.py: define tasks as @task def deploy(c): c.run(...). Claude Code generates Fabric deploy scripts, rolling server updates, and multi-host automation.

CLAUDE.md for Fabric

## Fabric Stack
- Version: fabric >= 3.2 | pip install fabric
- Connect: c = Connection("user@host") | Connection("host", user="u", port=22)
- Run: c.run("cmd") | c.sudo("cmd") | c.local("cmd")
- Files: c.put("local", "remote") | c.get("remote", "local")
- Context: with c.cd("/path"): | with c.prefix("source venv/bin/activate"):
- Groups: SerialGroup("h1","h2").run("cmd") | ThreadedGroup for parallel

Fabric Remote Automation Pipeline

# app/deploy.py — Fabric Connection, run/sudo/put/get, deploy tasks, multi-host
from __future__ import annotations

import sys
from contextlib import contextmanager
from pathlib import Path
from typing import Callable

from fabric import Connection, SerialGroup, ThreadedGroup
from invoke import task, Collection


# ─────────────────────────────────────────────────────────────────────────────
# 1. Connection helpers
# ─────────────────────────────────────────────────────────────────────────────

def connect(
    host: str,
    user: str | None = None,
    port: int = 22,
    key_file: str | None = None,
    password: str | None = None,
    gateway: str | None = None,
) -> Connection:
    """
    Create a Fabric Connection.
    gateway: hostname of SSH bastion/jump host.

    Example:
        c = connect("prod01.example.com", user="deploy", key_file="~/.ssh/deploy_key")
    """
    connect_kwargs: dict = {}
    if key_file:
        connect_kwargs["key_filename"] = str(Path(key_file).expanduser())
    if password:
        connect_kwargs["password"] = password

    kwargs: dict = {"port": port}
    if user:
        kwargs["user"] = user
    if connect_kwargs:
        kwargs["connect_kwargs"] = connect_kwargs
    if gateway:
        kwargs["gateway"] = Connection(gateway)

    return Connection(host, **kwargs)


def run(c: Connection, cmd: str, hide: bool = True, warn: bool = False) -> str:
    """Run a remote command and return stdout as a stripped string."""
    result = c.run(cmd, hide=hide, warn=warn)
    return result.stdout.strip()


def sudo(c: Connection, cmd: str, hide: bool = True, warn: bool = False) -> str:
    """Run a remote command with sudo and return stdout."""
    result = c.sudo(cmd, hide=hide, warn=warn)
    return result.stdout.strip()


def local(c: Connection, cmd: str, hide: bool = False) -> str:
    """Run a local command and return stdout."""
    result = c.local(cmd, hide=hide)
    return result.stdout.strip()


# ─────────────────────────────────────────────────────────────────────────────
# 2. File transfer helpers
# ─────────────────────────────────────────────────────────────────────────────

def upload(c: Connection, local_path: str | Path, remote_path: str) -> None:
    """
    Upload a local file to the remote host.
    Creates parent directories on the remote if needed.
    """
    remote = Path(remote_path)
    c.run(f"mkdir -p {remote.parent}", hide=True)
    c.put(str(local_path), str(remote_path))


def download(c: Connection, remote_path: str, local_path: str | Path) -> None:
    """Download a remote file to the local machine."""
    c.get(str(remote_path), str(local_path))


def upload_dir(
    c: Connection,
    local_dir: str | Path,
    remote_dir: str,
    exclude: list[str] | None = None,
) -> int:
    """
    Recursively upload a local directory using rsync (requires rsync on both ends).
    Returns number of files transferred (from rsync output).
    exclude: patterns passed to --exclude (e.g. ["*.pyc", "__pycache__"]).
    """
    excludes = ""
    for pat in (exclude or []):
        excludes += f" --exclude='{pat}'"
    c.local(
        f"rsync -avz --delete{excludes} {local_dir}/ "
        f"{c.user or ''}@{c.host}:{remote_dir}/",
        hide=True,
    )
    return 0  # rsync output parsing omitted for brevity


# ─────────────────────────────────────────────────────────────────────────────
# 3. Deployment tasks
# ─────────────────────────────────────────────────────────────────────────────

def deploy_app(
    c: Connection,
    repo_dir: str,
    branch: str = "main",
    requirements: bool = True,
    migrate: bool = True,
    service: str | None = None,
    python: str = "python3",
) -> dict:
    """
    Standard Python web app deploy:
    1. git pull
    2. pip install -r requirements.txt
    3. database migrate
    4. restart service

    Returns dict of step results.
    """
    steps: dict = {}

    with c.cd(repo_dir):
        # 1. Pull latest code
        print(f"  [{c.host}] git pull origin {branch}")
        steps["git_pull"] = run(c, f"git pull origin {branch}")

        # 2. Install dependencies
        if requirements:
            print(f"  [{c.host}] pip install")
            with c.prefix(f"{python} -m venv .venv && source .venv/bin/activate"):
                steps["pip"] = run(c, "pip install -r requirements.txt -q")

        # 3. Migrate
        if migrate:
            print(f"  [{c.host}] migrate")
            with c.prefix("source .venv/bin/activate"):
                steps["migrate"] = run(c, f"{python} manage.py migrate --noinput", warn=True)

    # 4. Restart service
    if service:
        print(f"  [{c.host}] restart {service}")
        steps["restart"] = sudo(c, f"systemctl restart {service}", warn=True)

    return steps


def rolling_deploy(
    hosts: list[str],
    repo_dir: str,
    branch: str = "main",
    service: str | None = None,
    user: str | None = None,
    key_file: str | None = None,
    health_check: Callable[[Connection], bool] | None = None,
    stop_on_failure: bool = True,
) -> dict[str, dict]:
    """
    Deploy to multiple hosts one at a time (rolling update).
    Runs health_check after each host; stops on failure if stop_on_failure=True.

    Returns {host: steps_dict}.
    """
    results: dict[str, dict] = {}
    for host in hosts:
        print(f"\n=== Deploying to {host} ===")
        try:
            c = connect(host, user=user, key_file=key_file)
            steps = deploy_app(c, repo_dir, branch=branch, service=service)
            if health_check and not health_check(c):
                steps["health"] = "FAILED"
                print(f"  [{host}] health check FAILED")
                if stop_on_failure:
                    results[host] = steps
                    break
            else:
                steps["health"] = "ok"
            results[host] = steps
        except Exception as e:
            results[host] = {"error": str(e)}
            print(f"  [{host}] ERROR: {e}")
            if stop_on_failure:
                break

    return results


# ─────────────────────────────────────────────────────────────────────────────
# 4. Multi-host operations
# ─────────────────────────────────────────────────────────────────────────────

def run_on_all(
    hosts: list[str],
    cmd: str,
    parallel: bool = False,
    user: str | None = None,
) -> dict[str, str]:
    """
    Run a shell command on multiple hosts.
    parallel=True: uses ThreadedGroup (concurrent).
    Returns {host: stdout}.
    """
    host_strs = [f"{user}@{h}" if user else h for h in hosts]
    GroupCls = ThreadedGroup if parallel else SerialGroup
    group = GroupCls(*host_strs)

    results = {}
    try:
        for conn, result in group.run(cmd, hide=True).items():
            results[conn.host] = result.stdout.strip()
    except Exception as e:
        print(f"Group run error: {e}", file=sys.stderr)

    return results


def tail_logs(
    c: Connection,
    log_path: str = "/var/log/app/app.log",
    lines: int = 50,
) -> str:
    """Fetch the last N lines of a remote log file."""
    return run(c, f"tail -n {lines} {log_path}", warn=True)


def check_disk(c: Connection, path: str = "/") -> dict[str, str]:
    """Return disk usage for a path on the remote host."""
    raw = run(c, f"df -h {path} | tail -1")
    parts = raw.split()
    if len(parts) >= 5:
        return {"filesystem": parts[0], "size": parts[1],
                "used": parts[2], "avail": parts[3], "use%": parts[4]}
    return {"raw": raw}


# ─────────────────────────────────────────────────────────────────────────────
# 5. Invoke task integration
# ─────────────────────────────────────────────────────────────────────────────

# These tasks can be run with: invoke deploy --host prod01
# or bundled in a fabfile.py:
#   from deploy import ns  →  fab deploy --host prod01

@task
def deploy_task(ctx, host, branch="main", service="myapp", user="deploy"):
    """Deploy app to a single host."""
    c = connect(host, user=user)
    steps = deploy_app(c, "/var/www/myapp", branch=branch, service=service)
    for step, out in steps.items():
        print(f"  {step}: {str(out)[:80]}")


@task
def status(ctx, host, user="deploy"):
    """Check service and disk status on a host."""
    c = connect(host, user=user)
    print("Uptime:", run(c, "uptime"))
    print("Disk:  ", check_disk(c))


ns = Collection("app")
ns.add_task(deploy_task, "deploy")
ns.add_task(status)


# ─────────────────────────────────────────────────────────────────────────────
# Demo (local dry-run — connects to localhost if SSH is set up)
# ─────────────────────────────────────────────────────────────────────────────

if __name__ == "__main__":
    # Demonstrate local command execution (no SSH needed)
    from invoke import Context
    ctx = Context()

    print("=== Local commands via invoke ===")
    result = ctx.run("echo 'Hello from local'", hide=True)
    print(f"  local run: {result.stdout.strip()!r}")

    result = ctx.run("uname -s", hide=True)
    print(f"  OS: {result.stdout.strip()}")

    print("\n=== SSH usage examples ===")
    print("  c = Connection('user@host')")
    print("  with c: c.run('uptime')")
    print("  c.put('dist.tar.gz', '/tmp/dist.tar.gz')")
    print("  with c.cd('/var/www'): c.sudo('systemctl restart app')")

For the paramiko alternative — paramiko provides the low-level SSH2 protocol implementation (SFTP client, channel management, host key verification); Fabric builds on paramiko (and invoke) to provide a higher-level task-running API with cd(), prefix(), put(), and group execution — use paramiko when you need fine-grained protocol control, Fabric when you need readable deployment scripts with context managers and multi-host support. For the ansible alternative — Ansible uses YAML playbooks and an agentless push model for idempotent configuration management at scale; Fabric is a Python library that you call from code — it is better for dynamic deployment logic, conditional branching, and integration with Python CI pipelines where you want to programmatically construct which hosts to update and in what order. The Claude Skills 360 bundle includes Fabric skill sets covering connect() with key_file/gateway/password, run/sudo/local helpers, upload()/download()/upload_dir() rsync, deploy_app() git-pull/pip/migrate/restart, rolling_deploy() with health check, run_on_all() serial/parallel group, tail_logs()/check_disk() monitoring helpers, and invoke @task integration for fabfile.py. Start with the free tier to try SSH deployment automation code generation.

Keep Reading

AI

Claude Code for email.contentmanager: Python Email Content Accessors

Read and write EmailMessage body content with Python's email.contentmanager module and Claude Code — email contentmanager ContentManager for the class that maps content types to get and set handler functions allowing EmailMessage to support get_content and set_content with type-specific behaviour, email contentmanager raw_data_manager for the ContentManager instance that handles raw bytes and str payloads without any conversion, email contentmanager content_manager for the standard ContentManager instance used by email.policy.default that intelligently handles text plain text html multipart and binary content types, email contentmanager get_content_text for the handler that returns the decoded text payload of a text-star message part as a str, email contentmanager get_content_binary for the handler that returns the raw decoded bytes payload of a non-text message part, email contentmanager get_data_manager for the get-handler lookup used by EmailMessage get_content to find the right reader function for the content type, email contentmanager set_content text for the handler that creates and sets a text part correctly choosing charset and transfer encoding, email contentmanager set_content bytes for the handler that creates and sets a binary part with base64 encoding and optional filename Content-Disposition, email contentmanager EmailMessage get_content for the method that reads the message body using the registered content manager handlers, email contentmanager EmailMessage set_content for the method that sets the message body and MIME headers in one call, email contentmanager EmailMessage make_alternative make_mixed make_related for the methods that convert a simple message into a multipart container, email contentmanager EmailMessage add_attachment for the method that attaches a file or bytes to a multipart message, and email contentmanager integration with email.message and email.policy and email.mime and io for building high-level email readers attachment extractors text body accessors HTML readers and policy-aware MIME construction pipelines.

5 min read Feb 12, 2029
AI

Claude Code for email.charset: Python Email Charset Encoding

Control header and body encoding for international email with Python's email.charset module and Claude Code — email charset Charset for the class that wraps a character set name with the encoding rules for header encoding and body encoding describing how to encode text for that charset in email messages, email charset Charset header_encoding for the attribute specifying whether headers using this charset should use QP quoted-printable encoding BASE64 encoding or no encoding, email charset Charset body_encoding for the attribute specifying the Content-Transfer-Encoding to use for message bodies in this charset such as QP or BASE64, email charset Charset output_codec for the attribute giving the Python codec name used to encode the string to bytes for the wire format, email charset Charset input_codec for the attribute giving the Python codec name used to decode incoming bytes to str, email charset Charset get_output_charset for returning the output charset name, email charset Charset header_encode for encoding a header string using the charset's header_encoding method, email charset Charset body_encode for encoding body content using the charset's body_encoding, email charset Charset convert for converting a string from the input_codec to the output_codec, email charset add_charset for registering a new charset with custom encoding rules in the global charset registry, email charset add_alias for adding an alias name that maps to an existing registered charset, email charset add_codec for registering a codec name mapping for use by the charset machinery, and email charset integration with email.message and email.mime and email.policy and email.encoders for building international email senders non-ASCII header encoders Content-Transfer-Encoding selectors charset-aware message constructors and MIME encoding pipelines.

5 min read Feb 11, 2029
AI

Claude Code for email.utils: Python Email Address and Header Utilities

Parse and format RFC 2822 email addresses and dates with Python's email.utils module and Claude Code — email utils parseaddr for splitting a display-name plus angle-bracket address string into a realname and email address tuple, email utils formataddr for combining a realname and address string into a properly quoted RFC 2822 address with angle brackets, email utils getaddresses for parsing a list of raw address header strings each potentially containing multiple comma-separated addresses into a list of realname address tuples, email utils parsedate for parsing an RFC 2822 date string into a nine-tuple compatible with time.mktime, email utils parsedate_tz for parsing an RFC 2822 date string into a ten-tuple that includes the UTC offset timezone in seconds, email utils parsedate_to_datetime for parsing an RFC 2822 date string into an aware datetime object with timezone, email utils formatdate for formatting a POSIX timestamp or the current time as an RFC 2822 date string with optional usegmt and localtime flags, email utils format_datetime for formatting a datetime object as an RFC 2822 date string, email utils make_msgid for generating a globally unique Message-ID string with optional idstring and domain components, email utils decode_rfc2231 for decoding an RFC 2231 encoded parameter value into a tuple of charset language and value, email utils encode_rfc2231 for encoding a string as an RFC 2231 encoded parameter value, email utils collapse_rfc2231_value for collapsing a decoded RFC 2231 tuple to a Unicode string, and email utils integration with email.message and email.headerregistry and datetime and time for building address parsers date formatters message-id generators header extractors and RFC-compliant email construction utilities.

5 min read Feb 10, 2029

Put these ideas into practice

Claude Skills 360 gives you production-ready skills for everything in this article — and 2,350+ more. Start free or go all-in.

Back to Blog

Get 360 skills free