在不使用命令行工具(fab)的情况下使用Python Fabric

19 投票
5 回答
9987 浏览
提问于 2025-04-16 21:48

虽然Fabric的文档提到了一种可以在不使用fab命令行工具和任务的情况下,通过SSH访问库的方法,但我似乎找不到实现这个方法的办法。

我想通过只执行'python example.py'来运行这个文件(example.py):

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

谢谢。

5 个回答

4

这里有三种不同的方法,都是使用 execute 这个方法。

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)

如果你要使用密钥文件,你需要设置 env.key 或者 env.key_filename,像这样:

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

你还可以提供多个密钥文件,哪个能让你登录到那个主机,就会使用哪个。

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)

更多信息请查看:http://docs.fabfile.org/en/latest/usage/library.html

16

我最后做成了这样:

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')

这样会产生:

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

撰写回答