前提:
1.手机被root;
2.该app已经取得了root权限。
目的:
试图获得系统文件夹下的文件的读写权限。
实现:
我们要使用的命令是:
chmod -R 0777 xxx/xxx等系统目录或文件
命令解读:
在Unix和Linux的各种操作系统下,每个文件(文件夹也被看作是文件)都按读、写、运行设定权限。
读、写、运行三项权限可以用数字表示,就是r=4,w=2,x=1。所以,rw-r–r–用数字表示成644。
反过来说777就是rwxrwxrwx,意思是该登录用户(可以用命令id查看)、他所在的组和其他人都有最高权限。
执行该命令的方法是:
Runtime.getRuntime().exec();
实现的关键是:
首先要通过命令”su”切换到Root身份,然后才能执行“chmod”等具体命令。
代码实现:
方法1:
public static boolean execCommand(String command) {
boolean status = false;
if (TextUtils.isEmpty(command)) {
return status;
}
try {
Process exec = Runtime.getRuntime().exec("su");
OutputStream outputStream = exec.getOutputStream();
outputStream.write(command.getBytes(Charset.forName("utf-8")));
outputStream.write("\n".getBytes());
outputStream.write("exit\n".getBytes());
outputStream.flush();
int waitFor = exec.waitFor();
Log.e(TAG, "execCommand command:"+command+";waitFor=" + waitFor);
if (waitFor == 0) {
//chmod succeed
status = true;
}
} catch (Exception e) {
e.printStackTrace();
Log.e(TAG, "execCommand exception=" + e.getMessage());
return false;
}
return status;
}
方法2:
public static boolean execCommand(String command) {
boolean status = false;
if (TextUtils.isEmpty(command)) {
return status;
}
String fullCommand = "su"+"\n"+command;
try {
Process exec = Runtime.getRuntime().exec(fullCommand);
int waitFor = exec.waitFor();
Log.e(TAG, "execCommand command:"+command+";waitFor=" + waitFor);
if (waitFor == 0) {
//chmod succeed
status = true;
}
} catch (Exception e) {
e.printStackTrace();
Log.e(TAG, "execCommand exception=" + e.getMessage());
return false;
}
return status;
}