Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stand-alone fabfile for fabric?

Tags:

python

fabric

Is it possible to make the fabfile stand-alone?
I'm not very fond of running the external tool 'fab'. If I manage to get the fabfile standalone I can run the file from within the (Eclipse / Pydev) IDE, easily debug it, use project configurations and paths etc.
Why doesn't this work:

from fabric.api import run

def host_type():
    run('uname -s')

if __name__ == '__main__':
    host_type()    
like image 328
Tal Weiss Avatar asked Jul 19 '10 06:07

Tal Weiss


2 Answers

I eventually found the solution (and it is really simple!).
In my fabfile, I added:

from fabric.main import main

if __name__ == '__main__':
    import sys
    sys.argv = ['fab', '-f', __file__, 'update_server']
    main()

I hope this helps people...

like image 162
Tal Weiss Avatar answered Sep 19 '22 02:09

Tal Weiss


If I recall correctly, I couldn't get the Fabric API to do what I wanted either. I decided to abandon the extra layer entirely and use Paramiko (the underlying SSH library used by Fabric) directly:

import os
import paramiko

ssh = paramiko.SSHClient()
ssh.load_system_host_keys()
ssh.load_host_keys(os.path.expanduser('~/.ssh/known_hosts'))
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('hostname.example.com', 22, 'username', 'password')
ssh.save_host_keys(os.path.expanduser('~/.ssh/known_hosts'))
stdin, stdout, stderr = ssh.exec_command('uname -s')
print stdout.read()

While there are a few more steps involved, doing it this way allows you to leverage the SSH layer directly, as opposed to using subprocess to spwan another Python instance, or figuring out the Fabric API. I have several projects, both web- and console- using Paramiko in this manner and I haven't had too much trouble.

Paramiko is extensively documented.

like image 42
AdmiralNemo Avatar answered Sep 21 '22 02:09

AdmiralNemo