Node.js 通过ssh在节点中转义bash变量

Node.js 通过ssh在节点中转义bash变量,node.js,bash,ssh,Node.js,Bash,Ssh,在节点中执行bash命令并传递动态参数时,标准方法是使用spawn并避免转义。即: const filename = 'file with spaces' spawn('ls', [filename]) // All good, received 'file with spaces' 这是万无一失的,因为filename是作为独立变量传递给bash的 现在,如果我想通过ssh做同样的事情,会发生什么?以下是而不是选项: const filename = 'file with spaces' s

在节点中执行bash命令并传递动态参数时,标准方法是使用spawn并避免转义。即:

const filename = 'file with spaces'
spawn('ls', [filename]) // All good, received 'file with spaces'
这是万无一失的,因为filename是作为独立变量传递给bash的

现在,如果我想通过ssh做同样的事情,会发生什么?以下是而不是选项:

const filename = 'file with spaces'
spawn('ssh', [host, 'ls', filename]) // Wrong!! Received 'file' 'with' 'spaces'

Ssh正在接受ls和filename作为vargars。加入它并执行,这就违背了目的。

一种方法是使用具有预期字符的base64传递值,然后在bash中转义

spawn('ssh', [host, 'ls', `"$(echo ${btoa(filename)} | base64 -d)"`])

我认为您可能需要使用空格来转义单引号,例如
filename='\'文件\'''
No,这不好。这在很大程度上取决于输入,即动态处理单个字符串(适当构造)是您唯一的实际选择
ssh
只是将其参数简单地合并成一个字符串,以便在远程主机上与
$SHELL-c
一起使用。创建一个函数
quote_me(string)
,在输入周围加上单引号,然后尝试
spawn('ssh',[host,'ls',quote_me(filename)])
@WalterA转义字符非常棘手,在某些情况下它总是不起作用。例如,在您的示例中,文件名可能在名称中有引号
btoa
如果节点中没有自定义函数或模块,则无法工作,但您可以使用
Buffer.from(filename).toString(“base64”)
来完成任务。