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
Remove HTML Tags from a String
How to Get Url from Firebase Storage Getdownloadurl
Com.Android.Build.Transform.API.Transformexception
Android/Java - Date Difference in Days
Will System.Currenttimemillis Always Return a Value ≫= Previous Calls
How to Generate a Random Alpha-Numeric String
Java: Maintaining Aspect Ratio of Jpanel Background Image
:: (Double Colon) Operator in Java 8
How to Send Http Request in Java
Android.Content.Res.Resources$Notfoundexception: String Resource Id #0X0
How to Display Data from Firestore in a Recyclerview With Android
How to Count the Number of Documents Under a Collection in Firestore
Technically What Is the Main Difference Between Oracle Jdk and Openjdk
Stringbuilder VS String Concatenation in Tostring() in Java