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.

fabiopedrosa
  • 2,521
  • 7
  • 29
  • 42

5 Answers5

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
blueFast
  • 41,341
  • 63
  • 198
  • 344
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

semente
  • 7,265
  • 3
  • 34
  • 35
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 = "hamiltont@10.0.0.2"
def foo():
  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')
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=['hamiltont@10.0.0.2'])

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

Hamy
  • 20,662
  • 15
  • 74
  • 102
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.

fabiopedrosa
  • 2,521
  • 7
  • 29
  • 42
  • 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 01 '11 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

mooli
  • 329
  • 3
  • 9