Deepak Kr. Karn
Deepak Kr. Karn

Reputation: 25

execute shell script as root in java code

How to run .sh file as a root in this code? in the main section i run my .sh file from desire directory. But i got permission denied when i run. I simple want my .sh code run as root. Is there any way?

    import java.io.IOException;
    import org.apache.commons.exec.CommandLine;
    import org.apache.commons.exec.DefaultExecutor;
    import org.apache.commons.exec.ExecuteException;

    public class TestScript {
        int iExitValue;
        String sCommandString;

        public void runScript(String command){
            sCommandString = command;
            CommandLine oCmdLine = CommandLine.parse(sCommandString);
            DefaultExecutor oDefaultExecutor = new DefaultExecutor();
            oDefaultExecutor.setExitValue(0);
            try {
                iExitValue = oDefaultExecutor.execute(oCmdLine);
            } catch (ExecuteException e) {
                // TODO Auto-generated catch block
                System.err.println("Execution failed.");
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                System.err.println("permission denied.");
                e.printStackTrace();
            }
        }

        public static void main(String args[]){
            TestScript testScript = new TestScript();
            testScript.runScript("sh /home/deepak/Desktop/ftpusers.sh");
        }
    }

Upvotes: 1

Views: 2790

Answers (2)

bedrin
bedrin

Reputation: 4586

You should either run your Java application as a root, or execute the ftpusers.sh using some king of sudo command. I can see two possible options here:

  1. If your application is started with an X Server, you can call the ftpusers.sh using gksudo, kdesudoor similar - it will prompt user if he is ok to run the application as root and probably ask for the password.
  2. If your application is a console one, you will have to use the sudo command and manually redirect the IO from this command to the IO of your application

Please note that this approach won't work on all environments (sudo might be unavailable for example), so I would just change the "permission denied." message to something like "Application foor must be started as root" and ask user to run the Java application with proper permissions

Upvotes: 1

Vitruvie
Vitruvie

Reputation: 2327

Either run your java program as root, or run a setuid script to elevate your permissions. If the latter, ensure that no unauthorized users have access to the script.

Upvotes: 0

Related Questions