我将使用subprocess.popen和shlex来调用远程bash脚本,使用ssh进行连接。在bash中,这个命令可以正常运行。但是一旦我尝试将其转换为Python并使用shlex与subprocess.popen一起使用时,它会出错。
远程bash脚本:
#!/bin/bash
tmp="";
while read -r line;
do
tmp="$tmp $line\n";
done;
echo $tmp;
BASH CMD RESULT(在命令行上调用远程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
$>
我错过了什么?
/tmp/bef69a1d-e580-5780-8963-6a9b950e529f.txt
文件是在本地还是远程系统上?如果是本地的话,我认为我会以不同的方式运行你的命令,如cat /tmp/bef69a1d-e580-5780-8963-6a9b950e529f.txt | ssh x.x.x.x /path/to/bash/script.sh
。无需在远程端运行cat
。(我不确定这是否能解决你的Python问题。) - Blckknghtssh x.x.x.x /path/to/bash/script.sh < /tmp/bef...
与您上面写的语句是等效的。 - mgilson