I want to reboot/shutdown my linux OS from a node.js script. Only on things i can find are methods to stop a express server or a running function inside a script but not a way to shutdown/reboot my hole linux.
is there any way to do that?
Linux system restart To reboot the Linux system from a terminal session, sign in or “su”/”sudo” to the “root” account. Then type “ sudo reboot ” to reboot the box. Wait for some time and the Linux server will reboot itself.
To restart your system by force, press Alt + SysRq + R , then Alt + SysRq + B . Doing this will switch your kernel's keyboard driver to “Raw,” then trigger a “Force Reboot” instruction.
The nodejs command is:
require('child_process').exec('sudo /sbin/shutdown -r now', function (msg) { console.log(msg) });
To avoid running nodejs as su you must give permission to run this command. Give permissions by creating a file under the /etc/sudoers.d/ directory, e.g.
$ sudo /etc/sudoers.d/mysudoersfile
Add the following lines and change pi
in the below snippet to the user nodejs will be running as:
pi ALL=/sbin/shutdown
pi ALL=NOPASSWD: /sbin/shutdown
This technique can also be applied to other commands. For example if you want to allow the user (in turn nodejs) to restart networking then add the following to your sudoers file.
pi ALL=/etc/init.d/networking
pi ALL=NOPASSWD: /etc/init.d/networking
thanks for so far. I got a solution thats working with that now. only it has no response that the command has been executed. For the rest it's working.
code:
console.log('loaded.....');
var exec = require('child_process').exec;
function execute(command, callback){
exec(command, function(error, stdout, stderr){ callback(stdout); });
}
execute('shutdown -r now', function(callback){
console.log(callback);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With