android执行su命令

文章目录

Root过后的Android使用su执行命令的java代码。

修改包目录权限

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public boolean () {
Process process = null;
DataOutputStream os = null;
String cmd="chmod 777 " + getPackageCodePath();
try {
process = Runtime.getRuntime().exec("su");
os = new DataOutputStream(process.getOutputStream());
os.writeBytes(cmd + "n");
os.writeBytes("exitn");
os.flush();
process.waitFor();
} catch (Exception e) {
return false;
} finally {
try {
if (os != null) {
os.close();
}
process.destroy();
} catch (Exception e) {
}
}
return true;
}

以root权限执行并获取输出

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
public String execRootCmd(String cmd) {
DataInputStream is = null;
DataOutputStream os = null;
String content = "";
try {
Process process = Runtime.getRuntime().exec("su");
os = new DataOutputStream(process.getOutputStream());
is = new DataInputStream(process.getInputStream());
os.writeBytes(cmd + "nexitn");
os.flush();
while (true) {
String line = is.readLine();
if (line == null) {
break;
}
content += line + "n";
}
//process.waitFor();
//return process.exitValue();
return content;
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (is != null) {
is.close();
}
if (os != null) {
os.close();
}
process.destroy();
} catch (Exception e) {
}
}
return "";
}

作者原创,转载请注明出处