Fabric: call run() for an explicit host

大憨熊 提交于 2020-01-15 09:11:13

问题


I'd like to use fabric as a tool to gather all server loads and process the values afterward, I thought of something like this:

from fabric.api import run

for servername in servernames:
    load_str = run('cat /proc/loadavg | cut -d' ' -f1', host=servername)

but fabric doesn't allow me to specify the hostname this way, I found this IMO ugly way:

from fabric.api import env, run

for servername in servernames:
    env.host_string = servername
    load_str = run('cat /proc/loadavg | cut -d' ' -f1')

are there more elegant ways?

Using paramiko directly, as suggested here pushes me to write an own module that abstracts it - quoting from fabrics website, that's exactly what fabric should do for me:

In addition to use via the fab fool, Fabric’s components may be imported into other Python code, providing a Pythonic interface to the SSH protocol suite at a higher level than that provided by e.g. Paramiko (which Fabric itself leverages.)


回答1:


This question offers a solution:

How to set target hosts in Fabric file




回答2:


It appears that fabric really is the wrong tool for that. The claim quoted above is probably from an earlier version. Looking at the run() code it's clear there's no module in fabric that could be used for my purpose.

There are small abstraction layers around paramiko, e.g. this one




回答3:


from fabric.api import settings

for servername in servernames:
    with settings(host_string=servername):
        load_str = run('cat /proc/loadavg | cut -d' ' -f1')

or better using execute

from fabric.tasks import execute

data = execute(load_str , hosts = servernames)

def load_str():
    return run('cat /proc/loadavg | cut -d' ' -f1') 

I'd recommend setting to skip hosts that are not reachable

env.skip_bad_hosts = True


来源:https://stackoverflow.com/questions/3567066/fabric-call-run-for-an-explicit-host

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!