How to Execute Bash Command With Sudo Privileges in Java

How to execute bash command with sudo privileges in Java?

I think you can use this, but I'm a bit hesitant to post it. So I'll just say:

Use this at your own risk, not recommended, don't sue me, etc...

public static void main(String[] args) throws IOException {

String[] cmd = {"/bin/bash","-c","echo password| sudo -S ls"};
Process pb = Runtime.getRuntime().exec(cmd);

String line;
BufferedReader input = new BufferedReader(new InputStreamReader(pb.getInputStream()));
while ((line = input.readLine()) != null) {
System.out.println(line);
}
input.close();
}

How to execute sudo commands in Java and get error output?

Is there a way to read the error output

Yes, call p.getErrorStream().

Better yet, use ProcessBuilder and call redirectErrorStream(true), so the error output is read from the getInputStream() data.

How to execute shell commands as root in Java

You could run gksudo <your command> but this ties your application to a certain UI, e.g. gnome, kde, etc.



Related Topics



Leave a reply



Submit