javalinuxtomcatubuntutomcat7

Running sudo command from Tomcat servlet


Is there a way to let a tomcat 7 server (running on an Ubuntu Server) execute a sudo command in a command line? In this specific case I want to make it possible to shut down the system from another server. What code would I have to use? And do I have to run the tomcat server as root or can i get these privileges at runtime and only for this action? Thanks for your help:)


Solution

  • No need to run Tomcat as root, you can just add tomcat user to /etc/sudoers to allow him run superuser commands, like sudo shutdown now. This way allows you to specify desired subset of commands that can be executed by user. E.g. to allow him to run only shutdown:

    tomcat ALL=NOPASSWD: /sbin/shutdown
    

    To run shell commands from Java code you can call one of Runtime.exec() or use ProcessBuilder.

    P.S. Also try googling about /etc/shutdown.allow file which allows running shutdown command by any user that is listed in it. But I've never used it.