的NodeJS,执行外部命令的唯一方法是经由sys.exec(CMD)。我想调用外部命令,并通过标准输入给它的数据。在那里的NodeJS也尚未似乎打开命令的方式,然后将数据推送到它(只Exec和接收其标准+错误输出),所以会出现我必须这样做,现在是唯一的出路经由单个字符串命令,例如:

var dangerStr = "bad stuff here";
sys.exec("echo '" + dangerStr + "' | somecommand");

大多数回答这样的问题都集中在正则表达式或者其不工作我的NodeJS(使用谷歌的V8 Javascript引擎)或本机功能,从像Python等语言。

我想逃避dangerStr使得它的安全构成一个exec串像上面的。如果有帮助,dangerStr将包含JSON数据。

有帮助吗?

解决方案

有是写于外部命令的方式:process.createChildProcess文档)返回一个用write方法对象。 createChildProcess是不是仿佛方便,因为它不缓冲输出和错误,所以你需要事件处理程序来读取输出块。

var stdout = "", stderr = "";
var child = process.createChildProcess("someCommand");

child.addListener("output", function (data) {
    if (data !== null) {
        stdout += data;
    }
});
child.addListener("error", function (data) {
    if (data !== null) {
        stderr += data;
    }
});
child.addListener("exit", function (code) {
    if (code === 0) {
        sys.puts(stdout);
    }
    else {
        // error
    }
});

child.write("This goes to someCommand's stdin.");

其他提示

这是我使用:

var escapeShell = function(cmd) {
  return '"'+cmd.replace(/(["\s'$`\\])/g,'\\$1')+'"';
};

如果您需要简单的解决方案,你可以使用这个:

function escapeShellArg (arg) {
    return `'${arg.replace(/'/g, `'\\''`)}'`;
}

所以你的字符串将用单引号简单地转义为克里斯·约翰逊提到的。

echo 'John'\''s phone';

它的工作原理,因为强引用bash,感觉像是在fish作品,但不会在zshsh工作。

如果您有bash您可以在shzsh'bash -c \'' + escape('all-the-rest-escaped') + '\''运行脚本。

但实际上......,Node.js就会逃避所有需要的字符,您:

var child = require('child_process')
  .spawn('echo', ['`echo 1`;"echo $SSH_TTY;\'\\0{0..5}']);

child.stdout.on('data', function (data) {
  console.log('stdout: ' + data);
});

child.stderr.on('data', function (data) {
  console.log('stderr: ' + data);
});

的代码块将执行:

echo '`echo 1`;"echo $SSH_TTY;'\''\\0{0..5}'

和将输出:

stdout: `echo 1`;"echo $SSH_TTY;\'\\0{0..5}

或一些错误。

看一看 http://nodejs.org/api/child_process.html#child_process_child_process_spawn_command_args_options

顺便说简单的解决方案来运行一串命令是:

require('child_process')
  .spawn('sh', ['-c', [
    'cd all/your/commands',
    'ls here',
    'echo "and even" > more'
  ].join('; ')]);

有一个愉快的一天!

应的从不的依靠逃逸未知输入要去一个shell参数 - 有几乎总是会有一些边缘情况下你有没有想过,允许用户在服务器上执行任意代码

节点具有用于调用命令,并分别通过每个参数,没有逃逸所需的支持。这是做的最安全的方式:

const { spawn } = require('child_process');
// Note that the arguments are in an array, not using string interpolation
const ls = spawn('ls', ['-lh', '/usr']);

ls.stdout.on('data', (data) => {
  console.log(`stdout: ${data}`);
});

ls.stderr.on('data', (data) => {
  console.log(`stderr: ${data}`);
});

ls.on('close', (code) => {
  console.log(`child process exited with code ${code}`);
});

该文档是此处

如果您还需要处理特殊字符(换行符等),你可以这样来做:

str = JSON.stringify(str)
    .replace(/^"|"$/g,'') //remove JSON-string double quotes
    .replace(/'/g, '\'"\'"\'') //escape single quotes the ugly bash way

这是假设你使用bash的强引用通过单-quotes)和接收机能理解JSON的类C漏出。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top