Search code examples
linuxjnarestartshutdown

Using JNA or similar to shutdown and restart computer in linux and mac


I am trying to write a function in java that will shutdown, force shutdown, restart and force restart the computer and it should work on Windows, Linux and Mac.

Windows is not a problem, but I am unable to run commands to shutdown on Linux due to the sudo privileges. I was therefore thinking of using JNA to shut down the computer (i know you can use JNA to do this on windows), but I can't find any examples online for linux or mac.

Can anyone help me out? It will be much appreciated!

Even if it's not through JNA, it would help me a lot as long as I can find some way to accomplish this.


Solution

  • If you could simply override system protections just by using Java, that would be a big security flaw! I'm surprised you can do this on Windows.

    Anyway, it can only be done if you have administrative access to your machine to set the program in a certain group which has the rights to shutdown/restart. Otherwise, you can't just do that.

    I think you could give directly these rights to your JVM, but that could be dangerous if other java programs try to do shutdown.