我在用子流程.popen使用shlex使用ssh调用远程bash脚本。这个命令在bash本身上运行得很好。但是当我试图用子流程.popen它错了。在
远程bash脚本:
#!/bin/bash
tmp="";
while read -r line;
do
tmp="$tmp $line\n";
done;
echo $tmp;
BASH CMD RESULT(在命令行调用远程BASH脚本)
^{pr2}$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
$>
我错过了什么?在
问题是您在命令中使用了shell重定向,但是在使用子进程时没有生成shell。在
考虑以下(非常简单)程序:
现在,如果我们像运行
^{pr2}$ssh
(假设foofile.txt
存在),我们得到:请注意,
< foofile.txt
永远不会使用python的命令行参数。这是因为bash解析器截获<
及其后的文件,并将该文件的内容重定向到程序的stdin。换句话说,ssh
正在从stdin读取文件。您也希望使用python将文件传递到ssh
的stdin
。在大概能起作用。在
以下是我的工作:
以及
bash
中的等效命令:其中
foo.h
是本地计算机上的一个文件。在为什么不放弃中间人使用Paramiko?在
相关问题 更多 >
编程相关推荐