ssh + here-document 语法 Python
ssh + here-document syntax with Python
我正尝试从 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:ed 进入的主机上的下载目录中进行验证。
我正尝试从 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:ed 进入的主机上的下载目录中进行验证。