如何在node.js中实现这个python代码snipp

2024-06-26 00:20:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要在Node.js中写这个

vCmd = any cmd that needs root privileges
vPwd = "1234" #asked before in a seperate dialog
vProc = subprocess.Popen(["sudo", "-S", "xfce4-terminal", "-e", vCmd], stdin=subprocess.PIPE, stderr=subprocess.PIPE)
vResult = vProc.communicate(vPwd + '\n')[1]

(可能与嵌套的子进程\u process.spawn有关)
重要的是以编程方式使用sudo和密码


Tags: cmdnodethatjssudoanyrootasked
1条回答
网友
1楼 · 发布于 2024-06-26 00:20:56

在节点的child_process模块中使用spawn函数,并将sudo密码写入stdin:

var spawn = require('child_process').spawn;
var vCmd = '<command to execute>';
var args = [ '-S', 'xfce4-terminal', '-e', vCmd ];
// The sudo password
var pw = '******';
// Spawn the sudo command
var proc = spawn( 'sudo', args );
// Log stdout to console.
proc.stdout.on('data', ( data ) => {
    console.log( data.toString() );
});
// Send password to stdin.
proc.stdin.write( pw+'\n' );
// Close stdin.
proc.stdin.end();

相关问题 更多 >