You can learn here how to execute shell commands as root and read output and errors
What you will need:
Eclipse with ADT plugin
Basic knowledge of java
Rooted android device
Note
Root commands should always be executed in background thread, you can use AsyncTask for example
I won't explain here how to use AsyncTask, maybe in another tut.
Also note that I'm a relative beginner myself so I won't use professional terms I'll try to explain in my own words, so I'm sorry in advance if you have no idea what I'm talking about
1. First thing that we need to do is open a new root shell like this:
Code:
Process process = Runtime.getRuntime().exec("su");
Make sure to destroy this process after finished
2. Open input output and error streams to write commands and read output
Code:
OutputStream stdin = process.getOutputStream();
stdin is used to write commands to shell. This is OutputStream, which means that using this stream we can execute command(like writing command in terminal)
Code:
InputStream stderr = process.getErrorStream();
InputStream stdout = process.getInputStream();
stderr and stdout are used to read output and error of a command which we executed.
3. Now we actually execute commands
Code:
stdin.write(("ls\n").getBytes());
//after you exec everything that you want exit shell
stdin.write("exit\n".getBytes());
"\n" at the end of the command means new line(like when you press enter in terminal). This is important, if you dont add new line it same like you didn't press enter
4. Flush and close OutputStream
Code:
stdin.flush(); //flush stream
stdin.close(); //close stream
5. Read output and error of a executed command
Code:
BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
while ((line = br.readLine()) != null) {
Log.d("[Output]", line);
}
br.close();
br =
new BufferedReader(new InputStreamReader(stderr));
while ((line = br.readLine()) != null) {
Log.e("[Error]", line);
}
br.close();
We read output and error (if any) line by line and write it to logcat
You can of course do anything with output(display in TextView for example)
6. Finally we destroy opened shell
Code:
process.waitFor();//wait for process to finish
process.destroy();
You need to handle InteruptedException and IOException.
Hope this helps someone. Again sorry for stupid explanations. I totally understand all this but English isn't my primary language so its a but hard to explain...
Here is whole code;
Code:
try {
String line;
Process process = Runtime.getRuntime().exec("su");
OutputStream stdin = process.getOutputStream();
InputStream stderr = process.getErrorStream();
InputStream stdout = process.getInputStream();
stdin.write(("ls\n").getBytes());
stdin.write("exit\n".getBytes());
stdin.flush();
stdin.close();
BufferedReader br =
new BufferedReader(new InputStreamReader(stdout));
while ((line = br.readLine()) != null) {
Log.d("[Output]", line);
}
br.close();
br =
new BufferedReader(new InputStreamReader(stderr));
while ((line = br.readLine()) != null) {
Log.e("[Error]", line);
}
br.close();
process.waitFor();
process.destroy();
} catch (Exception ex) {
}
Yea roottools is better solution, it handles opening shell for you, its easier, less code, and in my experience a little bit faster.
Here is an example:
Code:
Command command = new Command(0, "ls")
{
@Override
public void output(int id, String line)
{
// Handle output here
}
};
RootTools.getShell(true).add(command).waitForFinish();
And also do this when exiting application
Code:
RootTools.closeAllShells();
Sent from my Evo 3D GSM using Tapatalk 2
Everyone should read the How-To SU guide by Chainfire:
http://su.chainfire.eu/
Usable example code is on Github. In the meanwhile there's an interactive shell (like in RootTools) available too:
https://github.com/Chainfire/libsuperuser
I noticed that you called your InputStream stdout and your OutputStream stdin. Is there any reason that you chose to reverse the usual naming?
Great work but i would be delighted if op mentioned root commands and how to use them
octobclrnts said:
I noticed that you called your InputStream stdout and your OutputStream stdin. Is there any reason that you chose to reverse the usual naming?
Click to expand...
Click to collapse
Its confusing I know.
I'll try to explain
You use InputStream to read output of the shell so I called it stdout
Output of a shell/terminal is called stdout
You use OutputStream to write to shell(input to shell) so its stdin
Passing commands to terminal is stdin
It stands for standard output/input
More about stdin, stdout, stderr
http://en.m.wikipedia.org/wiki/Standard_streams
Sent from my Evo 3D GSM using Tapatalk 2
sak-venom1997 said:
Great work but i would be delighted if op mentioned root commands and how to use them
Click to expand...
Click to collapse
There is no such thing as root command.
commands can be executed as root user or as normal user.
Sent from my Evo 3D GSM using Tapatalk 2
pedja1 said:
There is no such thing as root command.
commands can be executed as root user or as normal user.
Sent from my Evo 3D GSM using Tapatalk 2
Click to expand...
Click to collapse
You didn't get me sir I ment the commands which run as root and how can developers utilize them
Sent from my GT-S5302 using Tapatalk 2
Hit Thanx Button if i helped you!
sak-venom1997 said:
You didn't get me sir I ment the commands which run as root and how can developers utilize them
Sent from my GT-S5302 using Tapatalk 2
Hit Thanx Button if i helped you!
Click to expand...
Click to collapse
I'm not really sure what you are asking. Any command can be executed as root.
Maybe you should read a bit about linux and shell
Sent from my Evo 3D GSM using Tapatalk 2
pedja1 said:
I'm not really sure what you are asking. Any command can be executed as root.
Maybe you should read a bit about linux and shell
Sent from my Evo 3D GSM using Tapatalk 2
Click to expand...
Click to collapse
No I was talking about the commands which require root to run like ifconfig
Sry for trouble I have no linux knowledge
Sent from my GT-S5302 using Tapatalk 2
Hit Thanx Button if i helped you!
sak-venom1997 said:
No I was talking about the commands which require root to run like ifconfig
Sry for trouble I have no linux knowledge
Sent from my GT-S5302 using Tapatalk 2
Hit Thanx Button if i helped you!
Click to expand...
Click to collapse
There are some commands that will just make sense as root. However, why should anyone write a tutorial about how to use some commands very few persons will need. Google "Linux command <what you want to do>" and you will find explanations. Many commands are just more flexible when executed like this.
I really recommend that. You will need it when you develop a root app. And you can use the adb shell! Great help.
@OP: What's about mentioning that you should use the busybox commands as the system's implementation of the shell commands differs from device to device and from ROM to ROM?
I also recommend RootTools. One of the best libraries in my opinion!
nikwen said:
.
@OP: What's about mentioning that you should use the busybox commands as the system's implementation of the shell commands differs from device to device and from ROM to ROM?
I also recommend RootTools. One of the best libraries in my opinion!
Click to expand...
Click to collapse
Purpose of this tutorial is to show how to execute commands as root, not how to use certain Linux commands.
And besides, using busybox is not always best solution, what if device doesn't have it installed, what if busybox doesn't have that command.
For example you would definitely not use "busybox echo" or "busybox ls".
Devs should already know how to use Linux, this is just to show how to do it from java.
Sent from my Evo 3D GSM using Tapatalk 2
pedja1 said:
Purpose of this tutorial is to show how to execute commands as root, not how to use certain Linux commands.
And besides, using busybox is not always best solution, what if device doesn't have it installed, what if busybox doesn't have that command.
For example you would definitely not use "busybox echo" or "busybox ls".
Click to expand...
Click to collapse
You are right. It is true that nobody would use busybox for very simple commands.
However, RootTools has the RootTools.offerBusyBox(Activity activity) Method which opens Google Play to download a busybox installer.
Devs should already know how to use Linux, this is just to show how to do it from java.
Sent from my Evo 3D GSM using Tapatalk 2
Click to expand...
Click to collapse
I understood what you wanted to do.
Great job, btw. Would have been glad if I had had this when I started with root apps.
Great Work!!!
I found how to execute root commands before. But this post has the best explanation. Thanks a lot!
pedja1 said:
Purpose of this tutorial is to show how to execute commands as root, not how to use certain Linux commands.
And besides, using busybox is not always best solution, what if device doesn't have it installed, what if busybox doesn't have that command.
For example you would definitely not use "busybox echo" or "busybox ls".
Devs should already know how to use Linux, this is just to show how to do it from java.
Sent from my Evo 3D GSM using Tapatalk 2
Click to expand...
Click to collapse
I once did run into troubles parsing the results of "ls" command. Usually 'ls' is just the short table-style list, while you could get all the details with 'ls -l'. This is what I needed. But when testing on the Motorola Milestone unfortunately 'ls' was sym-linked to 'ls -l', therefore calling 'ls -l' would result in an error message. Don't know if more devices act like that (didn't test on any other Motorola phones, and the Milestone is quite old by now), but maybe it still makes sense to use busybox for 'normal' command in some cases...
Hello,
I am trying to run a script kept in my assests folder of my app. It is Root.sh which contains -
Code:
su
cd system
mkdir abcdjdj
This is my java code:-
Code:
String path = "file:///android_asset/Root.sh";
Process p = new ProcessBuilder().command(path).start();
But now I get a runtime error -
Code:
04-22 15:08:03.144: E/AndroidRuntime(785): Caused by: java.io.IOException: Error running exec(). Command: [file:///android_asset/Root.sh] Working Directory: null Environment: [ANDROID_SOCKET_zygote=9, ANDROID_STORAGE=/storage, ANDROID_BOOTLOGO=1, EXTERNAL_STORAGE=/mnt/sdcard, ANDROID_ASSETS=/system/app, PATH=/sbin:/vendor/bin:/system/sbin:/system/bin:/system/xbin, ASEC_MOUNTPOINT=/mnt/asec, LOOP_MOUNTPOINT=/mnt/obb, BOOTCLASSPATH=/system/framework/core.jar:/system/framework/core-junit.jar:/system/framework/bouncycastle.jar:/system/framework/ext.jar:/system/framework/framework.jar:/system/framework/telephony-common.jar:/system/framework/mms-common.jar:/system/framework/android.policy.jar:/system/framework/services.jar:/system/framework/apache-xml.jar, ANDROID_DATA=/data, LD_LIBRARY_PATH=/vendor/lib:/system/lib, ANDROID_ROOT=/system, ANDROID_PROPERTY_WORKSPACE=8,32768]
Can anyone please help me?
Thanks.
abcdjdj said:
Hello,
I am trying to run a script kept in my assests folder of my app. It is Root.sh which contains -
Code:
su
cd system
mkdir abcdjdj
This is my java code:-
Code:
String path = "file:///android_asset/Root.sh";
Process p = new ProcessBuilder().command(path).start();
But now I get a runtime error -
Code:
04-22 15:08:03.144: E/AndroidRuntime(785): Caused by: java.io.IOException: Error running exec(). Command: [file:///android_asset/Root.sh] Working Directory: null Environment: [ANDROID_SOCKET_zygote=9, ANDROID_STORAGE=/storage, ANDROID_BOOTLOGO=1, EXTERNAL_STORAGE=/mnt/sdcard, ANDROID_ASSETS=/system/app, PATH=/sbin:/vendor/bin:/system/sbin:/system/bin:/system/xbin, ASEC_MOUNTPOINT=/mnt/asec, LOOP_MOUNTPOINT=/mnt/obb, BOOTCLASSPATH=/system/framework/core.jar:/system/framework/core-junit.jar:/system/framework/bouncycastle.jar:/system/framework/ext.jar:/system/framework/framework.jar:/system/framework/telephony-common.jar:/system/framework/mms-common.jar:/system/framework/android.policy.jar:/system/framework/services.jar:/system/framework/apache-xml.jar, ANDROID_DATA=/data, LD_LIBRARY_PATH=/vendor/lib:/system/lib, ANDROID_ROOT=/system, ANDROID_PROPERTY_WORKSPACE=8,32768]
Can anyone please help me?
Thanks.
Click to expand...
Click to collapse
Why don't you do it this way?
Code:
Runtime.getRuntime().exec("su", "-c", "cd system; mkdir abcdjdj");
Note that you need to pass the commands you want to execute to the command method, not the path.
nikwen said:
Why don't you do it this way?
Code:
Runtime.getRuntime().exec("su", "-c", "cd system; mkdir abcdjdj");
Note that you need to pass the commands you want to execute to the command method, not the path.
Click to expand...
Click to collapse
It gives a syntax error. I guess it should have been - Runtime.getRuntime().exec(new String[] { "su", "-c", "cd system; mkdir abcdjdj" });
It runs fine on my phone but I still don't see a folder called abcdjdj is /system
abcdjdj said:
It gives a syntax error. I guess it should have been - Runtime.getRuntime().exec(new String[] { "su", "-c", "cd system; mkdir abcdjdj" });
It runs fine on my phone but I still don't see a folder called abcdjdj is /system
Click to expand...
Click to collapse
You are right, it should have been that.
Try to add the full path:
Code:
Runtime runtime = Runtime.getRuntime();
try {
runtime.exec(new String[] {"su", "-c", "mkdir /system/abcdef"});
runtime.exec(new String[] {"su", "-c", "mkdir /system/aaab; mkdir /system/aaac"});
} catch (IOException e) {
e.printStackTrace();
}
I think that executing your first idea should work if you execute
Code:
runtime.exec("su");
and then write the commands to the outputstream as described in the first post of this thread.
---------- Post added at 06:13 PM ---------- Previous post was at 06:06 PM ----------
However, I recommend using roottools.
If you need to execute commands rarely it will be fine that way, but if you need to execute commands often, there will be annoying Toast messages every time. Using roottools, there will be such a message just once when the app requests SU rigths for the first time after the launch.
Ichigo said:
Yes, root tools is a great alternative. I use it a lot in my app. If you want, check my github for examples.
Click to expand...
Click to collapse
For a very basic tutorial, check this: http://code.google.com/p/roottools/wiki/Usage
I am trying to install an APK using a simple Java application, the file is local to my (Linux) pc and the tablet is connected via USB.
If I run this command with adb then the apk installs fine:
adb install -r /home/apk.apk
So I know the apk file is valid and works fine.
The Java application is giving me java.nio.bufferoverflowexeception errors, the apk is fairly large at 700Mb but it pushes and installs fine from the terminal.
The code I am using is:
Code:
public void wiredsyncapk(){
abdsourcesync = apkpath;
progress.setString("Sync in progress");
System.out.println("Starting Sync via adb with command " + "adb" + " install -r "+ apkpath);
Process process = Runtime.getRuntime().exec("adb" + " install -r "+ apkpath);
InputStreamReader reader = new InputStreamReader(process.getInputStream());
Scanner scanner = new Scanner(reader);
scanner.close();
int exitCode = process.waitFor();
System.out.println("Process returned: " + exitCode);
if (exitCode==1){
System.out.println("an error has occured!");
}else{
System.out.println("it all worked fine");
}
} catch(IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
How can I fix the bufferoverflow issue? I have searched and searched but not found a simple way to set a large buffer.
Thanks for the help;
Andy
where is it overflowing at? a logcat should tell this info.
zalez said:
where is it overflowing at? a logcat should tell this info.
Click to expand...
Click to collapse
Yep, logcat, please.