[英]Execute shell commands using nodejs with root access
我想在 nodeJs 應用程序中執行以下 shell 命令。 如果我手動完成工作,命令如下:
sudo su
password
1 command that needs a root access
exit
任何想法或代碼片段都會有所幫助
您可以通過 Ref: Super User answer將所有 4 個命令合二為一
echo "<password>" | sudo -S "<command that needs a root access>"
在您的 NodeJs 代碼中 - 嘗試以下操作之一:
var command='echo "<password>" | sudo -S "<command that needs a root access>"';
child_process.execSync(command)
const shellExec = require('shell-exec')
var command='echo "<password>" | sudo -S "<command that needs a root access>"';
shellExec('echo Hi!').then(console.log).catch(console.log)
在觸發執行之前,請務必驗證需要執行的命令,以避免出現不需要的結果。
您可以使用 child_process 的 exec 函數執行命令
const { exec } = require("child_process");
// Here you can execute whatever command you want to execute
exec("ls -la", (error, stdout, stderr) => {
if (error) {
console.log(`error: ${error.message}`);
return;
}
if (stderr) {
console.log(`stderr: ${stderr}`);
return;
}
// stdout returns the output of the command if you wish to use
console.log(`stdout: ${stdout}`);
});
雖然接受的答案很好,但它並不是最安全的 - 因為 sudo 密碼以明文形式存儲。
更安全的方法是在 sudoers 文件中添加一行,這將允許特定用戶通過 sudo 執行特定命令而無需密碼:
user host = (root) NOPASSWD: cmd
將“用戶”、“主機”和“cmd”替換為您的要求。
這避免了需要以明文形式存儲任何密碼,並且如果您將命令封裝在 shell 腳本中並進行適當的驗證,則可以嚴格控制超級用戶訪問。
有關更多詳細信息,請參閱此答案或sudoers 手冊
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.