使用subprocess通过ssh执行命令
我需要通过SSH连接到服务器,执行一些命令,然后用subprocess处理返回的结果。这是我的代码:
command = 'ssh -t -t buildMachine.X.lan; sudo su - buildbot ; build-set sets/set123'
print "submitting command"
result = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE)
print "got response"
response,err = result.communicate()
print response
这个代码运行时卡住了。我看到其他讨论提到要把列表传给subprocess,而不是字符串,并且要去掉shell=True。我也试过这样做,但还是不行。
最后,我需要最后一个命令的结果,也就是build-set,以便从中提取一些信息……谁能帮帮我?
1 个回答
1
我通过univerio的评论找到了解决办法。
这个命令应该是:
command = 'ssh -t -t buildMachine.X.lan \'sudo su - buildbot \'build-set sets/set123\'\''
每个单独的命令就像是前一个命令的参数。这样做是有效的。