Fabric SSH Automation
Fabric is a high-level Python library for streamlining SSH command execution and application deployment. It is currently at version 3.2.3 and releases updates on an as-needed basis, typically for bug fixes or minor enhancements, building on Invoke and Paramiko.
Warnings
- breaking Fabric 2.x and 3.x are NOT backward compatible with Fabric 1.x. The API was completely rewritten, moving from global state ('env') to an object-oriented design centered around the 'Connection' object.
- gotcha Global state ('env') from Fabric 1.x is gone. Tasks now receive a `Connection` object (`c`) as their first argument, which holds all connection-specific information and methods.
- gotcha The global functions `run()`, `sudo()`, `local()`, `put()`, `get()` from Fabric 1.x are now methods of the `Connection` object (e.g., `c.run()`, `c.sudo()`).
- gotcha Context managers like `cd()`, `warn_only()`, `settings()` from Fabric 1.x are also now methods of the `Connection` object (e.g., `with c.cd('/path'):`).
- gotcha Configuration is handled via the `Config` object or directly on `Connection` instances, not global dictionaries. Passing parameters to tasks requires explicit arguments or configuration.
Install
-
pip install fabric
Imports
- Connection
from fabric import Connection
- task
from fabric import task
Quickstart
# fabfile.py
from fabric import Connection, task
@task
def hello(c):
"""
Runs a simple command on the remote host.
Example usage: fab -H user@localhost hello
Note: For 'localhost' to work, an SSH server must be running
and your user configured for SSH access.
"""
print(f"Connecting to {c.host} as {c.user or 'default'}...")
# Run a command, hiding the command itself from stdout, only showing output
result = c.run("echo Hello from $(hostname)", hide=True)
print(f"Output: {result.stdout.strip()}")