【发布时间】:2015-03-12 10:44:21
【问题描述】:
我有几台 Unix 服务器,上面运行着一个应用程序,我需要从应用程序日志中对每台服务器上的一些模式进行 grep,并将所有服务器的 grep 结果放入一个统一文件中。
这就是我目前的做法。
def run_command(command):
ps = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE,shell=True)
out,err = ps.communicate()
if err != "":
return err
else:
return out
Server_List = [['ServerA','BecomeAccountA'],['ServerB','BecomeAccountB'],['ServerC','BecomeAccountC'],['ServerD','BecomeAccountD']]
Final_Result = ""
path = "some/path/"
pattern = "FindMe"
for list in Server_List:
server= list[0]
becomeaccount = list[1]
command="ssh -oConnectTimeout=5 -oBatchMode=yes -l %s %s 'grep %s %s'" % (becomeaccount,server,pattern,path)
result = run_command(command)
Final_Result+=result
with open("/some/path/output",'w') as f:
f.write(Final_Result)
现在我的output 文件包含以下内容:
14012015.1449.30 [INFO] something FindMe something
14012015.1449.40 [INFO] something FindMe something
14012015.1450.13 [INFO] something FindMe something
14012015.1450.48 [INFO] something FindMe something
14012015.1451.04 [INFO] something FindMe something
14012015.1451.19 [INFO] something FindMe something
14012015.1451.77 [INFO] something FindMe something
14012015.1452.09 [INFO] something FindMe something
要在output 文件中得到这个结果,我必须一个接一个地与所有服务器建立 ssh 连接,这需要一些时间来处理。我需要减少代码花费的时间才能获得最终输出。我想知道我可以在多线程中做到这一点吗?我的意思是一次建立多个 ssh 连接?我从未尝试过多线程。
注意:- output 文件中的行顺序并不重要,因此 ssh 连接的顺序也不是必需的,因为我总是可以对 output 文件中的行进行排序时间,因为它在每行的开头都有时间戳。
【问题讨论】:
-
听起来你正在做的事情可能是 io-bound,所以多线程听起来可能会有所帮助。但是,它可能完成的只是允许您并行等待所有服务器。
-
不相关:您可以使用退出状态
ps.returncode != 0作为错误指示器。如果要检查字符串err是否不为空,请使用if err而不是if err != ""(后者在 Python 3 上失败,其中bytes和str是不同的类型)并且它在 Python 上不是惯用的2个。
标签: python multithreading ssh subprocess