【问题标题】:In node.js, how can I auto input the password with sudo command in exec?在 node.js 中,如何在 exec 中使用 sudo 命令自动输入密码?
【发布时间】:2016-03-19 18:06:38
【问题描述】:

我正在开发 Node.js 程序并遇到问题。

我尝试使用stdin.write在exec中自动输入sudo的密码,但是好像不行。

我不想以 root 身份运行我的程序。

这是我的代码:

var SUDO_PASSWORD = '123456';
var command = 'sudo echo "1" > test.txt';
var child = require('child_process').exec(command);
child.on('exit', function() {
    console.log('in exit');
    return 'OK';
});
child.stdin.write(SUDO_PASSWORD);

如何修改?谢谢大家。

【问题讨论】:

  • 您好,请告诉我您是如何解决这个问题的。

标签: node.js exec stdin child-process


【解决方案1】:

我们有同样的问题,需要做一个 root 操作,但不希望应用程序以 root 权限运行。 所以我们从 root 启动应用程序,然后使用

删除 root 权限
 if (!/^win|^darwin/i.test(require('os').platform())) {
        try {
            console.log('I am ' + process.getuid());
            process.setgid('user');
            process.setuid('user');
            console.log('I now am ' + process.getuid());
        } catch (err) {
            console.error("Unable to drop root privileges, exiting\n" + err.message, [err.stack]);
            process.exit();
        }
    }

我知道这不是您想要的,但也许可以解决您的问题。

【讨论】:

  • 您好 xflofoxx,感谢您的回复,但它不能解决我的问题。那是因为当我更改为普通用户时,我无法使用 sudo 运行命令。在我的情况下,它将在普通用户上运行,但有时需要以 root 身份运行。
猜你喜欢
  • 2023-03-25
  • 2013-09-26
  • 1970-01-01
  • 1970-01-01
  • 2019-05-29
  • 2021-11-11
  • 2011-03-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多