我试图通过Python脚本通过ssh运行一组命令。我想到了here-document的概念和想法:酷,让我实现这样的东西:
command = ( ( 'ssh user@host /usr/bin/bash <<EOF\n'
+ 'cd %s \n'
+ 'qsub %s\n'
+ 'EOF' ) % (test_dir, jobfile) )
try:
p = subprocess.Popen( command.split(), stdout=subprocess.PIPE, stderr=subprocess.STDOUT )
except :
print ('from subprocess.Popen( %s )' % command.split() )
raise Exception
#endtry不幸的是,我得到的是:
bash: warning: here-document at line 0 delimited by end-of-file (wanted `EOF')我不知道如何对文件末尾的语句进行编码(我猜换行符会妨碍到这里吗?)
我在网站上做过搜索,但似乎没有这类Python的例子.
发布于 2016-02-12 09:02:54
下面是一个最小的工作示例,关键是在<< EOF之后,剩余的字符串不应该被拆分。注意,command.split()只被调用一次。
import subprocess
# My bash is at /user/local/bin/bash, your mileage may vary.
command = 'ssh user@host /usr/local/bin/bash'
heredoc = ('<< EOF \n'
'cd Downloads \n'
'touch test.txt \n'
'EOF')
command = command.split()
command.append(heredoc)
print command
try:
p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
except Exception as e:
print e通过检查所创建的文件test.txt是否显示在ssh:ed进入的主机上的下载目录进行验证。
https://stackoverflow.com/questions/35344870
复制相似问题