Home > Blockchain >  Android: How to process output of Runtime.getRuntime().exec() calling dumpsys on rooted phone
Android: How to process output of Runtime.getRuntime().exec() calling dumpsys on rooted phone

Time:11-23

I am working on a small proof of concept on a rooted phone, which relys on being able to read dumpsys output.

If I call dumpsys on my (rooted) phone running Android 11 like this, using adb:

adb shell dumpsys telephony.registry | grep "mCi="

I get a pretty long printout. The grep filters for lines containing cell tower IDs, but that shouldn't e important here (it's just an example). Now I'm trying to execute the same command inside a very simple app, and log its output, like this:

private  fun test() {
       
        try {
            val process = Runtime.getRuntime().exec("su dumpsys telephony.registry | grep \"mCi=\"")
            val bufferedReader = BufferedReader(InputStreamReader(process.inputStream))
            val string = bufferedReader.readText()
            Timber.d("output: $string")
            bufferedReader.close() // do I need this?
        } catch (e: IOException) {
            // handle Exception
        }
    }

I get no output at all (string length is 0). If I replace my process command with something simple like this: Runtime.getRuntime().exec("echo 'abcde'") the output is logged as intended (output: 'abcde').

I also tried shortening the possible output, in case that was the problem by appending --max-count=1, to have grep only put out the first found line. Again, it works using adb, does not work in code.

what am I doing wrong?

(I am using Timber to print my logs, if anyone doesn't know what that line is in the xample.)

CodePudding user response:

The first thing you should do is to log the stderr stream that is available for your process as well. This will give you information about what is wrong with your command.

Your command is not correctly processed as it is seen as one command. The reason is explained in this answer.

The solution is to use a String[] as an argument of exec and explicitly execute the command with the shell. I wrote some code that executes your command, but it is in Java on an unrooted device. Still, it generates output and grep works.

            String[] arrayCommand = {"sh", "-c","dumpsys telephony.registry | grep \"permission\""};
            
            Runtime r = Runtime.getRuntime();
            Process process = r.exec(arrayCommand);

            String stdoutString = convertInputStreamToString(process.getInputStream());
            String stderrString = convertInputStreamToString(process.getErrorStream());

  • Related