【问题标题】:ssh + here-document syntax with Pythonssh + here-document 语法与 Python
【发布时间】:2016-05-22 13:20:45
【问题描述】:

我正在尝试通过 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 示例...

【问题讨论】:

  • 你不是在&lt;&lt;EOF之后错过了\n吗?
  • 我已经更改了代码(如 OP 所示),但仍然无法正常工作(同样的错误)

标签: python shell ssh heredoc


【解决方案1】:

这是一个最小的工作示例,关键是在&lt;&lt; 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 进入的主机上的下载目录中进行验证。

【讨论】:

    猜你喜欢
    • 2020-09-30
    • 2015-12-08
    • 2012-09-20
    • 2018-07-22
    • 2016-12-22
    • 2016-12-08
    • 1970-01-01
    • 2011-06-14
    • 1970-01-01
    相关资源
    最近更新 更多