java执行root shell命令

    private static String runRootShell(String[] cmds){    
    
        String result = null;
        int ret = -1;
        java.lang.Process process;    
        try {
            process = Runtime.getRuntime().exec("su");
            DataOutputStream os = new DataOutputStream(process.getOutputStream());
            for(int i=0; i< cmds.length; i++) {
                os.writeBytes(cmds[i] + "\n");
            }
            os.writeBytes("exit\n");
            os.flush();
            try {
                ret = process.waitFor();
                Log.d("lx", "ret= " + ret);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            os.close();
            
            ByteArrayOutputStream resultOutStream = new ByteArrayOutputStream();
            InputStream errorInStream = new BufferedInputStream(process.getErrorStream());
            InputStream processInStream = new BufferedInputStream(process.getInputStream());
            int num = 0;
            
            byte[] bs = new byte[1024];

            while((num=errorInStream.read(bs))!=-1){

                resultOutStream.write(bs,0,num);

            }

            while((num=processInStream.read(bs))!=-1){

                resultOutStream.write(bs,0,num);

           }

            result=new String(resultOutStream.toByteArray());

            println( "result: " + result);

            errorInStream.close();
            errorInStream=null;

            processInStream.close();
            processInStream=null;

            resultOutStream.close();
            resultOutStream=null;
    
            
        } catch (IOException e) {
            // TODO Auto-generated catch block
            //e.printStackTrace();
        }
        
        
         result =  "result code: " + ret + " details: " +result;
        return result;    
    } 



 // 执行示例

runRootShell(new String[]{"rm -r /data/data/test",
                    "ls", "ls"});



PS:

InputStreamReader ir = new InputStreamReader(process .getInputStream());   
LineNumberReader input = new LineNumberReader(ir);  

 int ret = process.waitFor();

while ((line = input.readLine()) != null){ 

    println("result: " + line);
}


看到网上很多人采用上面的方法获取shell执行结果。 实际测试后发现有很多情况下readLine()并不会被执行,或者也并不能完全返回执行结果。


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值