Created
January 6, 2022 09:12
-
-
Save itstartstosnow/45de8bd1e6e76c544189e7b867fd4c80 to your computer and use it in GitHub Desktop.
Run sh command in Android
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.sylvia.gist; | |
import android.util.Log; | |
import java.io.BufferedReader; | |
import java.io.IOException; | |
import java.io.InputStreamReader; | |
import java.io.OutputStreamWriter; | |
public class MyCommandRunner { | |
private static final String TAG = "MyCommandRunner"; | |
Boolean logging = true; | |
public MyCommandRunner() { | |
} | |
public MyCommandRunner(Boolean logging) { | |
this.logging = logging; | |
} | |
public String executeCmd(String runtimeCmd, String cmd) { | |
Runtime runtime = Runtime.getRuntime(); | |
Process proc = null; | |
OutputStreamWriter osw = null; | |
try { | |
proc = runtime.exec(runtimeCmd); | |
osw = new OutputStreamWriter(proc.getOutputStream()); | |
osw.write(cmd); | |
osw.flush(); | |
osw.close(); | |
} catch (IOException ex) { | |
ex.printStackTrace(); | |
} finally { | |
if (osw != null) { | |
try { | |
osw.close(); | |
} catch (IOException ex) { | |
ex.printStackTrace(); | |
} | |
} | |
} | |
try { | |
if(proc != null) { | |
proc.waitFor(); | |
} | |
} catch(InterruptedException ex) { | |
ex.printStackTrace(); | |
} | |
try { | |
String stdOut = readBufRdr(new InputStreamReader(proc.getInputStream())); | |
String stdErr = readBufRdr(new InputStreamReader(proc.getErrorStream())); | |
if(logging) { | |
Log.i(TAG, "sbStdOut = " + stdOut); | |
Log.e(TAG, "sbStdErr = " + stdErr); | |
} | |
return stdOut + stdErr; | |
} catch(NullPointerException npe) { | |
npe.printStackTrace(); | |
} | |
return ""; | |
} | |
public String runCmd(String cmd) { | |
return executeCmd("/system/bin/sh", cmd); // or /bin/sh | |
} | |
public String runSuCmd(String cmd) { | |
return executeCmd("su", cmd); | |
} | |
private String readBufRdr(InputStreamReader isr) { | |
BufferedReader reader = new BufferedReader(isr); | |
StringBuilder found = new StringBuilder(); | |
String curLine = null; | |
String sep = System.getProperty("line.separator"); | |
try { | |
while((curLine = reader.readLine()) != null) { | |
found.append(curLine); | |
found.append(sep); | |
} | |
} catch (IOException ex) { | |
ex.printStackTrace(); | |
} finally { | |
try { | |
reader.close(); | |
} catch(IOException ex) { | |
ex.printStackTrace(); | |
} | |
} | |
return String.valueOf(found); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment