使用ssh命令和函数调用进行报价 [英] Quoting with ssh command with a function call

查看:48
本文介绍了使用ssh命令和函数调用进行报价的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要执行以下shell命令:

I need to execute the shell command as follows:

ssh <device> "command"

命令的调用方式为:

$(typeset); <function_name> \"arguement_string\"; cd ...; ls ... 

在此如何精确引用?这是正确的吗?

How exactly to quote here? Is this correct?

""$(typeset); <function_name> \"arguement_string\""; cd ...; ls ..."

我对shell脚本中的这种引用感到困惑.

I am confused with this quoting in shell scripts.

推荐答案

不要尝试手工进行报价-要求shell为您完成报价!

Don't try to do the quoting by hand -- ask the shell to do it for you!

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.

You can then build up command_array as you wish -- using logic to conditionally append values, with only the kind of quoting you'd usually refer to use to those values, and let printf %q add all additional quoting needed to make the content safe to pass through ssh.

如果您尝试逐步构建脚本,则可以这样做:

If you're trying to incrementally build up a script, you can do that like so:

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 的数据视为代码,以牺牲灵活性为代价来避免大量潜在的安全漏洞.

Note that in this case, all expansions take place locally, when the script is being generated, and shell constructs such as redirection operators cannot be used (except by embedding them in a function you then pass to the remote system with typeset). Doing so means that no data passed to safe_append_command can be treated as code -- foreclosing large classes of potential security holes at the cost of flexibility.

这篇关于使用ssh命令和函数调用进行报价的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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