使用Python通过ssh将文件cat到远程bash脚本

2024-09-28 03:16:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我在用子流程.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
$>

我错过了什么?在


Tags: topathtxt脚本bash远程sshtmp
2条回答

问题是您在命令中使用了shell重定向,但是在使用子进程时没有生成shell。在

考虑以下(非常简单)程序:

import sys
print sys.argv

现在,如果我们像运行ssh(假设foofile.txt存在),我们得到:

^{pr2}$

请注意,< foofile.txt永远不会使用python的命令行参数。这是因为bash解析器截获<及其后的文件,并将该文件的内容重定向到程序的stdin。换句话说,ssh正在从stdin读取文件。您也希望使用python将文件传递到sshstdin。在

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是本地计算机上的一个文件。在

为什么不放弃中间人使用Paramiko?在

相关问题 更多 >

    热门问题