读取su进程内的命令输出

glo*_*dos 12 android root su

首先,我将介绍我的情况.我需要在我的Android应用程序中执行"su"命令,它运行良好.然后我需要执行"ls"命令并读取输出.我是通过从"su"进程获取输出流并将命令写入其中来实现的.

这就是问题所在.如何读取"ls"进程的输出?我所拥有的只是"su"Process对象.从中获取输入流没有任何结果,因为"su"不会写任何内容.但"ls"确实如此,我不知道如何访问其输出消息.

我搜索了很多网站,但我找不到任何解决方案.也许有人会帮助我:)

问候

glo*_*dos 24

好的,我找到了解决方案.它应该如下所示:

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
Run Code Online (Sandbox Code Playgroud)

希望它对某人有所帮助

  • 如果系统调用没有返回任何内容,则对read()的调用会停止.在这种特殊情况下,"ls"应该总是返回一些内容,但请记住它可能会停止其他命令. (4认同)

She*_*tib 5

public String ls () {
    Class<?> execClass = Class.forName("android.os.Exec");
    Method createSubprocess = execClass.getMethod("createSubprocess", String.class, String.class, String.class, int[].class);
    int[] pid = new int[1];
    FileDescriptor fd = (FileDescriptor)createSubprocess.invoke(null, "/system/bin/ls", "/", null, pid);

    BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(fd)));
    String output = "";
    try {
        String line;
        while ((line = reader.readLine()) != null) {
            output += line + "\n";
        }
    }
    catch (IOException e) {}
    return output;
}
Run Code Online (Sandbox Code Playgroud)

检查这里提到的代码:

如何在Android应用程序中运行终端命令?


try {
// Executes the command.
Process process = Runtime.getRuntime().exec("/system/bin/ls /sdcard");

// Reads stdout.
// NOTE: You can write to stdin of the command using
//       process.getOutputStream().
BufferedReader reader = new BufferedReader(
        new InputStreamReader(process.getInputStream()));
int read;
char[] buffer = new char[4096];
StringBuffer output = new StringBuffer();
while ((read = reader.read(buffer)) > 0) {
    output.append(buffer, 0, read);
}
reader.close();

// Waits for the command to finish.
process.waitFor();

return output.toString();
} catch (IOException e) {
throw new RuntimeException(e);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
Run Code Online (Sandbox Code Playgroud)

参考

这段代码是 GScript