android su执行命令

通过Runtime.getRuntime().exec("su")启动su进程,然后使用DataOutputStream向其写入要执行的命令。命令执行完成后需要调用process.waitFor()等待进程结束,并妥善关闭所有流资源

复制代码
import java.io.DataOutputStream;

public class SuCommandExecutor {
    private static final String TAG = "SuCommandExecutor";
    
    /**
     * 执行需要root权限的单个命令
     * @param command 要执行的命令
     * @return 命令执行结果
     */
    public static String execSuCmd(String command) {
        String output = "";
        Process process = null;
        DataOutputStream os = null;
        DataInputStream is = null;
        
        try {
            // 启动su进程获取root权限
            process = Runtime.getRuntime().exec("su");
            os = new DataOutputStream(process.getOutputStream());
            
            // 写入要执行的命令
            os.writeBytes(command + "\n");
            os.writeBytes("exit\n");
            os.flush();
            
            // 等待命令执行完成
            int exitCode = process.waitFor();
            
            // 读取命令输出
            is = new DataInputStream(process.getInputStream());
            byte[] buffer = new byte[is.available()];
            is.read(buffer);
            output = new String(buffer);
            
        } catch (Exception e) {
            e.printStackTrace();
            output = "Exception: " + e.getMessage();
        } finally {
            // 关闭所有流资源
            try {
                if (os != null) {
                    os.close();
                }
                if (is != null) {
                    is.close();
                }
                if (process != null) {
                    process.destroy();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return output;
    }
    
    /**
     * 静默执行root命令(不读取输出)
     * @param command 要执行的命令
     * @return 执行结果代码
     */
    public static int execRootCmdSilent(String command) {
        int result = -1;
        DataOutputStream dos = null;
        
        try {
            Process process = Runtime.getRuntime().exec("su");
            dos = new DataOutputStream(process.getOutputStream());
            dos.writeBytes(command + "\n");
            dos.flush();
            dos.writeBytes("exit\n");
            dos.flush();
            process.waitFor();
            result = process.exitValue();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (dos != null) {
                try {
                    dos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }
    
    /**
     * 测试设备是否具有su执行权限
     * @return 测试结果
     */
    public static boolean testSuPermission() {
        try {
            Process process = Runtime.getRuntime().exec("su");
            DataOutputStream dos = new DataOutputStream(process.getOutputStream());
            dos.writeBytes("id\n");
            dos.writeBytes("exit\n");
            dos.flush();
            int exitCode = process.waitFor();
            return exitCode == 0;
        } catch (Exception e) {
            return false;
        }
    }
    
    public static void main(String[] args) {
        // 测试su权限
        boolean hasPermission = testSuPermission();
        System.out.println("设备是否具有su权限: " + hasPermission);
        
        if (hasPermission) {
            // 执行示例命令
            String result = execSuCmd("ls -l /system");
            System.out.println("命令执行结果: " + result);
        }
    }
}

import java.io.DataOutputStream;

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Process process = Runtime.getRuntime().exec("su");
                    DataOutputStream dos = new DataOutputStream(process.getOutputStream());
                    dos.writeBytes("echo 72 > /sys/class/gpio/export"+"\n");
                    dos.flush();
                    dos.writeBytes("echo in > /sys/class/gpio/gpio72/direction"+"\n");
                    dos.flush();
        
                    dos.writeBytes("echo 78 > /sys/class/gpio/export"+"\n");
                    dos.flush();
                    dos.writeBytes("echo in > /sys/class/gpio/gpio78/direction"+"\n");
                    dos.flush();
        
                    dos.writeBytes("echo 98 > /sys/class/gpio/export"+"\n");
                    dos.flush();
                    dos.writeBytes("echo in > /sys/class/gpio/gpio98/direction"+"\n");
                    dos.flush();
        
                    dos.writeBytes("echo 97 > /sys/class/gpio/export"+"\n");
                    dos.flush();
                    dos.writeBytes("echo out > /sys/class/gpio/gpio97/direction"+"\n");
                    dos.flush();
        
                    dos.writeBytes("echo 62 > /sys/class/gpio/export"+"\n");
                    dos.flush();
                    dos.writeBytes("echo out > /sys/class/gpio/gpio62/direction"+"\n");
                    dos.flush();
        
                    dos.writeBytes("echo 63 > /sys/class/gpio/export"+"\n");
                    dos.flush();
                    dos.writeBytes("echo out > /sys/class/gpio/gpio63/direction"+"\n");
                    dos.flush();
        
                    dos.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();

关键注意事项

  • 设备要求‌:执行su命令前必须确认设备已root,且应用获得了su执行权限。
  • 权限申请‌:首次执行su命令时,系统会弹出授权对话框请求用户确认。
  • 异常处理‌:必须妥善处理IOException等异常情况,特别是在某些Android主板上可能出现执行异常4。
  • 资源管理‌:使用完毕后必须关闭DataOutputStream和Process等资源,避免内存泄漏。
  • 系统限制‌:普通应用无法直接访问系统自带的su程序,需要通过SuperSU等工具或系统root来获取权限。

该实现提供了完整的su命令执行功能,包括权限测试、命令执行和异常处理,能够满足Android应用中执行root权限命令的需求。

相关推荐
添砖java‘’2 分钟前
Linux信号机制详解:从产生到处理
linux·c++·操作系统·信号处理
Evan芙12 分钟前
nginx日志管理及日志格式定制
运维·nginx
MC皮蛋侠客27 分钟前
Linux C++使用GDB调试动态库崩溃问题完全指南
linux·c++
Wang's Blog38 分钟前
RabbitMQ: 消息发送、连接管理、消息封装与三种工程方案
linux·ubuntu·rabbitmq
The star"'1 小时前
04-管理变量和事实
运维·云计算·ansible
Vect__1 小时前
初识操作系统
linux
若风的雨1 小时前
pcie bar 地址对齐规则
linux
LRX_1989271 小时前
华为设备配置练习(七)VRRP 配置
服务器·网络·华为
林疏safe1 小时前
灯塔部署云服务器docker 部署方式,以及忘记密码如何查找
运维·服务器·docker
CQ_YM1 小时前
Linux线程控制
linux·c语言·开发语言·线程