python - 如何收集结构任务输出并打印多个主机的摘要?

标签 python fabric

在 fabric 中,我有一个任务是在每个主机的基础上收集一些东西(小例子)。

from fabric.api import task, run, hide
env.hosts['h1', 'h2', 'h3']

@task
def info():
    with hide('everything'):
        info = run("who | tail -n 1")
        print("On host {0} last user was {1}".format(env.host_string, info))

运行

fab info

会给出类似的东西

[h1] Executing task 'info'
On host h1 last user was userXX  pts/29       2015-07-29 15:57 (:0)
[h2] Executing task 'info'
On host h2 last user was userXX  pts/29       2015-07-29 16:57 (:0)
[h3] Executing task 'info'
On host h3 last user was userXX  pts/29       2015-07-29 17:57 (:0)

虽然这对于 3 或 5 台主机来说很好,但对于 20 台或更多主机(或更复杂的输出)来说很难查看。我想要做的是累积每台主机的所有输出,并在每台主机上执行任务后使用它最终创建摘要/概述。

我该怎么做?

最佳答案

...在写这个问题时,在谷歌搜索不同的短语至少一个小时后,我终于找到了这个:

http://docs.fabfile.org/en/1.14/usage/execution.html#leveraging-execute-to-access-multi-host-results

虽然我浏览了这个网站几次,但我错过了相关部分,因此想把它张贴在这里,希望如果不在 google 上搜索确切的短语,它更容易找到:

from fabric.api import task, execute, run, runs_once

@task
def workhorse():
    return run("get my infos")

@task
@runs_once
def go():
    results = execute(workhorse)
    print results

因此问题中的示例可以通过以下方式解决:

from fabric.api import task, run, hide, execute, runs_once
env.hosts['h1', 'h2', 'h3']

@task
def collect_info():
    with hide('everything'):
        info = run("who | tail -n 1")
        return info

@task
@runs_once
def info():
    collected_output = execute(collect_info)
    for host, info in collected_output.iteritems():
        print("On host {0} last user was {1}".format(host, info))

关于python - 如何收集结构任务输出并打印多个主机的摘要?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31703985/

相关文章:

python - 在图中实现(修改后的)DFS

python - 如何按列的值计数对 Pandas 数据框进行排序?

python - 是否可以使用 Fabric 将命令传递到交互式 shell?

python - Windows 中的 Fabric 自动登录

python - 警告 : Unable to load SSH config file '/root/.ssh/config' in fabric

ruby - 临时更改 Rake 中的当前目录

python - 在 Windows 10 上从 python 运行时,ffmpeg.probe 不工作

python - 要么对数值进行操作,要么用 nan 替换单元格

python - 绘制非多项式多元隐式方程

django - 使用结构自动启动 virtualenv 和 Django 开发服务器?