使用 Python 的 ssh + here-document 语法 [英] ssh + here-document syntax with Python

查看:34
本文介绍了使用 Python 的 ssh + here-document 语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从 Python 脚本通过 ssh 运行一组命令.我想到了 here-document 概念并想:很酷,让我实现这样的东西:

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?)

我在网站上进行了搜索,但似乎没有此类 Python 示例...

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

推荐答案

这里是一个最小的工作示例,关键是<< 剩余的字符串不应被拆分.注意 command.split() 只调用一次.

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

通过检查创建的文件 test.txt 是否显示在您 ssh:ed 的主机上的下载目录中进行验证.

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

这篇关于使用 Python 的 ssh + here-document 语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆