0

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.

Angeline
  • 47
  • 1
  • 7

1 Answers1

1

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.

wormsparty
  • 2,481
  • 19
  • 31
  • Yeah, it's possible for Windows by using the shutdown command via Runtime.exec(). At the moment what I'm doing for linux is that I ssh back to myself with an account with administrator privileges in order to shutdown and restart. Is this the only way, then? – Angeline Oct 03 '11 at 10:07
  • That's just as unsecure as to give the JVM privileges or to use sudo/su with a passwordless account. As long as it works ;) – wormsparty Oct 03 '11 at 10:17
  • What you could also try is to edit the /etc/sudoers file and give yourself the right to execute `/sbin/shutdown` without any password. – wormsparty Oct 03 '11 at 10:19
  • Unfortunately, the account running the program may not have the right privileges to do the shutdown. So I have to make use of another administrator account anyway, right? – Angeline Oct 03 '11 at 13:42
  • Yes, that's the simplest way. – wormsparty Oct 03 '11 at 14:00
  • You can also edit the sudoers file (on OSX as well) to allow all users to run one specific program as root (you can even limit the args passed to it). In what context are you trying to allow users to reboot the machine? – technomage Oct 04 '11 at 12:54
  • I did try editing the sudoers file but somehow it just doesn't work when I try to run it through Runtime.exec(). When I run it through terminal it's fine though. I'm creating a monitoring system, where one computer is able to send a message to another to ask it to shut itself down. At the moment I think I'll be implementing it by using ssh (I was kind of hoping there was some other way, because then the administrator has install ssh on the computer and has to edit the sudoers file, which is slightly troublesome) Anyway, thanks for all the help :) – Angeline Oct 21 '11 at 03:34