织物环境主机未被确认

2024-09-30 04:26:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个简单的文件名 环境_工厂文件.py

# env_fabfile.py
# makes use of fab env variables 

from fabric.api import env, run
def login():
    env.hosts = ['user@host1:1234', 'user@host2:2345']
    env.passwords = {'user@host1:1234': 'pass1', 'user@host2:2345': 'pass2'}
    env.parallel=True

def run_lsb_release():
    run('lsb_release -a')

现在我使用fab命令运行上面的命令:

fab -f env_fabfile.py login run_lsb_release

它完美地运行(并行)并给出所需的输出

现在我想实际计算同一个脚本以串行方式运行与并行运行之间的时间差。为此,我编写了以下python脚本: timecal.py

^{pr2}$

但当我跑的时候timecal.py作为

python timecal.py

我在stdout上得到了以下内容(除了代码中的print语句)

No hosts found. Please specify (single) host string for connection:

我不明白为什么?另外,如何纠正脚本,以便我可以实现我想要的(如上述问题所述)

以防我尝试不同版本的timecal.py,作为:

from fabric.api import run, settings, env
import time

def do_parallel():
    start_time = time.time()
    env.hosts = ['user@host1:1234', 'user@host2:2345']
    env.passwords = {'user@host1:1234': 'pass1', 'user@host2:2345': 'pass2'}
    env.parallel=True
    run('lsb_release -a')
    elapsed_time = time.time() - start_time
    return elapsed_time

def do_serial():
    start_time = time.time()
    with settings(host_string='host1', port=1234, user='user', password='pass1'):
        run('lsb_release -a')
    with settings(host_string='host2', port=2345, user='user', password='pass2'):
        run('lsb_release -a')
    elapsed_time = time.time() - start_time
    return elapsed_time

if __name__ == '__main__':  
    try:
        print "Running in parallel mode"
        print "Total time taken ", do_parallel()

        print "Running in serial mode "
        print "Total time taken ", do_serial()
    except Exception as e:
        print e

我得到以下错误:

Fatal error: Needed to prompt for the target host connection string (host: None), but input would be ambiguous in parallel mode

我不明白为什么主人在这里:没有?密码怎么了?在


Tags: runpyenvhostreleasestringtimeparallel
1条回答
网友
1楼 · 发布于 2024-09-30 04:26:28

简而言之,您不应该像当前那样设置env.hosts值,而且env.passowrds非常粗略(可能损坏了?),和it's recommended to use SSH key-based access,尤其是{a2}。在

这是您的timecal.py脚本如预期的那样工作,我将指出下面的一些差异。在

# timecal.py
# runs the fabfile once in serial and calculates the time
# then runs the same file in parallel and calculates the time

from fabric.api import env, run, execute, parallel
import time

env.use_ssh_config = True
env.roledefs = {
    "my_servers": ['server_1', 'server_2']
}


def run_lsb_release():
    print "in run"
    run('lsb_release -a')


def do_task(task_func):
    start_time = time.time()
    execute(task_func, roles=['my_servers'])
    elapsed_time = time.time() - start_time
    return elapsed_time


if __name__ == '__main__':
    print "Running in serial mode "
    print "Total time taken ", do_task(run_lsb_release)

    print "Running in parallel mode"
    print "Total time taken ", do_task(parallel(run_lsb_release))

主要区别在于使用env.roledefs和SSH配置文件,而不是主机密码。这些值在并行执行模式下不起作用,因为这些任务是在不同的线程中执行的。The docs有点瘦,但这就是为什么你会有这个问题。在

相关问题 更多 >

    热门问题