19

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 want to run this file (example.py) by only executing 'python example.py':

env.hosts = [ "example.com" ]
def ps():
    run("ps")
ps()

Thanks.

5 Answers 5

16

I ended up doing this:

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

class FabricSupport:
    def __init__ (self):
        pass

    def run(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
0
4
#!/usr/bin/env python
from fabric.api import hosts, run, task
from fabric.tasks import execute

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

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

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

4

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 = "[email protected]"
def foo():
  run("ps")
execute(foo)

# 2 - Set host string using execute's host param
execute(foo, hosts=['[email protected]'])

# 3 - Annotate the function and call it using execute
@hosts('[email protected]')
def bar():
  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=['[email protected]'])

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

1
  • Can we pass the evn key in execute()
    – reetesh11
    Sep 22, 2017 at 10:16
3

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.

1
  • 3
    Could you please post the complete code which was working for you? I can not seem to get it right from your answer.
    – blueFast
    Dec 1, 2011 at 14:43
1

This is what needs to be done:

in example.py

from fabric.api import settings, run

def ps():
  with settings(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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.