ssh + here-document syntax with Python

2019-09-03 10:06发布

问题:

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