通过函数调用引用 ssh 命令
Quoting with ssh command with a function call
我需要执行shell命令如下:
ssh <device> "command"
命令被调用为:
$(typeset); <function_name> \"arguement_string\"; cd ...; ls ...
这里具体怎么引用?这是正确的吗?
""$(typeset); <function_name> \"arguement_string\""; cd ...; ls ..."
我对 shell 脚本中的这个引用感到困惑。
我会使用 here document:
ssh machine <<'EOF'
hello() {
echo "hello !"
}
hello "world"
EOF
请注意,我将开头的 EOF
括在单引号中。这样做可以防止 bash 解释本地 shell.
中的变量或命令替换
不要尝试手动引用 - 请 shell 为您完成!
command_array=( function_name "first argument" "second argument" )
printf -v command_str '%q ' "${command_array[@]}"
ssh_str="$(typeset); $command_str"
ssh machine "$ssh_str"
然后您可以根据需要构建 command_array
- 使用逻辑有条件地附加值,仅使用您通常引用的那种引用来引用这些值,然后让 printf %q
添加使内容安全地通过 ssh 传递所需的所有附加引号。
如果您尝试逐步构建脚本,您可以这样做:
remote_script="$(typeset)"$'\n'
safe_append_command() {
local command_str
printf -v command_str '%q ' "$@"
remote_script+="$command_str"$'\n'
}
safe_append_command cp "$file" "$destination"
safe_append_command tar -cf /tmp/foo.tar "${destination%/*}"
# ...etc...
ssh machine "$remote_script"
请注意,在这种情况下,所有扩展都发生在 本地,当生成脚本时,shell 不能使用诸如重定向运算符的构造(除了通过将它们嵌入到函数中,然后使用 typeset
) 传递给远程系统。这样做意味着传递给 safe_append_command
的任何数据都不能被视为代码——以牺牲灵活性为代价排除大量 类 潜在的安全漏洞。
我需要执行shell命令如下:
ssh <device> "command"
命令被调用为:
$(typeset); <function_name> \"arguement_string\"; cd ...; ls ...
这里具体怎么引用?这是正确的吗?
""$(typeset); <function_name> \"arguement_string\""; cd ...; ls ..."
我对 shell 脚本中的这个引用感到困惑。
我会使用 here document:
ssh machine <<'EOF'
hello() {
echo "hello !"
}
hello "world"
EOF
请注意,我将开头的 EOF
括在单引号中。这样做可以防止 bash 解释本地 shell.
不要尝试手动引用 - 请 shell 为您完成!
command_array=( function_name "first argument" "second argument" )
printf -v command_str '%q ' "${command_array[@]}"
ssh_str="$(typeset); $command_str"
ssh machine "$ssh_str"
然后您可以根据需要构建 command_array
- 使用逻辑有条件地附加值,仅使用您通常引用的那种引用来引用这些值,然后让 printf %q
添加使内容安全地通过 ssh 传递所需的所有附加引号。
如果您尝试逐步构建脚本,您可以这样做:
remote_script="$(typeset)"$'\n'
safe_append_command() {
local command_str
printf -v command_str '%q ' "$@"
remote_script+="$command_str"$'\n'
}
safe_append_command cp "$file" "$destination"
safe_append_command tar -cf /tmp/foo.tar "${destination%/*}"
# ...etc...
ssh machine "$remote_script"
请注意,在这种情况下,所有扩展都发生在 本地,当生成脚本时,shell 不能使用诸如重定向运算符的构造(除了通过将它们嵌入到函数中,然后使用 typeset
) 传递给远程系统。这样做意味着传递给 safe_append_command
的任何数据都不能被视为代码——以牺牲灵活性为代价排除大量 类 潜在的安全漏洞。