ssh + here-document syntax with Python

痞子三分冷 提交于 2019-12-12 02:56:31

问题


I'm trying to run a set of commands through ssh from a Python script. I came upon the here-document concept and thought: cool, let me implement something like this:

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

Unfortunately, here is what I get:

bash: warning: here-document at line 0 delimited by end-of-file (wanted `EOF')

Not sure how I can code up that end-of-file statement (I'm guessing the newline chars get in the way here?)

I've done a search on the website but there seem to be no Python examples of this sort...


回答1:


Here is a minimum working example,the key is that after << EOF the remaining string should not be split. Note that command.split() is only called once.

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

Verify by checking that the created file test.txt shows up in the Downloads directory on the host that you ssh:ed into.

Kind regards,
Filip



来源:https://stackoverflow.com/questions/35344870/ssh-here-document-syntax-with-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!