Notes on Fabric 2 and Python 3
Fabric 2 is a Python package used for running commands on remote machines via SSH. Fabric 2 supports Python 3 and is a rewrite of the Fabric I used years ago. Here are my notes on using Fabric 2 and Python 3.
Set up SSH config and SSH agent
- Create or edit your
~/.ssh/config
file to contain your remote host parametersHost myhost User myusername HostName myhost.com IdentityFile ~/.ssh/id_rsa
- Add your private key to your SSH agent
$ ssh-add ~/.ssh/id_rsa
Create a project, create a virtualenv, and install fabric2
$ mkdir -p /tmp/my-project
$ cd /tmp/my-project
$ python3 -m venv venv
$ source venv/bin/activate
$ pip install fabric2
Create a fabfile.py script
Create a file /tmp/my-project/fabfile.py
with the following contents. Note: "myhost" is the same name used in ~/.ssh/config
described above.
from fabric2 import task
hosts = ["myhost"]
@task(hosts=hosts)
def mytask(c):
print("Starting mytask...")
with c.cd("/var"):
c.run("ls -l")
print("Done.")
Run the fabric script
In /tmp/my-project
, with the virtualenv activated, run the fabric task to list the contents of /var
on the remote host.
$ fab2 mytask
Output:
Starting mytask... total 48 drwxr-xr-x 2 root root 4096 backups drwxr-xr-x 9 root root 4096 cache drwxrwxrwt 2 root root 4096 crash drwxr-xr-x 38 root root 4096 lib drwxrwsr-x 2 root root 4096 local drwxrwxrwt 2 root root 4096 lock drwxrwxr-x 14 root root 4096 log drwxrwsr-x 2 root root 4096 mail drwxr-xr-x 2 root root 4096 opt drwxr-xr-x 5 root root 4096 spool drwxrwxrwt 2 root root 4096 tmp drwxr-xr-x 3 root root 4096 www Done.
See also / References
Related posts
- How to expose a Flask local development server to the public using SSH remote port forwarding — posted 2013-02-12
- How to run a Django local development server on a remote machine and access it in your browser on your local machine using SSH port forwarding — posted 2012-10-23
- Notes on debugging ssh connection problems — posted 2011-08-31
- Fabric post-run processing Python decorator — posted 2010-11-06
- Class-based Fabric scripts via a Python metaprogramming hack — posted 2010-09-23