NDK/Jni底层获取root权限的四种思路
16lz
2021-01-26
很多时候对Android系统底层进行操作(如查看/data/data/下的数据)是没有权限的。当然如果能在Java层直接执行的操作,直接用类似如下代码执行即可:
Process process; String cmd = "....";try {process = Runtime.getRuntime().exec("su");BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(process.getOutputStream()));BufferedReader error = new BufferedReader(new InputStreamReader(process.getErrorStream()));writer.write(cmd + "\n");writer.write("exit\n");writer.flush();String line;while ((line = reader.readLine()) != null) { // 处理结果}while ((line = error.readLine()) != null) {Log.e("error", line);}process.destroy();} catch (IOException e) {e.printStackTrace();}
但是有时候我们需要在Jni层进行类似的操作,那么我们如何获取root权限呢?这边提供四种思路供大家参考(前提是手机已root,有的思路未经实践,如果不可行或有更好的方法,还望斧正):
1.通过“su -c”来执行:
这里我们用命令行来演示一下:
android:/ $ du -ah /data/data/com.example.helloworld/du: can't open '/data/data/com.example.helloworld/': Permission denied
这里我们可以看到没有权限。但是当我们通过“su -c cmd”来执行上述命令的时候就会获得root权限来执行:
@android:/ $ su -c "du -ah /data/data/com.example.helloworld/"8.0K/data/data/com.example.helloworld/lib/libhelloworld.so12.0K/data/data/com.example.helloworld/lib4.0K/data/data/com.example.helloworld/cache/com.android.renderscript.cache8.0K/data/data/com.example.helloworld/cache1.0M/data/data/com.example.helloworld/files/busybox4.0K/data/data/com.example.helloworld/files/test1.0M/data/data/com.example.helloworld/files1.1M/data/data/com.example.helloworld/
在jni的native 层可以同过此方法来执行。
2.sign Android app with system signature
(从stackoverflow的到的思路,未实际操作过)
3.将native层编译成可执行文件
(use the NDK toolchain to cross-compile native program as a binary)
然后通过Java层通过su来调用。
(我自己项目用到busybox就是通过这个方法来执行的)
4.copy app to /system/app/
这个应该和第2种方法异曲同工吧。
当然如果有.so文件还是要移动到/system/lib/下的
更多相关文章
- android读取sd卡图片并进行缩放操作
- Android(安卓)基础知识之JobScheduler基本使用
- Android(安卓)中短信数据库的简单操作
- Android(安卓)Modules 依赖关系,命令行
- Android系统定制之源码完美下载
- android周期性任务
- android小功能实现之拨打电话
- Android(安卓)性能优化的一些方法
- ContactsProvider2