关于Android手机root的那点事

本文介绍了检测Android设备是否被Root的三种方法,包括检查特定文件存在性、验证系统构建标签和执行Shell命令来直接判断是否获取了Root权限。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

手机root是我工作后做的第一个安全功能,上网查了一下,答案蛮多,随便选了一种,结果判断过程中出现了问题。

网上所说的方法的主要原理是:当手机被root后,在   /system/app/    文件夹下会生成一个“Superuser.apk”的应用软件。则有:


File file = new File("/system/app/Superuser.apk");

if (file.exists()) {
return true;
}


但是很多手机,如小米,魅族的部分手机不支持该判断。那天用红米2测试的时候发现手机明明没有root但是这个方法返回的值是true。查阅的网上的资料,原来小米系统中本身含有这个apk的,而且知道了:我们所说的  “root过了” 和“获取了root权限”并不是完全相同的概念。像小米,魅族这样的手机一般都是已经root过的,但是未必都获取了root权限,可能都是出于一种安全角度考虑的吧!

但是问题还是要解决滴!郁闷之中查到另一种方法,就是判断 android.os.Build.TAGS 字符串中是否含有"test-keys"这个字符串,效果和上述方法是一样的。最后找了一种万能的方法就是运行shell-command命令的方式判断,这种方法可以直接判断手机设备是否获取了root权限。十分管用的方法。

public class AndroidUtil {

public static boolean isDeviceRooted() {
if (checkRootMethod1()) {
return true;
}
if (checkRootMethod2()) {
return true;
}
if (checkRootMethod3()) {
return true;
}
return false;
}


public static boolean checkRootMethod1() {
String buildTags = android.os.Build.TAGS;
if (buildTags != null && buildTags.contains("test-keys")) {
return true;
}
return false;
}


public static boolean checkRootMethod2() {
try {
File file = new File("/system/app/Superuser.apk");
if (file.exists()) {
return true;
}
} catch (Exception e) {
}


return false;
}


public static boolean checkRootMethod3() {
if (new ExecShell().executeCommand(ExecShell.SHELL_CMD.check_su_binary) != null) {
return true;
} else {
return false;
}
}

}




public class ExecShell {


private static String LOG_TAG = ExecShell.class.getName();


public static enum SHELL_CMD {
check_su_binary(new String[] { "/system/xbin/which", "su" }), ;


String[] command;


SHELL_CMD(String[] command) {
this.command = command;
}
}


public ArrayList executeCommand(SHELL_CMD shellCmd) {
String line = null;
ArrayList fullResponse = new ArrayList();
Process localProcess = null;


try {
localProcess = Runtime.getRuntime().exec(shellCmd.command);
} catch (Exception e) {
return null;
// e.printStackTrace();
}


BufferedWriter out = new BufferedWriter(new OutputStreamWriter(
localProcess.getOutputStream()));
BufferedReader in = new BufferedReader(new InputStreamReader(
localProcess.getInputStream()));


try {
while ((line = in.readLine()) != null) {
Log.d(LOG_TAG, "–> Line received: " + line);
fullResponse.add(line);
}
} catch (Exception e) {
e.printStackTrace();
}


Log.d(LOG_TAG, "–> Full response was: " + fullResponse);


return fullResponse;
}


}


如果返回的值不为null,说明已经获取root权限。这种方法覆盖的机型蛮全的,如果有漏洞,希望大家指出,大家一起进步!



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值