在使用Fabric的SSH连接期间,我试图跳过提示。就像Python Fabric: Skip logins needing passwords。我在文档中看到,选项abort_on_prompts应该这样做。但我不能让它起作用。
#!/usr/bin/python
from fabric.api import *
env.abort_on_prompts=True
def remote_cmd(server_name):
with settings(hide('output','running','warnings'),
host_string=server_name,
user = 'john',
key_filename = '/home/john/id_rsa',
warn_only=True):
return run('ls /data/')
server_name = 'server01'
ls_result = remote_cmd(server_name)这段代码一直要求我提供server01 01的密码(因为它没有公钥),而我想跳过它。
发布于 2015-08-03 15:22:28
多亏了FunkySayu,我终于找到了解决方案和问题所在。我在Debian 6上使用了Python2.6.6和Fabric 0.9,所以我用Python2.7.9和Fabric 1.10在Debian 8上试用了它,它工作得很好!
abort_on_prompts退出脚本,但我想跳过它。下面是我找到的解决方案:
#!/usr/bin/python
from fabric.api import *
env.abort_on_prompts=True
def remote_cmd(server_name):
with settings(hide('output','running','warnings'),
host_string=server_name,
user = 'john',
key_filename = '/home/john/id_rsa',
warn_only=True):
return run('ls /data/')
servers = (('server01',), ('server02',))
for row in servers:
server_name = row[0]
print "Connection to ", server_name
try:
result_ls = remote_cmd(server_name)
print result_ls
except SystemExit:
print server_name," doesn't have the key"在本例中,server01在authorized_key文件中没有公钥。但是没有坏处,脚本将继续,打印一条消息,然后在server02上运行命令。我希望这是明确的:)
me@myserver:~$ ./test_fabric.py
Connection to server01
Fatal error: Needed to prompt for a connection or sudo password (host: server01), but abort-on-prompts was set to True
Aborting.
server01 doesn't have the key
Connection to server02
[we see the results of ls command]发布于 2017-01-19 15:21:41
为了使用python fabric.api env.abort_on_prompts = True并管理中止事件,必须将其与try/ SystemExit语句一起使用。下面是一个简单的示例,abort_on_promt_test.py,在您的本地主机中测试它,为执行定义一个本地角色。
from fabric.api import settings, env, run
from termcolor import colored
env.roledefs = {
'local': ['localhost'],
}
def command(cmd):
"""
Run a command in the host/s
:param cmd: bash command to be executed
eg: fab -R local command:"hostname"
eg: fab -R local command:"ls -ltra"
"""
env.abort_on_prompts = True
try:
with settings(warn_only=False):
run(cmd)
except SystemExit:
print colored('===============================================', 'red')
print colored('HOST: ' + env.host_string + ' aborted on prompt', 'red')
print colored('===============================================', 'red')以下是其测试执行的输出
delivery@delivery-E5450$ fab -f abort_on_promt_test.py -R local command:"hostname"
[localhost] Executing task 'command'
[localhost] run: hostname
Fatal error: Needed to prompt for a connection or sudo password (host: localhost), but abort-on-prompts was set to True
Aborting.
===============================================
HOST: localhost aborted on prompt
===============================================
Done.https://stackoverflow.com/questions/31789557
复制相似问题