【问题标题】:What is the most efficient way to escape passed parameters in ssh on a posix compliant shell?在 posix 兼容的 shell 上转义 ssh 中传递的参数的最有效方法是什么?
【发布时间】:2012-01-17 15:20:21
【问题描述】:

有时您想在通过 ssh 将某些内容传递给 shell 之前可靠地转义它。很好奇这个问题看起来有多困难。 :-$

是否有更短或更有效的方式来定义这个函数,所以它可以与任何严格遵守 posix 的 shell 一起工作?

function sshesc () { printf "%s" "$1" | sed -e "s|'|\'\\\\\'\'|g" -e "s|^|'|" -e "s|$|'|"; }

(简单地使用 echo 代替 printf 可能会引入错误。)

【问题讨论】:

    标签: ssh escaping posix dash-shell


    【解决方案1】:

    你会使用 Perl 吗?

    如果您需要经常这样做,Perl 模块 Net::OpenSSH 可以让您的生活更轻松。

    例如:

    #!/usr/bin/perl
    use Net::OpenSSH;
    
    my $ssh = Net::OpenSSH->new('host');
    $ssh->error and die "ssh connection failed: " . $ssh->error;
    
    $ssh->system('ls /*');                      # the remote shell expands '/*'
    
    $ssh->system('echo', '* $how are you! *');  # like calling execvp(3) on the
                                                # remote machine, as if no remote
                                                # shell were involved at all
    

    【讨论】:

    • 我可以要求一切。但我只接受使用 ssh 无处不在的基本工具。
    【解决方案2】:

    据我所知,没有。这是我见过的最短的 shell 引用实现。如果你不想依赖 sed,你可以do it in pure shell,但那样会更冗长(也更慢)。

    据我了解,符合 POSIX 标准的 shell 并非普遍可用(嗨,Solaris!)。如果您愿意将要求提高到 bash 而不是 dash,您可以说:

    sshesc () { printf "%q" "$1" }
    

    (也适用于 zsh!)

    【讨论】:

      【解决方案3】:

      在 Bash 中,您可以:

      $ printf '%q' 'echo "argument with    spaces"'
      

      在 POSIX shell 中,printf%q 未定义。我最近开始使用类似于您的 sed 脚本:

      $ printf '%s' 'echo "argument with    spaces"' | sed -e "s/'/'\\\\''/g" -e "1 s/^/'/" -e "$ s/$/'/"
      

      这个想法是将文本附在'中。然后你只需要逃脱已经存在的'

      我也将其用作可执行文件:

      #!/bin/sed -f
      
      # usage: $0
      
      # make this:
      #
      #     echo "'special   chars'"
      #
      # into this:
      #
      #     'echo "'\''special   chars'\''"'
      #
      
      # escape all '
      s/'/'\\''/g
      
      # enclose in '
      1 s/^/'/
      $ s/$/'/
      

      时间会证明它是否可行。

      我遇到了severalprojects 来解决这个问题,尽管它们中的大多数似乎对我来说太复杂了。这就是我最终自己制作的原因。

      【讨论】:

      • bash-completion 有一个 neat function 来解决这个问题,但它与 POSIX shell 不兼容。
      猜你喜欢
      • 1970-01-01
      • 2019-08-08
      • 1970-01-01
      • 1970-01-01
      • 2011-07-13
      • 1970-01-01
      • 2020-11-02
      • 2015-02-23
      • 1970-01-01
      相关资源
      最近更新 更多