我正在尝试通过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示例...
这是一个最小的工作示例,关键是在<< 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:所在的主机的Downloads目录中。