2011-07-31 198 views
0

我想通过我的代码在Iptables中添加条目来执行shell命令。以下是我的一段代码如何在android中执行shell命令?

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"); 
    } 
} 

这里有两种方法即,createshellCommand()用于构建外壳命令和writeIptables()用于更新的iptables。但每当我运行该程序的logcat正在显示以下警告

“W 19913苏请求拒绝(0-> 0 /系统/ bin/sh的)”

但我可以手动添加通过命令提示的入口和它添加到iptables,但通过使用上面的代码,它不更新。我的手机已经植根,我正在使用Android 2.3.4和Linux内核2.6.29。我正在使用外部库“Roottools”来检查根访问权限。

请帮我纠正错误。

回答

4

这个工程:

protected void onCreate(Bundle savedInstanceState) 
{ 
    super.onCreate(savedInstanceState); 
    execute_reboot(); 

} 
void execute_reboot() 
{ 
    Process reboot; 
    try { 
     reboot=Runtime.getRuntime().exec("su"); 
      DataOutputStream os = 
       new DataOutputStream(reboot.getOutputStream()); 
      os.writeBytes("reboot\n"); 
      os.flush(); 

       os.writeBytes("exit\n"); 
       os.flush(); 

      reboot.waitFor(); 

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

此代码工作正常。你的程序中有几个小错误。试试我粘贴的那个。它的工作魅力。祝一切顺利。我尽可能保持简单,以便于理解。你仍然可以使用数组和其他东西来欣赏你的编码。

而yaa同样适用于chmod命令,您需要传递多个参数。

对于此只需更换

“os.writeBytes(” 重新启动\ n “);”

“搭配chmod 777的/ dev/video0的\ n” 个(或任何其它系统文件)。

谢谢。让我知道是否有什么我可以做的事情。

+0

感谢您的建议... – Unnikrishnan

0

尝试使用iptables命令(使用sudo而不使用),而不是仅仅关闭iptables配置文件。

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

这一个是多了几分紧凑

您可以添加 “proc.waitFor();”在Process proc ...行后面摆脱未使用的警告,但重新启动设备需要几秒钟的时间,如果您想在UI线程的几秒钟内禁用某些功能,我认为最好不要等待过程结束。