How to shut down a computer (host)

Viewed 59

I know it sounds weird, but I have a case where Deno would need to shutdown its own host (and kill its own process therefore). Is this possible?

I am specifically needing this for linux (lubuntu), if that's relevant. I guess this requires sudo rights, which sucks but would be an option.

For those interested in details: I'm coding a minecraft server software and if the server has no player for 30 minutes, it will shut itself down to save some power. A raspberry PI that runs 24/7 anyways, has a wake on lan feature, so that it can boot again. After boot, the server manager software would automatically start as a linux service.

2 Answers

You can create a subprocess to do this:

await Deno.run({ cmd: ["shutdown", "-h", "now"] }).status();

Concepts

  • Deno is capable of spawning a subprocess via Deno.run.
  • --allow-run permission is required to spawn a subprocess.
  • Spawned subprocesses do not run in a security sandbox.
  • Communicate with the subprocess via the stdin, stdout and stderr streams.
  • Use a specific shell by providing its path/name and its string input switch, e.g. Deno.run({cmd: ["bash", "-c", "ls -la"]});

See also command line - Shutdown from terminal without entering password? - Ask Ubuntu for ideas on how to avoid needing sudo to call shutdown or alternative commands that you can invoke from Deno instead.

To extend on what @mfulton2 wrote, here is how I made it work, so that I did not need to start the program with sudo rights, but still was able to shut down the computer without the use of sudo outside or within the app.

  1. Open or create the following file: sudo nano /etc/sudoer
  2. Add the line username ALL = NOPASSWD: /sbin/shutdown
  3. Add this line %admin ALL = NOPASSWD: /sbin/shutdown
  4. In your deno script, write Deno.run({ cmd: ["shutdown", "-h", "now"]}).status();
  5. Execute script!

Keep in mind that any experienced linux user would potentially tell you that this is very dangerous (it probably is) and that it might not be the very best way. But IMHO, the damage this can cause is minor enough, as it only affects the shutdown command.

Related