Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

在 Android 應用中部署自訂 su 的實作

編輯:關於 Android 程式設計

本文延續自訂 su 的主題,說明如何在一個普通應用程式中,把自己編譯好的 su 部署到系統裡並加以運用。為了和系統自帶的 su 區分,這裡把自己的 su 命名為 sur(本文未考慮 x86 架構的手機)。

首先把自訂的 sur 放到應用工程的 assets 目錄。接著透過工具類完成部署與呼叫,關鍵在於利用系統原本的 su 取得 root 後,把 assets 裡的 sur 複製到 /system/xbin,並設定好擁有者與權限。

Util.java

這個類負責把 assets 中的 sur 釋放到內部儲存,再以 root 權限 remount /system 為可寫、複製檔案、chown 與 chmod 6777,最後把 /system 重掛為唯讀:

package cdut.robin.root.utils;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import android.content.Context;
import android.util.Log;
public class Util {
    final static String kSysSuPath = "/system/xbin/sur";
    private static String getDeployMySuShellScript(String localSuPath) {
        StringBuffer strBuffer = new StringBuffer();
        strBuffer.append("mount -o remount,rw " + MountPoint.getDeviceName("/system") + " /system");
        strBuffer.append("\n");
        strBuffer.append("mount -o remount,rw /system /system");
        strBuffer.append("\n");
        strBuffer.append("cat ").append(localSuPath).append("> " + kSysSuPath);
        strBuffer.append("\n");
        strBuffer.append("chown 0:0 " + kSysSuPath);
        strBuffer.append("\n");
        strBuffer.append("chmod 6777 " + kSysSuPath);
        strBuffer.append("\n");
        strBuffer.append("mount -o remount,ro " + MountPoint.getDeviceName("/system") + " /system");
        strBuffer.append("\n");
        strBuffer.append("mount -o remount,ro /system /system");
        strBuffer.append("\n");
        return strBuffer.toString();
    }
    private static boolean isMySuExists() {
        return new File(kSysSuPath).exists();
    }
    private static boolean writeMySu(Context context) {
        Process processShell = null;
        DataOutputStream osShell = null;
        String mySuTempPath = context.getFilesDir().getPath() + "/sur";
        File file = new File(mySuTempPath);
        if (file.exists()) {
            file.delete();
        }
        InputStream open = null;
        FileOutputStream out = null;
        try {
            open = context.getResources().getAssets().open("sur");
            out = context.openFileOutput("sur", Context.MODE_WORLD_WRITEABLE);
            byte buffer[] = new byte[4 * 1024];
            int len = 0;
            while ((len = open.read(buffer)) != -1) {
                out.write(buffer, 0, len);
            }
            out.flush();
        } catch (IOException e) {
            Log.e("TAG", "errMessage" + e.getMessage());
        } finally {
            if (out != null) {
                try {
                    out.close();
                    if (open != null) open.close();
                } catch (Exception e) { }
            }
        }
        Runtime runTime = Runtime.getRuntime();
        try {
            processShell = runTime.exec("su");
            osShell = new DataOutputStream(processShell.getOutputStream());
            String str = getDeployMySuShellScript(mySuTempPath);
            osShell.writeBytes(str);
            osShell.writeBytes("exit\n");
            osShell.flush();
            processShell.waitFor();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            if (processShell != null) {
                try { processShell.destroy(); } catch (Exception e) { }
                processShell = null;
            }
            if (osShell != null) {
                try { osShell.close(); osShell = null; } catch (IOException e1) { }
            }
        }
        return new File(kSysSuPath).exists();
    }
    public static boolean doSthBySu(Context context) {
        if (!isMySuExists()) {
            boolean res = writeMySu(context);
            Log.i("robin", res ? "deploy My Su success!" : "deploy My Su fail!");
        }
        Process processShell = null;
        DataOutputStream osShell = null;
        try {
            Runtime runTime = Runtime.getRuntime();
            processShell = runTime.exec("sur");
            osShell = new DataOutputStream(processShell.getOutputStream());
            String str = getBussinessShellScript();
            osShell.writeBytes(str);
            osShell.writeBytes("exit\n");
            osShell.flush();
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            if (processShell != null) {
                try { processShell.destroy(); } catch (Exception e) { }
                processShell = null;
            }
            if (osShell != null) {
                try { osShell.close(); osShell = null; } catch (IOException e1) { }
            }
        }
        return true;
    }
    public static String getBussinessShellScript() {
        return "echo hello";
    }
}

MountPoint.java

這個輔助類在靜態區塊中讀取 /proc/mounts,快取掛載點與裝置名的對應關係,供上面的腳本判斷 /system 的實際裝置名:

package cdut.robin.root.utils;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public final class MountPoint {
    private static HashMap<String, String> MOUNT_POINT_CACH = new HashMap(10);
    private static HashMap<String, List<String>> DEVICE_CACH = new HashMap(10);
    public static String getDeviceName(String mountPoint) {
        if (mountPoint == null) return null;
        return (String) MOUNT_POINT_CACH.get(mountPoint);
    }
    static {
        BufferedReader mountPointReader = null;
        try {
            mountPointReader = new BufferedReader(new InputStreamReader(new FileInputStream(new File("/proc/mounts"))));
            String buffer = null;
            while ((buffer = mountPointReader.readLine()) != null) {
                MOUNT_POINT_CACH.put(buffer.split(" ")[1], buffer.split(" ")[0]);
                List list = (List) DEVICE_CACH.get(buffer.split(" ")[0]);
                if (list == null) list = new ArrayList(1);
                list.add(buffer.split(" ")[1]);
                DEVICE_CACH.put(buffer.split(" ")[0], list);
            }
        } catch (IOException e) {
        } finally {
            try {
                if (mountPointReader != null) mountPointReader.close();
            } catch (IOException e) { }
        }
    }
}

透過這套流程,應用便能自動完成自訂 su 的部署,之後即可用 sur 執行需要 root 權限的操作。結束!

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved