Fabric - 测试与多个主机的SSH连接

时间:2016-03-03 19:49:33

标签: python ssh fabric

我有一个Python脚本,它使用结构库来测试与多个主机的SSH连接。我想将所有结果收集到一个列表中:

...
import fabric
from fabric.api import *

results = []

@parallel
def test_connection():
  global results
  try:
    run('ls')
    results += "%s: SUCCESS" % env.host
  except Exception as e:
    results += "%s: FAILURE. Exception: %e" % (env.host, e)

if __name__ == '__main__':
    tasks.execute(test_connection)
    print results

当我执行脚本时,我得到以下内容:

Traceback (most recent call last):
  File "./test_ssh.py", line 99, in <module>
    tasks.execute(test_connection)
  File "/Library/Python/2.7/site-packages/fabric/tasks.py", line 387, in execute
    multiprocessing
  File "/Library/Python/2.7/site-packages/fabric/tasks.py", line 277, in _execute
    return task.run(*args, **kwargs)
  File "/Library/Python/2.7/site-packages/fabric/tasks.py", line 174, in run
    return self.wrapped(*args, **kwargs)
  File "./test_ssh.py", line 96, in test_connection
    results += "%s: FAILURE. Exception: %e" % (env.host, e)
UnboundLocalError: local variable 'results' referenced before assignment

我认为这是因为test_connection运行了自己的上下文,所以它无法访问results

那么我可以通过另一种方式收集我的结果吗?

1 个答案:

答案 0 :(得分:4)

诀窍是你可以实际返回parallel执行结果:

@parallel
def test_connection():
  try:
    run('ls')
    return True
  except Exception:
    return False

现在,当你打电话给你的任务时,你会得到:

result = execute(test_connection)
results = [ ('HOST %s succeeded' % key) if value else ('HOST %s failed' % key) for key, value in result.items() ]