管脚本和二进制数据通过ssh标准输入 [英] Pipe script and binary data to stdin via ssh

查看:150
本文介绍了管脚本和二进制数据通过ssh标准输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要执行一个bash脚本远程消耗压缩包,并执行一些逻辑来了。诀窍是,我想只使用一个SSH命令来做到这一点(而不是 SCP 的压缩包,然后按 SSH 为脚本)。

I want to execute a bash script remotely which consumes a tarball and performs some logic to it. The trick is that I want to use only one ssh command to do it (rather than scp for the tarball followed by ssh for the script).

在bash脚本是这样的:

The bash script looks like this:

cd /tmp
tar -zx
./archive/some_script.sh
rm -r archive

我认识到,我可以简单地格式化这个脚本到一个一行,并使用

I realize that I can simply reformat this script into a one-liner and use

tar -cz ./archive | ssh $HOST bash -c '<commands>'

但我实际的脚本是足够复杂,我必须管它庆典通过标准输入。这里的挑战是, SSH 只提供了一个输入管道(标准输入),我想使用这两个bash脚本和包。

but my actual script is complicated enough that I must pipe it to bash via stdin. The challenge here is that ssh provides only one input pipe (stdin) which I want to use for both the bash script and the tarball.

推荐答案

我想出了两种解决方案,它们都包括bash脚本,并在标准输入压缩包。

I came up with two solutions, both of which include the bash script and the tarball in stdin.

在这种情况下,服务器接收到一个bash脚本的压缩包被嵌入到一个里面定界符:

In this case the server receives a bash script with the tarball is embedded inside a heredoc:

base64 -d <<'EOF_TAR' | tar -zx
<base64_tarball>
EOF_TAR

下面是完整的例子:

ssh $HOST bash -s < <(
# Feed script header
cat <<'EOF'
cd /tmp
base64 -d <<'EOF_TAR' | tar -zx
EOF

# Create local tarball, and pipe base64-encoded version
tar -cz ./archive | base64

# Feed rest of script
cat <<'EOF'
EOF_TAR
./archive/some_script.sh
rm -r archive
EOF
)

在此方法,但焦油不开始解压压缩包,直到它完全通过网络传输。

In this approach however, tar does not start extracting the tarball until it is fully transferred over the network.

在这种情况下,bash脚本被管道输送到标准输入随后的原始压缩包的数据。 庆典将控制权交给焦油它处理标准输入的焦油部分:

In this case the bash script is piped into stdin followed by the raw tarball data. bash passes control to tar which processes the tar portion of stdin:

ssh $HOST bash -s < <(
# Feed script.
cat <<'EOF'
function main() {
  cd /tmp
  tar -zx
  ./archive/some_script.sh
  rm -r archive
}
main
EOF
# Create local tarball and pipe it
tar -cz ./archive
)

不像第一种方法,这一个允许焦油来开始解压压缩包,因为它正在通过网络传输。

Unlike the first approach, this one allows tar to start extracting the tarball as it is being transferred over the network.

(而不是在结尾)在bash脚本的中间把二进制焦油数据会导致错误,因为焦油消耗过去的tar文件的末尾(其中包括一些bash脚本)。因此,功能用于强制整个bash脚本来焦油数据之前。

Putting binary tar data in the middle of the bash script (rather than at the end) causes errors since tar consumes past the end of the tarfile (including some of the bash script). Hence the function main is used to force the whole bash script to come before the tar data.

这篇关于管脚本和二进制数据通过ssh标准输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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