ssh - 在 posix 兼容的 shell 上转义 ssh 中传递的参数的最有效方法是什么?

标签 ssh escaping posix dash-shell

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

是否有一种更短或更有效的方法来定义这个函数,所以它可以与任何严格符合 posix 的 shell 一起使用?

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

(简单地使用 echo 而不是 printf 可能会引入错误。)

最佳答案

你会用 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 - 在 posix 兼容的 shell 上转义 ssh 中传递的参数的最有效方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8460630/

相关文章:

regex - 如何忽略存储在PowerShell字符串变量中的转义序列?

jQuery 选择器值转义

c++ - OpenMP 和 CPU 亲和性

Git 完全重置。删除所有文件。删除历史记录

linux - 如何在这里实现设置 ssh 隧道到端口...?

PHP:JSON 中的正则表达式导致 json_decode 出现问题?

c - 为什么 fwrite 为 uint8_t 写入两个字节?

c - 防止陷入阻塞调用

linux - Bash:使用 SSH 启动长时间运行的远程命令并收集其 PID

r - R ssh 包中的 ssh ipv6 地址