在本地机器上从远程服务器执行 shell 脚本

Goo*_*bot 5 shell ssh remote shell-script

将远程服务器上的 shell 脚本想象为

#!/bin/bash
rm /test.x
Run Code Online (Sandbox Code Playgroud)

我如何(如果可能)从本地计算机执行此脚本以删除本地计算机上的/test.x文件。显然,解决方案应该是ssh授权之类的,但不要从远程服务器下载脚本文件。

事实上,我想使用远程脚本作为在本地机器上运行的 shell 命令的提供者。

Sté*_*las 11

您需要以某种方式下载脚本的内容。你可以做

ssh remote-host cat script.bash | bash
Run Code Online (Sandbox Code Playgroud)

但这会产生与以下相同的问题:

cat script.bash | bash
Run Code Online (Sandbox Code Playgroud)

即脚本中的 stdin 将是脚本本身(如果脚本中的命令需要从用户那里获得一些输入,这可能是一个问题)。

然后,一个更好的选择(但你需要一个支持进程替换的 shell,如 ksh、zsh 或 bash)是:

bash <(ssh remote-host cat script.bash)
Run Code Online (Sandbox Code Playgroud)

这两种方法都会下载脚本,因为它们会检索其内容,但不会将其存储在本地。而是将内容馈送到管道的另一端由 读取和解释bash

您还可以使用以下命令在当前 bash 进程中执行远程脚本的内容:

eval "$(ssh remote-host cat script.bash)"
Run Code Online (Sandbox Code Playgroud)

但这会在运行之前完全下载脚本(并将其存储在内存中)。

显而易见的解决方案是:

. <(ssh remote-host cat script.bash)
Run Code Online (Sandbox Code Playgroud)

但请注意,某些版本的 bash 存在此问题。