我正在使用shlex使用subprocess.popen來使用ssh調用遠程bash腳本。這個命令在bash本身上工作得很好。但只要我嘗試用subprocess.popen將它翻譯成python和shlex,它就會錯誤地出現。使用Python通過ssh將文件捕獲到遠程bash腳本
遠程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
$>
我在想什麼?
爲什麼你的python腳本在參數列表中有一個額外的''<'',看起來不存在於bash腳本中? (或者我讀錯了嗎?) – mgilson
我錯過了,錯字。我通過將<放在bash命令行中來糾正它。 – Chris
本地或遠程系統上是否有/ 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問題。) – Blckknght