node.js - nodejs运行系统命令时遇到(Y or N)必须要输入Y或者N才能继续向下运行的解决办法是什么?
大家讲道理
大家讲道理 2017-04-17 14:43:56
0
2
746

假设当前nodejs要运行命令rm -rf 123.txt,那么代码就是

process.exec('rm -rf 123.txx',function (error, stdout, stderr) {
    if (error !== null) {
        console.log('exec error: ' + error);
    }else {
        console.log(stdout)
    }
});

OK,这里确实删除了。但是如果加上sudo呢?比如sudo rm -rf 123.txt,需要输入密码才能删除。下面是我尝试的办法,但是无法删除:

process.exec('sudo rm -rf 123',function (error, stdout, stderr) {
    if (error !== null) {
        console.log('exec error: ' + error);
    }else {
        process.exec('密码',function (error, stdout, stderr) {
            if (error !== null) {
                console.log('exec error: ' + error);
            }else {
                console.log(stdout)
            }
        });
        console.log(stdout)
    }
});

这是我尝试嵌套process.exec来解决,但是发现无法解决。

上面是个例子,实际项目中我需要使用nodejs来调用python或者其他脚本。
比如xxx.py,在实际终端下他是这样的:

test@test:~/$ python xxx.py
info:xxxxxxx
请问是否继续么?(Y or N):Y
sys_info:xxxxx
请问是否退出?(Y or N):N
log_info:xxxxx
test@test:~/$ 

如果nodejs调用的话,该怎么办,怎么让提示信息为请问是否继续么?(Y or N):时自动输入Y,并回车继续向下执行。当提示信息为请问是否退出?(Y or N):时,自动输入N,然后回车运行。

大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

全部回覆(2)
小葫芦

sudo指令有個-S選項,用於在需要輸入密碼的時候,讀取密碼。

假設密碼為111111,那麼,完整指令如下

echo "111111" | sudo -S rm -rf ./123.txt

對應的,node程式碼可以這樣

var child_process = require('child_process');
child_process.exec('echo "111111" | sudo -S rm -rf ./123.txt', function(error, stdout, stderr){
    if(error){
        throw error;
    }else{
        console.log(stdout);
    }
});
PHPzhong

stackoverflow

I have been working on this all day.

The problem is that the STDOUT of your spawned process needs to flush it's output buffer, otherwise it will sit there until it fills up, in which case your code won't execute again.p.stdin.end() only serves to end the process, which by its very nature, allows the OS to clear up all buffers.

You can't do this from the node as this is not the owner of the output buffer.

It is annoying, but as long as you have control of the script, you can modify it there, perhaps allow it to take a command line option to set an autoflush?

Hope this is of some help.

由於sudo索取密碼的輸出沒有沖刷緩衝區,node的data沒有被觸發,所以下面的程式碼不能工作

假如子程序呼叫了對緩衝區的flush(e.g. in python

),那麼理論上類似這一段的程式碼可以工作sys.stdin.flash

const childProcess = require("child_process");

const exec = childProcess.spawn("sudo", ["rm", "123.tx"], {
  stdio: "pipe"
});

exec.stdout.on("data", (data) => {
  console.log("stdout", data.toString());
  exec.stdin.write("123456\n");
});

exec.stderr.on("data", (data) => {
  console.log("stderr", data.toString());
  exec.stdin.write("123456\n");
});

exec.on("close", (code) => {
  console.log(`exit ${code}`);
});
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板