Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i reboot linux from nodejs

Tags:

linux

node.js

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?

like image 989
Paules Avatar asked Apr 12 '14 15:04

Paules


People also ask

How do you reboot the system in Linux?

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.

How do I restart a stuck Linux?

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.


2 Answers

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
like image 74
Simon Hutchison Avatar answered Oct 18 '22 22:10

Simon Hutchison


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);
});
like image 37
Paules Avatar answered Oct 18 '22 20:10

Paules