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权限命令的需求。

相关推荐
AOwhisky1 小时前
Linux(CentOS)系统管理入门笔记(第二十一期)——防火墙管理(Firewalld)——zone、服务端口、富规则与端口转发
linux·运维·笔记·安全·centos·防火墙
腾飞开源1 小时前
01_K8s干货笔记之认识K8s
运维·笔记·云原生·容器·kubernetes·k8s·容器化部署
tg_xianheyun7 小时前
CDN节点分布如何影响网页加载速度和用户体验
服务器·cdn加速·全球访问优化
lsh曙光8 小时前
延时at指令和定时cron指令
linux·服务器·网络
圆山猫8 小时前
[Virtualization](四):Linux KVM/RISC-V 的 vCPU 运行路径
java·linux·risc-v
布鲁飞丝8 小时前
vivo Pulsar 万亿级消息处理实践()-Ansible运维部署
运维·ansible
XR1234567888 小时前
企业全光网络架构选型技术白皮书:从物理层到运维层的全链路分析
运维·网络·架构
似的8358 小时前
一步一步学习使用FireMonkey动画() 使用TAnimator类创建动画
linux·学习·nginx
HiDev_9 小时前
【非标自动化】2、认识元器件(直线模组)
运维·自动化
夏殇之殁10 小时前
包中创建自定义列表项。 . 使用自定义列表项进行数据绑定 . 将天气预报数据保存到本地内存表,通过LiveBindings进行显示。 ...
服务器·前端·javascript