【问题标题】:How to pass parameters with quotes via ssh如何通过 ssh 传递带引号的参数
【发布时间】:2018-07-24 14:35:38
【问题描述】:

当我在我的 Linux 服务器中运行如下脚本时:

./myscript \"hello\"

然后脚本接收参数为“hello”。现在,我希望能够通过 ssh 从不同的主机远程运行这个脚本。如果 ssh 连接是 Linux 到 Linux,则以下工作:

ssh remote-host ./myscript \\\"hello\\\"

但是,如果您的 ssh 连接是 Windows 10 到 Linux。以上不起作用,远程脚本接收参数为 \hello"--注意多余的反斜杠和缺少双引号。我尝试了以下方法,但都没有:

ssh remote-host ./myscript \\\"hello\\\"
ssh remote-host ./myscript ^"hello^"
ssh remote-host ./myscript ""hello""
ssh remote-host ./myscript '"hello"'

我能想到的唯一解决方法是创建另一个 shell 脚本,其中包含:

./myscript \"hello\"

然后将此脚本 scp 到远程 Linux 服务器并在那里执行。那么,有没有办法让我正确引用我的论点?

【问题讨论】:

  • 我没有要测试的 Windows 机器,但 ssh remote-host './myscript \"hello\"' 有效吗?知道ssh 只是要加入它的参数以传递给远程主机上的sh -c,我发现首先只传递一个字符串更简单。
  • 如果^ 是转义字符,^\"hello^\"'\"hello\"' 之一是否有效?
  • 目标是确保远程端运行类似于sh -c './myscript \"hello\"'

标签: ssh cmd quotes


【解决方案1】:

您可以使用以下方便的包装脚本ssh.sh

cat <<'EOF' > ssh.sh
#!/bin/bash

function escape() {
  for arg in "$@"; do
    printf "%q " "$arg"
  done
}

ssh $(escape "$@")
EOF

chmod +x ssh.sh

然后你就可以安全地通过ssh.sh调用ssh了,不用担心逃跑。

例如,

./ssh.sh host sh -c 'ls /'

与标准 ssh 相比,

ssh host sh -c 'ls /'

不行,需要转换成

ssh host sh -c \'ls /\'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-11-21
    • 2015-10-29
    • 1970-01-01
    • 2021-09-20
    • 2012-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多