如何将任意参数传递给通过SSH执行的命令? [英] How do I pass arbitrary arguments to a command executed over SSH?

查看:58
本文介绍了如何将任意参数传递给通过SSH执行的命令?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个脚本,其内容位于远程服务器 example.com 上的〜/echo.sh 中:

Assume I have a script with the following contents located at ~/echo.sh on a remote server example.com:

#!/usr/bin/env bash
echo "Arg 1: $1"
echo "Arg 2: $2"
echo "Arg 3: $3"
echo "Arg 4: $4"

现在,在我的本地计算机上,我还有另一个脚本 remote-echo.sh ,其内容如下:

Now, on my local machine, I have another script, remote-echo.sh with the following contents:

#!/usr/bin/env bash
ssh example.com "~/echo.sh $*"

这个想法是,用户应该能够使用任何参数运行 remote-echo.sh ,并将这些参数转发到计算机上的〜/echo.sh 上.远程服务器.

The idea is that a user should be able to run remote-echo.sh with any arguments and have those arguments be forwarded to ~/echo.sh on the remote server.

不幸的是,这不起作用:

Unfortunately, this doesn't work:

$ ./remote-echo.sh "arg with space" "argwith\"quote" "arg3"
bash: -c: line 0: unexpected EOF while looking for matching `"'
bash: -c: line 1: syntax error: unexpected end of file

我该如何解决?我已经尝试使用 $ @ 代替 $ * ,但这对结果没有任何影响.

How do I fix this? I already tried using $@ instead of $*, but that didn't have any effect on the result at all.

推荐答案

您需要确保正确地转义传递给SSH的字符串中嵌入的所有参数,以便不会被远程服务器上的Shell解释..最简单的方法是在Bash中为 printf 使用%q 格式字符:

You need to ensure that all arguments embedded in the string passed to SSH are being properly escaped, so they don't get interpreted by the shell on the remote server. The simplest way to do this is using the %q format character for printf in Bash:

#!/usr/bin/env bash
ssh example.com "~/echo.sh $(printf "%q " "$@")"

根据Bash中printf的 help 信息:

According to the help information for printf in Bash:

除了printf(1)中描述的标准格式规范外,printf还会解释:

In addition to the standard format specifications described in printf(1), printf interprets:

[...]

%q以可以作为shell输入重用的方式引用参数

%q quote the argument in a way that can be reused as shell input

这应该可以解决您在此处看到的问题,并确保将每个参数正确传递给 echo.sh .

That should resolve the issue you see here, and ensure each argument is passed correctly to echo.sh.

这篇关于如何将任意参数传递给通过SSH执行的命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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