or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

context-management.mdcore-operations.mddecorators-tasks.mdfile-operations.mdindex.md
tile.json

tessl/pypi-fabric

A Python library and command-line tool for streamlining SSH usage in application deployment and systems administration.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/fabric@1.10.x

To install, run

npx @tessl/cli install tessl/pypi-fabric@1.10.0

index.mddocs/

Fabric

Fabric is a Python library and command-line tool that streamlines SSH usage for application deployment and systems administration tasks. It provides a comprehensive suite of operations for executing local or remote shell commands (including sudo), uploading/downloading files, and auxiliary functionality like user input prompting and execution control. The library offers a Pythonic interface to SSH protocol operations at a higher level than direct SSH libraries like Paramiko, enabling developers to create deployment scripts and automation tools through simple Python functions that can be executed via the 'fab' command-line tool across multiple servers simultaneously.

Package Information

  • Package Name: Fabric
  • Language: Python
  • Installation: pip install fabric
  • Command Line Tool: fab

Core Imports

from fabric.api import *

Or import specific functions:

from fabric.api import run, sudo, put, get, env, cd, settings

Individual module imports:

from fabric.operations import run, sudo, local, put, get
from fabric.context_managers import cd, lcd, settings, hide
from fabric.decorators import task, hosts, roles
from fabric.state import env, output
from fabric.utils import abort, warn, puts

Contrib module imports:

from fabric.contrib.files import exists, upload_template, sed, comment, append
from fabric.contrib.project import rsync_project, upload_project
from fabric.contrib.console import confirm

Basic Usage

from fabric.api import run, sudo, put, env, cd, task

# Set connection details
env.hosts = ['user@example.com']
env.key_filename = '/path/to/private/key'

@task
def deploy():
    # Execute remote commands
    run('git pull origin master')
    
    # Use sudo for privileged operations
    sudo('systemctl restart nginx')
    
    # Change directories with context manager
    with cd('/var/www/myapp'):
        run('npm install')
        run('npm run build')
    
    # Upload files
    put('local/config.json', '/etc/myapp/config.json', use_sudo=True)

# Run with: fab deploy

Architecture

Fabric's architecture centers around several key components:

  • Global Environment (env): Central configuration dictionary containing connection settings, execution parameters, and runtime state
  • Operations: Core functions for local/remote command execution, file transfer, and user interaction
  • Context Managers: Temporary state modification tools for directories, settings, and output control
  • Decorators: Function decorators for task definition, host/role specification, and execution control
  • State Management: Global variables and configuration that persist across function calls
  • CLI Integration: Command-line interface for executing tasks across multiple hosts

This design enables both programmatic use as a library and command-line execution as a deployment tool, with seamless integration between SSH operations and Python control flow.

Capabilities

Core Operations

Essential remote and local command execution, including standard shell commands and privileged operations via sudo. These operations form the foundation of Fabric's automation capabilities.

def run(command, shell=True, pty=True, combine_stderr=None, quiet=False, warn_only=False, stdout=None, stderr=None, timeout=None, shell_escape=None):
    """Execute shell command on remote host"""

def sudo(command, shell=True, pty=True, combine_stderr=None, user=None, quiet=False, warn_only=False, stdout=None, stderr=None, group=None, timeout=None, shell_escape=None):
    """Execute command with superuser privileges"""

def local(command, capture=False, shell=None):
    """Execute command on local system"""

Core Operations

Context Management

Temporary state modification tools for managing directories, environment settings, output control, and SSH tunneling. Context managers ensure clean state restoration and enable nested operations.

def cd(path):
    """Context manager for remote directory changes"""

def lcd(path):
    """Context manager for local directory changes"""

def settings(*args, **kwargs):
    """Context manager for temporary environment variable overrides"""

def hide(*groups):
    """Context manager to hide output groups"""

def shell_env(**kw):
    """Context manager to set shell environment variables"""

Context Management

Task Definition and Execution

Decorators and functions for defining Fabric tasks, specifying target hosts and roles, and controlling execution patterns including parallel and serial execution modes.

def task(*args, **kwargs):
    """Decorator to mark functions as Fabric tasks"""

def hosts(*host_list):
    """Decorator to specify target hosts for a task"""

def roles(*role_list):
    """Decorator to specify target roles for a task"""

def execute(task, *args, **kwargs):
    """Execute task with host/role resolution"""

Decorators and Tasks

File Operations

File transfer capabilities including basic upload/download operations and advanced file management functions for template rendering, text processing, and project synchronization.

def put(local_path=None, remote_path=None, use_sudo=False, mirror_local_mode=False, mode=None, use_glob=True, temp_dir=""):
    """Upload files to remote host"""

def get(remote_path, local_path=None, use_sudo=False, temp_dir=""):
    """Download files from remote host"""

File Operations

Global State and Configuration

Environment Dictionary (env)

env = _AttributeDict()
"""Global environment dictionary containing connection and execution settings"""

Key Connection Settings:

  • env.hosts - List of host strings for task execution
  • env.user - Default username for SSH connections
  • env.password - Default password for SSH connections
  • env.key_filename - Path to SSH private key file(s)
  • env.port - Default SSH port (default: 22)
  • env.gateway - SSH gateway/bastion host configuration

Key Execution Settings:

  • env.warn_only - Continue execution on command failure (default: False)
  • env.shell - Shell command prefix (default: '/bin/bash -l -c')
  • env.sudo_prefix - Sudo command prefix template
  • env.parallel - Enable parallel execution (default: False)
  • env.pool_size - Number of concurrent connections for parallel execution

Output Control Dictionary (output)

output = _AliasDict()
"""Output control settings dictionary"""

Output Categories:

  • output.running - Show "[host] run: command" lines
  • output.stdout - Show command standard output
  • output.stderr - Show command standard error
  • output.warnings - Show warning messages
  • output.aborts - Show abort messages
  • output.debug - Show debug information

Exception Classes

class NetworkError(Exception):
    """Network-related errors during SSH operations"""
    
class CommandTimeout(Exception):
    """Command execution timeout errors"""

Utility Functions

def abort(msg):
    """Abort execution with error message"""

def warn(msg):
    """Print warning message without aborting"""

def puts(text, show_prefix=None, end="\n", flush=False):
    """Managed print function with prefix support"""

def fastprint(text, show_prefix=False, end="", flush=True):
    """Immediate print without buffering"""

def prompt(text, key=None, default='', validate=None):
    """Prompt user for input with validation"""

Return Value Objects

Operations return enhanced string and list objects with additional attributes:

class _AttributeString(str):
    """String subclass with execution metadata"""
    # Attributes: .failed, .succeeded, .return_code, .command, .real_command, .stderr

class _AttributeList(list):
    """List subclass for file transfer results"""
    # Attributes: .failed, .succeeded