我正在使用带有 shlex 的 subprocess.popen 来使用 ssh 调用远程 bash 脚本。该命令在 bash 本身上运行良好。但是,一旦我尝试使用 subprocess.popen 将其转换为 python 和 shlex,它就会出错。
远程 bash 脚本:
#!/bin/bash
tmp="";
while read -r line;
do
tmp="$tmp $line\n";
done;
echo $tmp;
BASH CMD 结果(在命令行调用远程 bash 脚本)
$> ssh x.x.x.x cat < /tmp/bef69a1d-e580-5780-8963-6a9b950e529f.txt " | /path/to/bash/script.sh;"
Bar\n
$>
Python代码
import shlex
import subprocess
fn = '/tmp/bef69a1d-e580-5780-8963-6a9b950e529f.txt'
s = """
ssh x.x.x.x cat < {localfile} '| /path/to/bash/script.sh;'
""".format(localfile=fn)
print s
lexer = shlex.shlex(s)
lexer.quotes = "'"
lexer.whitespace_split = True
sbash = list(lexer)
print sbash
# print buildCmd
proc=subprocess.Popen(sbash,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
out,err=proc.communicate()
print "Out: " + out
print "Err: " + err
Python脚本结果:
$> python rt.py
ssh x.x.x.x cat < /tmp/bef69a1d-e580-5780-8963-6a9b950e529f.txt '| /path/to/bash/script.sh'
['ssh', 'x.x.x.x', 'cat', '<', '/tmp/bef69a1d-e580-5780-8963-6a9b950e529f.txt', "'| /path/to/bash/script.sh'"]
Out:
Err: bash: /tmp/bef69a1d-e580-5780-8963-6a9b950e529f.txt: No such file or directory
$>
我错过了什么?