我有一个使用Fabric api的python脚本。问题是我无法获得在远程服务器上启动的命令的返回码。
我知道我可以使用.return_code
获取返回代码,如果我使用local
运行fabric.tasks.execute
命令而不是多个远程主机,则可以正常工作,例如:execute(self.run,command=task,hosts=self.HOSTS)
以下是类代码的摘录:
def execs(self,task):
with settings(warn_only=True):
if (self.getMode() is "local"):
return self.run(task)
else:
return execute(self.run,command=task,hosts=self.HOSTS)
def run(self,command):
with settings(warn_only=True):
if (self.getMode() is "local"):
return local(command,True)
if self.isSudo():
return sudo(command,pty=False)
return run(command,pty=False)
def dir_exists(self,directory):
'''Check if directory exists'''
if ((self.execs("test -d %s" % (directory))).return_code == 0):
return True
else:
warn("Directory doesnot exists")
return False
def dir_ensure(self,destination = None , user =None,group = None, permissions =None,recursive= False):
'''Ensures a directory is created'''
if (destination is None):
warn("Destination of directory must be specified")
return False
if (self.dir_exists(destination)):
warn("Destination folder already exists; Just setting permissions")
self.dir_setAttr(destination,user,group,permissions,recursive)
else:
self.execs("mkdir -p %s" % (destination))
self.dir_setAttr(destination,user,group,permissions,recursive)
当我运行代码时:
myCooker.dir_ensure("/tmp/tototoot",user="k.sewnundun",group="k.sewnundun",permissions="777",recursive=True)
我收到以下错误:
Traceback (most recent call last):
File "test.py", line 8, in <module>
myCooker.dir_ensure("/tmp/tototoot",user="k.sewnundun",group="k.sewnundun",permissions="777",recursive=True)
File "build/bdist.linux-i686/egg/cooker.py", line 234, in dir_ensure
File "build/bdist.linux-i686/egg/cooker.py", line 210, in dir_exists
AttributeError: 'dict' object has no attribute 'return_code'
但是如果我将方法.exec
和.run
中的dir_ensure
更改为dir_exists
并设置env.host_string
我可以获取远程命令的返回码但是问题是我只能传递一个主机,这不是想要的结果。
我如何使用方法.exec
中的dir_exists
获取返回代码,或者更好的方法?
答案 0 :(得分:2)
注意,fabric
&#39; execute
返回dict
!
来自docs:
返回:将主机字符串映射到给定任务的主机执行运行的返回值的字典。例如,执行(foo,hosts = [&#39; a&#39;,&#39; b&#39;])可能会返回{&#39; a&#39;:无,&#39; b&#39 ;:&#39; bar&#39;}如果foo在主机上没有返回任何内容,但返回了&#39; bar&#39;在主持人b。
因此,您会在result_dict[host].return_code
中找到错误代码。
您还必须返回fabric
run
函数的输出,但是您这样做:return run(command,pty=False)
。没有它,你会在字典中找到None
。
希望它有所帮助。