我有一个脚本,它使用两台不同的机器运行测试用例。测试需要在机器2上运行命令之前在机器1上运行一些命令,然后机器1向机器2发送数据。目标是能够从两台机器上运行测试,所以我想我会在机器1上运行ssh并在那里执行命令,然后ssh到机器2并在那里执行命令.我试图避免paramiko,因为我不想要额外的依赖,所以我找到了一段很好的代码,它可以完成任务:
def executeRemoteCommand(host, command):
ssh = subprocess.Popen(["ssh", "%s" % host, command],
shell=False,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
以下是我所做工作的一个例子:
executeRemoteCommand(user@machine1, "cd /dcd-netapp1/test/test-priority_v6; ./prerun")
time.sleep(30)
executeRemoteCommand(user@machine2, "cd /dcd-netapp1/test/test-priority-v6; ./run")
time.sleep(1800)
executeRemoteCommand(user@machine1, "cd /dcd-netapp1/test/test-priority-v6; ./postrun")
executeRemoteCommand(user@machine2, "cd /dcd-netapp1/test/test-priority-v6; ./graph_results")
问题是我的prerun
ssh会话没有被关闭。postrun
脚本负责杀死用prerun
脚本启动的日志脚本,但是正如我所说的,当我查看使用ps -ef | grep ssh
运行的所有进程时,ssh会话在测试结束后就会显示出来。
关于一些其他信息,我以前在executeRemoteCommand
函数中有以下代码:
result = ssh.stdout.readlines()
if result == []:
error = ssh.stderr.readlines()
print >>sys.stderr, "ERROR: %s" % error
else:
print result
我将其注释掉,因为prerun
脚本将挂起等待std输出的结果。这种事永远不会发生。我的prerun
脚本确实有std输出,但我想它无法收集它,因为它可能是一种守护进程?我对prerun
脚本不太了解。
发布于 2015-11-24 23:51:26
移除管道对我的方案是有效的。现在,我从我开始测试的机器上得到所有来自远程机器的输出,所有的输出都优雅地关闭。顺便说一下,我发现shell=False
在默认情况下是假的,因此它是不必要的,%s % host
字符串替换也是不必要的。下面是与我的问题相关的内容:
def executeRemoteCommand(host, command):
ssh = subprocess.Popen(["ssh", host, command])
由于这个函数现在已经超级简化了,所以我更进一步,认为如果我完全去掉这个函数并直接使用Popen
,那么这个测试就更容易阅读了:
subprocess.Popen(["ssh", user@machine1, "cd /dcd-netapp1/test/test-priority-v6; ./prerun"])
time.sleep(5)
subprocess.Popen(["ssh", user@machine2, "cd /dcd-netapp1/test/test-priority-v6; ./run"])
time.sleep(1800)
subprocess.Popen(["ssh", user@machine1, "cd /dcd-netapp1/test/test-priority-v6; ./postrun"])
subprocess.Popen(["ssh", user@machine1, "cd /dcd-netapp1/test/test-priority-v6; ./graph_results"])
https://stackoverflow.com/questions/33883619
复制相似问题