Android Root execute su with parameters

2019-03-06 02:52发布

I ve got a problem, executing su with parameters (containing blank space?!). My Command.java looks like this:

public class Command
{
    Process process;

public String executeCommand(String command)
{

    StringBuffer output = new StringBuffer();

    try {
        process = Runtime.getRuntime().exec(command);
        process.waitFor();
        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));

        String line = "";
        while ((line = reader.readLine())!= null) {
            output.append(line + "\n");
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
    String response = output.toString();
    return response;
}
}

In my MainActivity it is working for single commands.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    TextView content = (TextView) findViewById(R.id.txt_content);

    Command cmd = new Command();

    String outp = cmd.executeCommand("su -c 'id'");
    Log.d("OOOOOOUT", outp);

    content.setText(outp);

}

The result shows, that it is working:

D/OOOOOOUT: uid=0(root) gid=0(root) context=u:r:init:s0

This is also working for the ls command. But when I try to parse an argument with paramters, it will not get executed.

E.g.

    String outp = cmd.executeCommand("su -c 'ls /data/data/'");
    Log.d("OOOOOOUT", outp);

    content.setText(outp);

I also tryed the following:

String outp = cmd.executeCommand("su -c \'ls /data/data/\'");
String outp = cmd.executeCommand("su -c 'ls -l'");

And even more. When I execute this command within the shell directly I get the following output:

shell@hammerhead:/ $ su -c 'ls -l'
drwxr-xr-x root     root              1970-06-20 18:01 acct
drwxrwx--- system   cache             2016-06-21 22:06 cache
-rwxr-x--- root     root       272364 1970-01-01 01:00 charger
dr-x------ root     root              1970-06-20 18:01 config

I also tryed using the complete path:

shell@hammerhead:/ $ /system/xbin/su -c 'ls -l'                                
drwxr-xr-x root     root              1970-06-20 18:01 acct
drwxrwx--- system   cache             2016-06-21 22:06 cache

Also within the application. I guess its a parsing error. Sometimes I see people adding the "\n" at the end of a command? No clue why. I really appreciate any help within this topic. Thanks!

1条回答
等我变得足够好
2楼-- · 2019-03-06 03:02

I think the way to pass arguments to the su command would be to use a string array:

Runtime.getRuntime().exec(new String[]{"su","-c", "ls /data/data/"});
查看更多
登录 后发表回答