有没有办法通过将其汇总到fabric中的远程shell的标准输入来执行多行shell脚本?或者我必须始终将其写入远程文件系统,然后运行它,然后删除它?我喜欢发送到stdin,因为它避免了临时文件。如果没有结构API(似乎没有基于我的研究),大概我可以直接使用ssh
模块。基本上我希望fabric.api.run
不仅限于作为命令行参数传递给shell的1行命令,而是采用完整的多行脚本并将其写入远程shell的标准输入。 / p>
澄清我想要这个命令行的结构等效:
ssh somehost /bin/sh < /tmp/test.sh
除了python之外,脚本源coude不会来自本地文件系统上的文件,它只是内存中的多行字符串。请注意,这是一个逻辑操作,远程端没有临时文件,这意味着意外故障和崩溃不会留下孤立文件。如果在结构中有这样的选项(这就是我要问的问题),那么任何一方都不需要一个临时文件,这只需要一个ssh操作。
答案 0 :(得分:4)
您可以使用Fabric操作。您可以使用
fabric.operations.put(local_path, remote_path, use_sudo=False,mirror_local_mode=False,mode=None)
将脚本文件复制到远程路径,然后执行它。
,或者
你可以使用fabric.operations.open_shell
,但这只适用于一系列简单的命令,对于涉及逻辑流的脚本,最好使用put操作并像在本地服务器上一样执行脚本。 / p>
答案 1 :(得分:3)
如果脚本在文件中,您可以阅读它,然后将其内容传递给run
。重写Jasper的例子:
from fabric.api import run
script_file = open('myscript.sh')
run(script_file.read())
script_file.close()
答案 2 :(得分:2)
对于它的价值,这完全没问题。它使用python的多行字符串表示法'''
和bash的换行符(换行符之前的\
)。您可以使用分号分隔独立行或仅使用&&
run('''echo hello;\
echo testing;\
echo is this thing on?;''')
run('''echo hello && \
echo testing && \
echo is this thing on?''')
这是我得到的输出:
[root@192.168.59.103:49300] run: echo hello; echo testing; echo is this thing on?;
[root@192.168.59.103:49300] out: hello
[root@192.168.59.103:49300] out: testing
[root@192.168.59.103:49300] out: is this thing on?
[root@192.168.59.103:49300] out:
[root@192.168.59.103:49300] run: echo hello && echo testing && echo is this thing on?
[root@192.168.59.103:49300] out: hello
[root@192.168.59.103:49300] out: testing
[root@192.168.59.103:49300] out: is this thing on?
[root@192.168.59.103:49300] out: