我使用subprocess.popen和shlex来使用ssh调用远程bash脚本。这个命令在bash本身上运行得很好。但是,只要我尝试用subprocess.popen将其翻译成python和shlex,它就会出错。
远程bash脚本:
#!/bin/bash
tmp="";
while read -r line;
do
tmp="$tmp $line\n";
done;
echo $tmp;BASH结果(在命令行上调用远程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
$>我遗漏了什么?
发布于 2012-11-07 19:51:40
问题是在命令中使用shell重定向,但是在使用子进程时没有生成shell。
考虑以下(非常简单)程序:
import sys
print sys.argv现在,如果我们像运行ssh一样运行它(假设foofile.txt存在),我们将得到:
python argcheck.py ssh cat < foofile.txt " | /path/to/bash/script.sh;"
['argcheck.py', 'ssh', 'cat', ' | /path/to/bash/script.sh;']请注意,< foofile.txt从未将其用于python的命令行参数。这是因为bash解析器拦截<及其后面的文件,并将该文件的内容重定向到程序的stdin。换句话说,ssh正在从stdin读取文件。您也希望使用python将您的文件传递给stdin of ssh。
s = """
ssh x.x.x.x cat '| /path/to/bash/script.sh;'
"""
#<snip>
proc=subprocess.Popen(sbash,stdout=subprocess.PIPE,stderr=subprocess.PIPE,
stdin=subprocess.PIPE)
out,err=proc.communicate(open(fn).read())大概会起作用。
以下几点对我来说是可行的:
import subprocess
from subprocess import PIPE
with open('foo.h') as f:
p = subprocess.Popen(['ssh','mgilson@XXXXX','cat','| cat'],stdin=f,stdout=PIPE,stderr=PIPE)
out,err = p.communicate()
print out
print '#'*80
print err和bash中的等效命令
ssh mgilson@XXXXX cat < foo.h '| cat'其中foo.h是本地机器上的一个文件。
https://stackoverflow.com/questions/13276755
复制相似问题