我写了一个bash脚本foo.sh
#!/usr/bin/env bash
echo "starting the script";
Run Code Online (Sandbox Code Playgroud)
我想在我的远程服务器上执行它.我试过ssh user@remote-addr < test.sh,它有效.
之后我改变了test.sh文件
#!/usr/bin/env bash
echo "starting the script";
echo $1;
Run Code Online (Sandbox Code Playgroud)
现在我想传递一个本地参数来执行我的脚本但是当我输入ssh user@remote-addr < test.sh testparam它时返回一个错误.
如何用脚本传递参数?
bash或ksh为/bin/sh如果你的遥控器/bin/sh是由bash或ksh提供的,你可以使用不受信任的参数列表安全地执行以下操作,这样即使是恶意名称(例如$(rm -rf $HOME).txt)也可以安全地作为参数传递:
runRemote() {
local args script
script=$1; shift
# generate eval-safe quoted version of current argument list
printf -v args '%q ' "$@"
# pass that through on the command line to bash -s
# note that $args is parsed remotely by /bin/sh, not by bash!
ssh user@remote-addr "bash -s -- $args" < "$script"
}
Run Code Online (Sandbox Code Playgroud)
此后...:
runRemote test.sh testparam
Run Code Online (Sandbox Code Playgroud)
/bin/sh请注意,仍然需要运行以下内容bash,但只要远程计算机安装了bash,当进入的系统ssh具有/bin/shPOSIX-baseline 时,它将正常工作.
为了防止充分恶意的参数数据(试图利用printf %qbash中使用的非POSIX兼容引用,当被转义的字符串中存在非打印字符时),即使/bin/sh是base-POSIX(例如dash或ash),它也是如此变得更有趣:
runRemote() {
local script=$1; shift
local args
printf -v args '%q ' "$@"
ssh user@remote-addr "bash -s" <<EOF
# pass quoted arguments through for parsing by remote bash
set -- $args
# substitute literal script text into heredoc
$(< "$script")
EOF
}
Run Code Online (Sandbox Code Playgroud)
类似地调用为:
runRemote test.sh testparam
Run Code Online (Sandbox Code Playgroud)
使用该-s选项,强制bash(或任何 POSIX 兼容 shell)从标准输入读取其命令,而不是从第一个位置参数命名的文件中读取命令。所有参数都被视为脚本的参数。
ssh user@remote-addr 'bash -s arg' < test.sh
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6644 次 |
| 最近记录: |