2011-07-31 110 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線程的幾秒鐘內禁用某些功能,我認爲最好不要等待過程結束。