How to run sudo poweroff in java

250 views Asked by At

I am a jsp developer. I need to shut down my slow, unresponsive, laggy, (you get the point) development ubuntu "server" sometimes, when its keyboard stops responding to input. I already have tomcat configured properly, and even when my keyboard stops responding, I can use it as a server (accessing webpages served by tomcat). My idea is to make a jsp page that calls sudo poweroff. But I have no idea how to do that. I have tried

Runtime.getRuntime.exec("sudo poweroff");

but it does not work for me. I have already edited the sudoers file to allow the tomcat user to perform this action without requiring a password. How can I make this happen?

1

There are 1 answers

2
Larry On

If the user running tomcat has sudo perms (w/o a password), it should be doable - but the call should be something like this:

Runtime.getRuntime().exec(new String[]{"sudo", "poweroff"});

The command and parameters can't all be passed in one big string.

Check out the docs for more info: https://docs.oracle.com/javase/7/docs/api/java/lang/Runtime.html#exec(java.lang.String[])

PS: This is probably a bad idea. :)