A Python library and command-line tool for streamlining SSH usage in application deployment and systems administration.
npx @tessl/cli install tessl/pypi-fabric@1.10.0Fabric 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.
pip install fabricfabfrom fabric.api import *Or import specific functions:
from fabric.api import run, sudo, put, get, env, cd, settingsIndividual 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, putsContrib 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 confirmfrom 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 deployFabric's architecture centers around several key components:
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.
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"""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"""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"""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"""env = _AttributeDict()
"""Global environment dictionary containing connection and execution settings"""Key Connection Settings:
env.hosts - List of host strings for task executionenv.user - Default username for SSH connectionsenv.password - Default password for SSH connectionsenv.key_filename - Path to SSH private key file(s)env.port - Default SSH port (default: 22)env.gateway - SSH gateway/bastion host configurationKey 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 templateenv.parallel - Enable parallel execution (default: False)env.pool_size - Number of concurrent connections for parallel executionoutput = _AliasDict()
"""Output control settings dictionary"""Output Categories:
output.running - Show "[host] run: command" linesoutput.stdout - Show command standard outputoutput.stderr - Show command standard erroroutput.warnings - Show warning messagesoutput.aborts - Show abort messagesoutput.debug - Show debug informationclass NetworkError(Exception):
"""Network-related errors during SSH operations"""
class CommandTimeout(Exception):
"""Command execution timeout errors"""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"""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