开发者

Show Processes of Shell Script

开发者 https://www.devze.com 2023-03-06 15:22 出处:网络
I have the following method for running shell commands in my java applications and i\'m looking to run a few scripts such as one that fixes permissions for all applications on the users phone. I can r

I have the following method for running shell commands in my java applications and i'm looking to run a few scripts such as one that fixes permissions for all applications on the users phone. I can run the script no problem by using this command execCommand("/system/xbin/fix_perm"); however the problem is that i want to just print out what's being done like terminal emulator does how can i take my outputstream and print it on the screen? Thank you for any help

public Boolean execCommand(String command) 
{
    try {
        Runtime rt = Runtime.getRuntime();
        Process process = rt.exec("su");
        DataOutputStream os = new DataOutputStream(process.getOutputStream()); 开发者_如何转开发
        os.writeBytes(command + "\n");
        os.flush();
        os.writeBytes("exit\n");
        os.flush();
        process.waitFor();
    } catch (IOException e) {
        return false;
    } catch (InterruptedException e) {
        return false;
    }
    return true;
}


I'm hoping you're aware of the potentially extreme consequences of allowing a user to run arbitrary commands as su and will instead point to a possible solution.

public Boolean execCommand(String command) 
{
    try {
        Runtime rt = Runtime.getRuntime();
        Process process = rt.exec("su");

        // capture stdout
        BufferedReader stdout = new BufferedReader(
            new InputStreamReader(process.getInputStream()));
        // capture stderr
        BufferedReader stderr = new BufferedReader(
            new InputStreamReader(process.getErrorStream()));

        DataOutputStream os = new DataOutputStream(process.getOutputStream()); 
        os.writeBytes(command + "\n");
        os.flush();

        String line = null;
        StringBuilder cmdOut = new StringBuilder();
        while ((line = stdout.readLine()) != null) {
            cmdOut.append(line);
        }
        stdout.close();
        while ((line = stderr.readLine()) != null) {
            cmdOut.append("[ERROR] ").append(line);
        }
        stderr.close();

        // Show simple dialog
        Toast.makeText(getApplicationContext(), cmdOut.toString(), Toast.LENGTH_LONG).show();

        os.writeBytes("exit\n");
        os.flush();

        // consider dropping this, see http://kylecartmell.com/?p=9
        process.waitFor(); 
    } catch (IOException e) {
        return false;
    } catch (InterruptedException e) {
        return false;
    }
    return true;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消