How to Executing Shell commands through android app? - android

Firstly I'm new to Android.
How to execute the following shell command
echo "1" > /sys/devices/enable
in an android app.
I referred many link's but I didn't get the solution.
Is there any permission that I should mention in the manifest file to execute the shell commands in the app???.
Thanks in advance.

try{
Process process;
process = Runtime.getRuntime().exec("echo "1" > /sys/devices/enable");
BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}

Why not write in Java?
try{
FileWriter fw = new FileWriter(new File("/sys/devices/enable"));
fw.write('1');
fw.close();
}catch(IOExceprion e){}
If you really want to invoke a shell, try this:
Runtime rt = Runtime.getRuntime();
Process p = rt.exec(new String[]{"/system/bin/sh", "-c", "echo \"1\" > /sys/devices/enable");
Make sure your device is rooted first before trying any of the above mentioned approaches.

Related

How to run .sh file from android app?

My device has been rooted and now i want to run an .sh file from my android application. I tried with following code but it did't provide the intended output:
Process process = Runtime.getRuntime().exec("sh /data/local/tmp/xyz.sh");
If i run .sh file from adb it is working fine for me.
Try following code.
try{
Process root = Runtime.getRuntime().exec("su");
DataOutputStream os = new DataOutputStream(root.getOutputStream());
os.writeBytes("sh /system/bin/xyz.sh \n");
os.flush();
}
catch (IOException e) {
e.printStackTrace();
}
catch (SecurityException se){
se.printStackTrace();
}
This snippet worked for me,I hope this may help you.
Process process = Runtime.getRuntime().exec("sh /data/local/tmp/xyz.sh");
Scanner stdout = new Scanner(process.getInputStream());
while (stdout.hasNextLine()) {
Log.i("stdout", stdout.nextLine());
}
stdout.close();
Scanner stderr = new Scanner(process.getErrorStream());
while (stderr.hasNextLine()) {
Log.e("stderr", stderr.nextLine());
}
stderr.close();

Starting adb logs on internal storage without going into the shell

I am trying to start internal logs within my android devices without having to go directly into the adb shell. I have to script this process so I can run it from a program.
I am aware that you can take the following steps to start internal logs on an android device:
Open a cmd prompt
enter 'adb shell'
enter 'logcat -v time -f /sdcard/LogFile.txt&'
The above will start a logcat process within the actual device. I can now unplug my phone from the computer and move around then come back and collect the logs once my test is complete. It's crucial that I am able to start this process and be able to unplug my device with the logs still running.
To my knowledge running 'adb shell' in front of any command would run as if it were in the shell. Therefore by this logic I tried running:
Method 1:
'adb shell logcat -v time -f /sdcard/LogFile.txt&'
This command did properly start the log on the device which is great. However, once I unplug from my computer the logcat process stops.
Method 2:
'adb shell "logcat -v time -f /sdcard/LogFile.txt&" '
This didn't seem to do anything at all on the phone and I don't know why.
Method 3
I have tried the scripting method as well where I run a Batch file that contains only:
'adb shell < Commands.txt'
Where commands has the single line:
'logcat -v time -f /sdcard/LogFile.txt&'
This doesn't appear to do anything. It appears to send the command once the window comes up but doesn't actually perform the action.
Any help on this topic would be greatly appreciated. Thanks.
you can use this code in application class. so when app will launch this code will start executing. and it will create new log file according to current time.
Thread t = new Thread(new Runnable() {
public void run() {
while (collectLog == true) {
try {
Thread.sleep(1000 * 60 * 6);
StringBuilder log = null;
Date now = new Date();
String fileName = formatter.format(now);
File file = new File(dir, fileName + "_logcat2.txt");
try {
Process process = Runtime.getRuntime().exec("logcat -d");// d will dump logs
//Process process = Runtime.getRuntime().exec("logcat -c"); c will clear logs
// process = Runtime.getRuntime().exec("logcat -f " + file);
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
log = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
log.append(line);
log.append("\n");
}
} catch (IOException e) {
}
try {
//to write logcat in text file
FileOutputStream fOut = new FileOutputStream(file);
OutputStreamWriter osw = new OutputStreamWriter(fOut)
// Write the string to the file
osw.append(log.toString());
osw.flush();
osw.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
t.start();

execute pipes command in android?

I want to display application logs.
On terminal I used this command: adb logcat -s brief *:V|grep "pid"
It's display My Application logs.
pid means application pid which is display in logcat table.
public static String logProc()
{
String value = "";
try
{
String cmd[] = {"logcat","-s","brief","*:V","|","grep",
android.os.Process.myPid()+""};
Process p = Runtime.getRuntime().exec(cmd,null, null);
BufferedReader reader = new BufferedReader(new
InputStreamReader(p.getInputStream()));
String line = reader.readLine();
while (line != null)
{
value += line + "\n";
line = reader.readLine();
}
p.waitFor();
}
catch (IOException e1)
{
e1.printStackTrace();
}
catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return value;
}
Most official Android builds do not come with grep (Edit: more recent releases now do)
You can install busybox if you want extra commands - without root you would have to put it in an alternate location.
You have the additional problem that you are trying to exec() a shell command to connect two programs via pipes, which isn't going to work unless you exec a shell interpreter and give it that command. Or you could set up the pipe yourself and exec both programs.
But since you are writing a program, it would probably be simpler to do your pattern matching in the java code.

Syntax for shell command in Android app

I am trying to run
String command = "su -c 'busybox ls /data'";
p = Runtime.getRuntime().exec(command);
in my app, but it seems like the syntax is somehow wrong. I have no problem running it from the terminal emulator app on the phone, though, so I just can't understand why it is not working when called from within my app.
Any help is deeply appreciated!
SOLUTION FOUND! Thanks to the link suggested by onit here. See the code below: for superuser shell commands to work properly, you first need to create a superuser shell and assign it to a process, then write and read on it's input and output streams respectively.
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
Use the function below:
public void shellCommandRunAsRoot(String Command)
{
try
{
Process RunProcess= Runtime.getRuntime().exec("su");
DataOutputStream os;
os = new DataOutputStream(RunProcess.getOutputStream());
os.writeBytes(cmds+"\n");
os.writeBytes("exit+\n");
os.flush();
}
catch (IOException e)
{
// Handle Exception
}
}
Usage:
shellCommandRunAsRoot("pkill firefox");

Running shell commands from app [Rooted]

In my app, I want to run few shell command sand interpret the output. These commands are essentially the on that would run on rooted phone.
How do I do it?
First make sure that the shell command that you need is actually available in Android. I've run into issues by assuming you can do things like redirect output with >.
This method also works on non-rooted phones of I believe v2.2, but you should check the API reference to be sure.
try {
Process chmod = Runtime.getRuntime().exec("/system/bin/chmod 777 " +fileName);
BufferedReader reader = new BufferedReader(
new InputStreamReader(nfiq.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();
chmod.waitFor();
outputString = output.toString();
} catch (IOException e) {
throw new RuntimeException(e);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
While it's probably not 100% necessary, it's a good idea to have the process wait for the exec to complete with process.waitFor() since you said that you care about the output.
You need to first ensure you have busybox installed as that would install the list of most commonly used shell commands and then use the following code to run the command.
Runtime.getRuntime().exec("ls");

Categories

Resources