Skip to content Skip to sidebar Skip to footer

Ssh + Here-document Syntax With Python

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 = ( ( '

Solution 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)
printcommand

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.

Post a Comment for "Ssh + Here-document Syntax With Python"