---
title: "ShellCommand.java"
author: "fonter"
date: "2011-04-07T19:38:46Z"
tags: []
categories: ["移动开发"]
slug: "shellcommand-java"
draft: false
lastmod: "2011-04-07T19:38:46Z"
id: 990977
url: "https://fonter.iteye.com/blog/990977"
---

/\**  
 * ShellCommand.java runs commands as if in a native shell instance, and can return stdio.  
 *  
 * Code by Kevin(at)TeslaCoil  
 * Adapted by LouZiffer(at)SDX  
 *  
 * Example usage (use cmd.su.runWaitFor instead of cmd.sh.runWaitFor to run as su):  
 *  
 * ShellCommand cmd = new ShellCommand();  
 * CommandResult r = cmd.sh.runWaitFor("/system/bin/getprop wifi.interface");  
 *  
 * if (!r.success()) {  
 *     Log.d(MSG\_TAG, "Error " + r.stderr);  
 * } else {  
 *     Log.d(MSG\_TAG, "Successfully executed getprop wifi.interface. Result: " + r.stdout);  
 *     this.tetherNetworkDevice = (r.stdout);  
 * }  
 \*/

package m900.tether.system;  
import java.io.DataInputStream;  
import java.io.DataOutputStream;  
import java.io.InputStream;

import android.util.Log;

public class ShellCommand {  
    private static final String TAG = "ShellCommand.java";  
    private Boolean can\_su;   

    public SH sh;  
    public SH su;  
     
    public ShellCommand() {  
        sh = new SH("sh");  
        su = new SH("su");  
    }  
     
    public boolean canSU() {  
        return canSU(false);  
    }  
     
    public boolean canSU(boolean force\_check) {  
        if (can\_su == null || force\_check) {  
            CommandResult r = su.runWaitFor("id");  
            StringBuilder out = new StringBuilder();  
             
            if (r.stdout != null)  
                out.append(r.stdout).append(" ; ");  
            if (r.stderr != null)  
                out.append(r.stderr);  
             
            Log.v(TAG, "canSU() su\[" + r.exit\_value + "]: " + out);  
            can\_su = r.success();  
        }  
        return can\_su;  
    }

    public SH suOrSH() {  
        return canSU() ? su : sh;  
    }  
     
    public class CommandResult {  
        public final String stdout;  
        public final String stderr;  
        public final Integer exit\_value;  
         
        CommandResult(Integer exit\_value\_in, String stdout\_in, String stderr\_in)  
        {  
            exit\_value = exit\_value\_in;  
            stdout = stdout\_in;  
            stderr = stderr\_in;  
        }  
         
        CommandResult(Integer exit\_value\_in) {  
            this(exit\_value\_in, null, null);  
        }  
         
        public boolean success() {  
            return exit\_value != null && exit\_value == 0;  
        }  
    }

    public class SH {  
        private String SHELL = "sh";

        public SH(String SHELL\_in) {  
            SHELL = SHELL\_in;  
        }

        public Process run(String s) {  
            Process process = null;  
            try {  
                process = Runtime.getRuntime().exec(SHELL);  
                DataOutputStream toProcess = new DataOutputStream(process.getOutputStream());  
                toProcess.writeBytes("exec " + s + "\\n");  
                toProcess.flush();  
            } catch(Exception e) {  
                Log.e(TAG, "Exception while trying to run: '" + s + "' " + e.getMessage());  
                process = null;  
            }  
            return process;  
        }  
         
        private String getStreamLines(InputStream is) {  
            String out = null;  
            StringBuffer buffer = null;  
            DataInputStream dis = new DataInputStream(is);

            try {  
                if (dis.available() &gt; 0) {  
                    buffer = new StringBuffer(dis.readLine());  
                    while(dis.available() &gt; 0)  
                        buffer.append("\\n").append(dis.readLine());  
                }  
                dis.close();  
            } catch (Exception ex) {  
                Log.e(TAG, ex.getMessage());  
            }  
            if (buffer != null)  
                out = buffer.toString();  
            return out;  
        }

        public CommandResult runWaitFor(String s) {  
            Process process = run(s);  
            Integer exit\_value = null;  
            String stdout = null;  
            String stderr = null;  
            if (process != null) {  
                try {  
                    exit\_value = process.waitFor();  
                     
                    stdout = getStreamLines(process.getInputStream());  
                    stderr = getStreamLines(process.getErrorStream());  
                     
                } catch(InterruptedException e) {  
                    Log.e(TAG, "runWaitFor " + e.toString());  
                } catch(NullPointerException e) {  
                    Log.e(TAG, "runWaitFor " + e.toString());  
                }  
            }  
            return new CommandResult(exit\_value, stdout, stderr);  
        }  
    }  
}