假设当前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,然后回车运行。
The
sudo
command has a-S
option, which is used to read the password when a password needs to be entered.Assuming the password is
111111
, then the complete command is as followsCorrespondingly, the node code can be like this
stackoverflow
Because the output of sudo asking for a password does not flush the buffer and the node data is not triggered, the following code does not work
If the child process calls flush on the buffer (e.g. in python
sys.stdin.flash
), then theoretically code similar to this section can work