Android 执行shell 命令

package com.haha.xixi;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.ArrayList;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.text.TextUtils;
import android.util.AndroidRuntimeException;



/**
 * 
 */
public class Cmd {
    public static final String RESULT_UNKNOW = "unknown";
    public static ArrayList<String> sSuPkgNames = new ArrayList<String>();
    static {
        // //
        sSuPkgNames.add("com.miui.uac");
    }

    private static final String DEFAULT_CHARSET = "utf-8";

    public static String findSuShellBin() {
        String pathStr = System.getenv("PATH");
        if (pathStr != null && pathStr.length() > 0) {
            String[] paths = pathStr.split(":");
            for (String path : paths) {
                File file = new File(path, "su");
                if (file.exists()) {
                    return file.getPath();
                }
            }
        }
        return null;
    }

    public static String findShShellBin() {
        String pathStr = System.getenv("PATH");
        if (pathStr != null && pathStr.length() > 0) {
            String[] paths = pathStr.split(":");
            for (String path : paths) {
                File file = new File(path, "sh");
                if (file.exists()) {
                    return file.getPath();
                }
            }
        }
        return null;
    }
    public static final String SU_SOCKET = "/dev/ddd/server";

    private static String readStrFromInputStream(InputStream in, String charset)
            throws IOException {
        final BufferedReader br = new BufferedReader(new InputStreamReader(in,
                charset));
        final char[] buf = new char[1024];
        int readed = 0;
        final StringBuilder builder = new StringBuilder();
        while ((readed = br.read(buf)) != -1) {
            builder.append(buf, 0, readed);
        }
        return (builder.length() > 0) ? builder.toString() : null;
    }

    public static String execForString(String cmd) {
        try {
            Process process = Runtime.getRuntime().exec(cmd);

            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    process.getInputStream()));
            int read;
            char[] buffer = new char[4096];
            StringBuffer output = new StringBuffer();
            while ((read = reader.read(buffer)) > 0) {
                output.append(buffer, 0, read);
            }
            reader.close();
            process.waitFor();
            return output.toString();

        } catch (IOException e) {
        } catch (InterruptedException e) {
        }
        return RESULT_UNKNOW;
    }

    public static String exec(File directory, String... cmd) {
        Process process = null;
        try {
            ProcessBuilder builder = new ProcessBuilder().command(cmd)
                    .redirectErrorStream(true).directory(directory);
            try {
                builder.environment().putAll(System.getenv());
            } catch (Exception e) {
            }
            process = builder.start();
            InputStream stdOut = process.getInputStream();
            String str = readStrFromInputStream(stdOut, DEFAULT_CHARSET);
            stdOut.close();
            if (str != null) {
                return str;
            } else {
                InputStream stdError = process.getErrorStream();
                return readStrFromInputStream(stdError, DEFAULT_CHARSET);
            }
        } catch (Exception e) {
            if (AppEnv.DEBUG) {
                e.printStackTrace();
            }
            // throw new RuntimeException(e);
        } finally {
            if (process != null) {
                process.destroy();
            }

        }
        return RESULT_UNKNOW;
    }

    public static void exec(String cmd) throws IOException {
        Process p = Runtime.getRuntime().exec(cmd);
        BufferedReader stdInput = new BufferedReader(new InputStreamReader(
                p.getInputStream()));
        String s;
        while ((s = stdInput.readLine()) != null) {
        }
        try {
            p.waitFor();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public static String execOnRoot(File directory, String... cmds)
            throws Exception {

        Process process = null;
        String su = findSuShellBin();
        if (su == null)
        {
            throw new Exception("The devices(" + Build.MODEL + ") has not rooted");
        }
        try
        {

            ProcessBuilder builder = new ProcessBuilder().command(su).redirectErrorStream(true).directory(directory);
            try
            {
                builder.environment().putAll(System.getenv());
            } catch (Exception e)
            {
                if (AppEnv.DEBUG)
                {
                    e.printStackTrace();
                }
            }
            process = builder.start();

            OutputStream stdIn = process.getOutputStream();
            InputStream stdOut = process.getInputStream();
            InputStream stdError = process.getErrorStream();

            for (String cmd : cmds)
            {
                if (AppEnv.DEBUG)
                {               
                    AssistLog.d("fu","cmd--" + cmd);
                }
                if (!cmd.endsWith("\n"))
                {
                    cmd += "\n";
                }
                stdIn.write(cmd.getBytes());
                stdIn.flush();
            }
            stdIn.write("exit\n".getBytes());
            stdIn.flush();
            stdIn.close();
            if (AppEnv.DEBUG)
            {               
                AssistLog.d("fu","readStrFromInputStream start");
            }
            String str = readStrFromInputStream(stdError, DEFAULT_CHARSET);
            if (AppEnv.DEBUG)
            {               
                AssistLog.d("fu","readStrFromInputStream end " + str);
            }
            if (TextUtils.isEmpty(str))
            {
                if (AppEnv.DEBUG)
                {               
                    AssistLog.d("fu","readStrFromInputStream empty start " + str);
                }
                str = readStrFromInputStream(stdOut, DEFAULT_CHARSET);
                if (AppEnv.DEBUG)
                {               
                    AssistLog.d("fu","readStrFromInputStream empty end " + str);
                }
            }
            process.waitFor();
            stdOut.close();
            stdError.close();
            if (AppEnv.DEBUG)
            {               
                AssistLog.d("fu","exit--" + str);
            }
            return str;
        } catch (Exception e)
        {
            if (AppEnv.DEBUG)
                e.printStackTrace();
            throw new AndroidRuntimeException(e);
        } finally
        {
            if (process != null)
            {
                try
                {
                    process.destroy();
                } catch (Exception e)
                {
                    if (AppEnv.DEBUG)
                        e.printStackTrace();
                }
            }
        }
    }

    public static boolean hasSuCmd() {
        try {
            return findSuShellBin() != null;
        } catch (Exception e) {
            return false;
        }
    }

    public static boolean hasSuApk(Context c) {
        try {
            PackageManager p = c.getPackageManager();
            for (String pkg : sSuPkgNames) {
                try {
                    PackageInfo info = p.getPackageInfo(pkg, 0);
                    if (info != null) {
                        return true;
                    }
                } catch (Exception e) {
                    continue;
                }
            }
            return false;
        } catch (Exception e) {
            return false;
        }
    }

    public static boolean isRoot() {
        try {
            String rootShell = findSuShellBin();
            if (rootShell == null) {
                return false;
            }
            String rtn = exec(new File("/"), rootShell, "-c", "id");
            if (TextUtils.isEmpty(rtn)) {
                return false;
            }
            return (-1 != rtn.indexOf("root"));
        } catch (Exception e) {
            return false;
        }
    }


    public static boolean tryReBoot() {
        try {
            Runtime.getRuntime()
                    .exec(new String[] { "su", "-c", "reboot now" });

            return true;
        } catch (Exception e) {
            AssistLog.d("Cmd", " Cmd tryReBoot() Exception=" + e.toString());
            if (AppEnv.DEBUG) {
                e.printStackTrace();
            }
        }
        return false;
    }   
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值