在nodejs中生成一个带参数空格的unix命令 [英] Spawn in nodejs for a unix command with spaces in parameters
问题描述
我想在Debian系统上使用Spawn的nodejs执行以下命令:
/usr/bin/apt-get upgrade -s | tail -1 | cut -f1 -d' '
我想使用spawn而不是exec,因为将来会使用仅root命令,并且我不想允许完整的shell访问(我会使用正确的命令更新visudo文件)
这是我的代码
I would like to execute the following command using nodejs Spawn on a Debian system :
/usr/bin/apt-get upgrade -s | tail -1 | cut -f1 -d' '
I want to use spawn and not exec because of future use of root only commands and i don't want to allow a full shell access (i will update the visudo file with correct commands)
Here is my code
const apt = spawn('/usr/bin/apt-get', ['upgrade', '-s']);
const tail = spawn('tail', ['-1']);
const cut = spawn('cut', ['-f1', '-d" "']);
apt.stdout.on('data', (data) => {
tail.stdin.write(data);
});
tail.stdout.on('data', (data) => {
cut.stdin.write(data);
});
cut.stdout.on('data', (data) => {
console.log(data.toString());
});
apt.stderr.on('data', (data) => {
console.log("apt stderr: ${data}");
});
tail.stderr.on('data', (data) => {
console.log("tail stderr: ${data}");
});
cut.stderr.on('data', (data) => {
console.log("cut stderr: ${data}");
});
apt.on('close', (code) => {
if (code !== 0) {
console.log("apt process exited with code ${code}");
}
});
tail.on('close', (code) => {
if (code !== 0) {
console.log("tail process exited with code ${code}");
}
});
cut.on('close', (code) => {
if (code !== 0) {
console.log("cut process exited with code ${code}");
}
});
res.status(200).json('');
一旦执行,由于无法识别'-d"'参数,我将出现错误.我尝试使用双\来转义空格,或者在两个参数中均分割参数,但仍然出错
Once executed i have an error because of the '-d" "' parameter that is not recognized. I try escaping the space with a double \ or split the parameter in both but still errors
推荐答案
应为:
const cut = spawn('cut', ['-f1', '-d ']);
没有双引号或反斜杠转义-它们是用于shell的 ,而不是cut
,并且这里没有shell.
No double quotes or backslash escapes -- those are for the use of the shell, not cut
, and there's no shell here.
这使得处理未知文件名(对于您将来的用例)特别容易:当将字符串作为参数传递给(以后不会误用我正在运行的eval
等效代码的软件)时,您不会在将它们作为数据传递之前,需要对其进行引用,转义,清理或进行其他修改.
This makes dealing with unknown filenames (for your future use cases) particularly easy: When your strings are passed as arguments (to software that doesn't misuse them my running eval
-equivalent code later), you don't need to quote, escape, sanitize, or otherwise modify them before they can be passed as data.
(也就是说,当您告诉外壳程序cut -f1 -d" "
时,它调用的实际syscall以C语法启动cut
进程,看起来像execve("/usr/bin/cut", {"cut", "-f1", "-d ", NULL}, environ)
;引号是句法的,由shell,当它们使用它们来决定-d
之后的空格应该是同一文字参数的一部分时.
(That is to say -- when you tell your shell cut -f1 -d" "
, the actual syscall it invokes to start that cut
process, in C syntax, looks like execve("/usr/bin/cut", {"cut", "-f1", "-d ", NULL}, environ)
; the quotes were syntactic, consumed by the shell when it used them to make the decision that the space after the -d
should be part of the same literal argument).
这篇关于在nodejs中生成一个带参数空格的unix命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!