The reason why Java cannot use sudo command when booting under Linux system and the solution

  • 2020-04-01 02:12:30
  • OfStack

Operating system: centos 5.2
Scene description:
We had a WEB project where the client wanted to run it as a regular user (like CHB), and then had a button on the page that could be clicked to shut it down

Implementation method:
1. JAVA code:


        public static boolean shutDownForLinux() {
                try {
                        Runtime.getRuntime().exec("sudo /sbin/poweroff");
                } catch (IOException e) {
                        return false;
                }
                return true;
        }

2. Modify /etc/sudoers to add the following information to the end:
CHB ALL = NOPASSWD: / sbin/reboot, / sbin/poweroff

3. Set the startup to start tomcat automatically, modify /etc/rc.d. /rc.local, and add the following at the end:
Su CHB - c "/ opt/tomcat/bin/startup. Sh"

Problem description:
The shutdown button on the page fails to realize the shutdown function every time the Java process is started automatically. However, if you log into the server via SSH with the CHB account, manually kill the tomcat process, and then restart tomcat, the shutdown button on the page will be effective. Do you know why? Is it related to the sudo loading order? Or is it related to the CHB user shell environment?

Problem analysis:
Through the analysis of the JAVA process of startup and manually start the JAVA process, found the tty is different, then go to Google sudo and tty, sudo default is found to tty, system startup, no tty, we log in the server via SSH client, kill a tomcat, and then restart the tomcat, tty to PTS can be obtained at this time, so you can use the sudo command

Solutions:
By modifying the /etc/sudoers file, will
        Defaults requiretty
Just comment it out


Related articles: