1

I am trying to run

String command = "su -c 'busybox ls /data'";
p = Runtime.getRuntime().exec(command);

in my app, but it seems like the syntax is somehow wrong. I have no problem running it from the terminal emulator app on the phone, though, so I just can't understand why it is not working when called from within my app.

Any help is deeply appreciated!

3
  • Does your app have superuser privileges? App permissions are different from terminal permissions. Commented Feb 21, 2012 at 19:08
  • My knowledge is limited, but I had understood that an app can't have superuser privileges, only spawn processes that do. Btw the Superuser app notifies me that root privileges have been granted if I run say "su -c id", and the output is correct.. What do you suggest? Thanks a lot Commented Feb 22, 2012 at 9:09
  • 1
    Not exactly sure what is wrong. However, there seems to be a lot of other topics on stackoverflow that might help you if you search. stackoverflow.com/questions/7216071/…. stackoverflow.com/questions/6896618/… Commented Feb 22, 2012 at 14:54

2 Answers 2

3

SOLUTION FOUND! Thanks to the link suggested by onit here. See the code below: for superuser shell commands to work properly, you first need to create a superuser shell and assign it to a process, then write and read on it's input and output streams respectively.

Process p = Runtime.getRuntime().exec(new String[]{"su", "-c", "system/bin/sh"});
DataOutputStream stdin = new DataOutputStream(p.getOutputStream());
//from here all commands are executed with su permissions
stdin.writeBytes("ls /data\n"); // \n executes the command
InputStream stdout = p.getInputStream();
byte[] buffer = new byte[BUFF_LEN];
int read;
String out = new String();
//read method will wait forever if there is nothing in the stream
//so we need to read it in another way than while((read=stdout.read(buffer))>0)
while(true){
    read = stdout.read(buffer);
    out += new String(buffer, 0, read);
    if(read<BUFF_LEN){
        //we have read everything
        break;
    }
}
//do something with the output
Sign up to request clarification or add additional context in comments.

Comments

0

Use the function below:

public void shellCommandRunAsRoot(String Command)
{
 try 
  {
     Process RunProcess= Runtime.getRuntime().exec("su");
     DataOutputStream os;
     os = new DataOutputStream(RunProcess.getOutputStream()); 

     os.writeBytes(cmds+"\n");
         os.writeBytes("exit+\n");
     os.flush();

  }
  catch (IOException e)
  {
     // Handle Exception 
  }    
}

Usage:

shellCommandRunAsRoot("pkill firefox");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.