Skip to content Skip to sidebar Skip to footer

Using Python Fabric Without The Command-line Tool (fab)

Altough Fabric documentations refers to a way of using the library for SSH access without requiring the fab command-line tool and/or tasks, I can't seem to manage a way to do it. I

Solution 1:

I ended up doing this:

from fabric.api import env
from fabric.api import run

classFabricSupport:
    def__init__ (self):
        passdefrun(self, host, port, command):
        env.host_string = "%s:%s" % (host, port)
        run(command)

myfab = FabricSupport()

myfab.run('example.com', 22, 'uname')

Which produces:

[example.com:22] run: uname
[example.com:22] out: Linux

Solution 2:

#!/usr/bin/env pythonfrom fabric.api import hosts, run, task
from fabric.tasks import execute

@task@hosts(['user@host:port'])deftest():
    run('hostname -f')

if __name__ == '__main__':
   execute(test)

More information: http://docs.fabfile.org/en/latest/usage/library.html

Solution 3:

Here are three different approaches all using the execute method

from fabric.api import env,run,execute,hosts

# 1 - Set the (global) host_string
env.host_string = "hamiltont@10.0.0.2"deffoo():
  run("ps")
execute(foo)

# 2 - Set host string using execute's host param
execute(foo, hosts=['hamiltont@10.0.0.2'])

# 3 - Annotate the function and call it using execute@hosts('hamiltont@10.0.0.2')defbar():
  run("ps -ef")
execute(bar)

For using keyfiles, you'll need to set either env.key or env.key_filename, as so:

env.key_filename = 'path/to/my/id_rsa'# Now calls with execute will use this keyfile
execute(foo, hosts=['hamiltont@10.0.0.2'])

You can also supply multiple keyfiles and whichever one logs you into that host will be used

Solution 4:

Found my fix. I needed to provided my own *env.host_string* because changing env.user/env.keyfile/etc doesn't automatically updates this field.

Solution 5:

This is what needs to be done:

in example.py

from fabric.api import settings, run

def ps():
  withsettings(host_string='example.com'):
    run("ps")
ps()

see docs for using fabric as a library: http://docs.fabfile.org/en/1.8/usage/env.html#host-string

Post a Comment for "Using Python Fabric Without The Command-line Tool (fab)"