Reputation: 25
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
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:
ftpusers.sh
using gksudo
, kdesudo
or similar - it will prompt user if he is ok to run the application as root and probably ask for the password. sudo
command and manually redirect the IO from this command to the IO of your applicationPlease 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