Home > other >  How to execute a full shell string without writing it to a file?
How to execute a full shell string without writing it to a file?

Time:04-16

I have a shell (.sh) file that it is multi-line and has functions inside it as a string and I want to execute it entirely without the need to write it to to a .sh file.

  • I tried with Process process = Runtime.getRuntime().exec(commands) and the ProcessBuilder but it was never executed correctly and I was not able to get the error message.
  • I also tried with su cat << EOF commands_here EOF but also never finished

I believe the error comes because it has functions inside it and not only one command per line. Is there a way to execute such shell's string without the need to write it to disk and using ./file.sh?

CodePudding user response:

The safest way to achieve this in android is to:

  1. Encode your commands to base64 then apply
  2. Apply a command that decodes them and executes them

Here is a code example:

val b64 = Base64.encode(allCmds.toByteArray(), Base64.DEFAULT)
                            .toString(Charsets.UTF_8).trim()
b64 = b64.replace("\n", "")
var exitValue = 0
try {
    p = Runtime.getRuntime().exec("su -c echo $b64 | base64 -d | sh")
    exitValue = p.waitFor()
} catch (e: Exception) {
    exitValue = 1
}

return exitValue # the value 0 indicates normal termination

CodePudding user response:

You can do it like this in Kotlin:

val result = "PowerShell -Command --YOUR COMMAND HERE-- ".execute().text.trim()
  • Related