How to execute shell commands in android?

I am trying to execute shell command through my code for adding entry in Iptables. The following is my piece of code

private void createShellCommand(String uidValue_param, String interface_param) { // TODO Auto-generated method stub StringBuilder cmdScript=new StringBuilder(); script.append("iptables -A OUTPUT " + interface_param + "-m owner --uid-owner " + uidValue_param + "-j REJECT"); writeIptables(cmdScript); } private void writeIptables(StringBuilder scriptfile) { // TODO Auto-generated method stub String cmd=scriptfile.toString(); if(RootTools.isRootAvailable()) { Process exec; try { exec = Runtime.getRuntime().exec(new String[]{"su","-c"}); final OutputStreamWriter out = new OutputStreamWriter(exec.getOutputStream()); out.write(cmd); // Terminating the "su" session out.write("exit\n"); out.flush(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); Log.e("IPtables updation failed", "Iptable write failed"+e); } } else { Log.e("Root Access denied", "Access Denied"); } }

Here there are two methods i.e, createshellCommand() for building the shell command and writeIptables() for updating the iptables. But whenever I run the program logcat is displaying the following warning

"W 19913 su request rejected (0->0 /system/bin/sh)"

But I can manually add the entry through command prompt and its adding to the iptables but by using the above code its not updating. My phone is rooted and I am using android 2.3.4 with linux kernel 2.6.29. And I am using external library "Roottools" for checking the root access.

Please help me to rectify the error.

-------------Problems Reply------------

This Works:

protected void onCreate(Bundle savedInstanceState)

void execute_reboot()
Process reboot;
try {
DataOutputStream os =
new DataOutputStream(reboot.getOutputStream());



} catch (IOException e) {
// TODO Auto-generated catch block
} catch (InterruptedException e) {
// TODO Auto-generated catch block

This Code Works fine. There are couple of small mistakes in your program. Try the one i pasted. Its working charm. All the best. I kept it as simple as possible so that it is easy to understand. You can still use arrays and other stuff to fancy your coding.

And yaa the same one also works for chmod command where you need to pass more than one argument.

For this Just replace



"chmod 777 /dev/video0\n"(or any other system file).

Thanks. LEt me know if there is something tat i can do.

Trying using the iptables command (with sudo and without), rather than just clobbering the iptables config file.

public static void rebootNow() {
Log.d(TAG, "Rebooting");
try {
Process proc = Runtime.getRuntime().exec(
new String[] { "su", "-c", "reboot" });
} catch (Exception ex) {
Log.d(TAG, "Rebooting failed (Terminal Error)");

This one is a little more compact

You can add "proc.waitFor();" after the Process proc... line to get rid of the unused warning, but rebooting your device takes a few seconds time and if you want to disable some features during the few seconds in your UI-thread, I think its better to not wait for the process to end.

Category:android Views:4 Time:2011-07-31
Tags: shell android

Related post

  • CTS_ERROR >>> Failed to execute shell command am instrument 2010-11-29

    Using the Android 2.2, API-8, SDK-r7 along with CTS-2.2_r4 suite. Updated the SDK_ROOT environment variable with SDK_r7 tools in “android-cts/tools/startcts” script and the “SDK_ROOT/tools” also included in PATH environment variable. Ran the “android

  • How to get error message of a failed shell command on android 2012-02-02

    On a rooted android device, I tried to run a cat command that read kernel log, as follow: Process p = Runtime.getRuntime().exec("su"); p = Runtime.getRuntime().exec("/system/bin/cat /proc/kmsg"); The su command was successfully executed but not the c

  • Execute shell command from within MySQL client? 2009-05-30

    In oracle database, command "host" can be used to run bash command from database command window. Is there a equivalent command as "host" in mySql? --------------Solutions------------- You can use the system command. system command, \! command Execute

  • Executing shell commands using PHP, e.g. shell_exec() etc., on a remote host? 2010-09-19

    Is it possible to execute shell commands on a remote computer (not localhost)? For instance things like $output = shell_exec("unzip"); You can assume that you have the login credentials of a user account on the remote machine, as well as

  • Executing shell command from ruby console returning Permission Denied Error? 2011-03-28

    Getting permission denied error while executing shell command from ruby console. And the same shell command is working from shell. From Shell.. [email protected]:~$ "`grep '^datadir=' /etc/mysql/my.cnf | cut -f 2 -d '='`/db_backups" bash: /db_b

  • How to execute shell command in C? 2011-05-12

    I am having problems executing the shell commands in C. I want to execute a shell command in C then capture the output of shell command and process the output further. I used following code to perform the functionality. But, the issue is when the she

  • Execute shell command in c++ 2011-08-29

    I have a question regarding executing shell commands in c++. I'm building an application in winforms, vs 2008. My application has a button, when clicked should decode a binary file to a .csv file. I can decode files by first going to the right direct

  • python: os.system does not execute shell command 2012-03-02

    I need to execute shell command in python program (I have ubuntu). More specifically I want to create graph using graphviz in python script. My code is os.system("dot -Tpng -o graph.png") It does not work, but if I just type "dot -Tpng grap

  • php executing shell command gives random output in only in heavy use mode 2012-03-28

    Please help me with this issue that I am facing on production server. I launched an application that saves images in a directory only after checking that it does not already exist. To check if it already exists I used the following command find $file

  • How can I execute all the possible unix(shell) commands in android programmatically? 2012-04-24

    I have this .php file sending commands to my android application: I have tried working with: Runtime.getRuntime().exec(commandLine); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream())); but the commands

  • Execute multiple root shell commands in Android 2014-11-09

    I'm developing an application that execute multiple shell command in different time. I'm using the following method: public void RunAsRoot(String[] cmds){ Process p = Runtime.getRuntime().exec("su"); DataOutputStream os = new DataOutputStream(p.getOu

  • Run shell commands from android program 2011-09-16

    This question has been asked here before but the solutions provided are not working..I am trying to display the contents of /data/dalvik-cache folder. I know that to do this we need to become su. I even did that but still i am unable to execute a she

  • Issue while executing adb command in android applicaiton 2012-01-06

    I am having problem in executing adb commands with in application in android mobile, It is showing environment error for the command. Can any one please lookinto this and suggest the correct way to execute the command with application. below is the c

  • Executing shell commands programmatically 2012-01-28

    I want to execute this shell commands by program. How can I do it? cd C:\android-sdk\platform-tools adb shell su mount -t rfs -o remount,rw /dev/block/stl9 /system cp /sdcard/MyApp.apk /system/app/MyApp.apk --------------Solutions------------- You Sh

  • Groovy executing shell commands 2008-10-01

    Groovy adds the execute method to String to make executing shells fairly easy; println "ls".execute().text but if an error happens, then there is no resulting output. Is there an easy way to get both the standard error and standard out? (other than c

  • Executing shell command from MySQL 2008-11-14

    I know what I'm looking for is probably a security hole, but since I managed to do it in Oracle and SQL Server, I'll give it a shot: I'm looking for a way to execute a shell command from a SQL script on MySQL. It is possible to create and use a new s

  • PHP exec() will not execute shell command when executed via browser 2009-02-11

    I have a certain PHP script that calls exec() to execute a command to convert a PDF to JPG. This command works fine in bash. To preempt your initial troubleshooting guesses, note the following: safe_mode = Off Permission on the directory containing t

  • vim: execute shell command without filtering 2009-08-06

    I want to select a block of text (eg. V%) and use the text as input to a shell command (eg. wc or pbcopy) - but I DON'T want to alter the current buffer - I just want to see the output of the command (if any) the continue editting without any changes

  • How to execute shell command in Javascript 2009-12-10

    I want to write a javascript function which will execute the system shell commands (ls for example) and return the value. How do I achieve this? --------------Solutions------------- What if the client you are executing this javascript is running Wind

Copyright (C), All Rights Reserved.

processed in 0.165 (s). 11 q(s)