How to generate processes with inherited rights and permissions

我的梦境 提交于 2019-12-06 10:38:08

First of all, I hope this isn't being used for evil purposes. Your example of "rm -rf /*" causes me some concern.

If you do Runtime.getRuntime().exec("bash") you'll get a shell that you can send commands to and get responses from. So, for example, you could tie the console into it:

final Process process = Runtime.getRuntime().exec("bash");

new Thread() {
    public void run() {
        try {
            InputStreamReader reader = new InputStreamReader(process.getInputStream());
            for(int c = reader.read(); c != -1; c = reader.read()) {
                System.out.print((char)c);
            }
        } catch(IOException e) {
            e.printStackTrace();
        }
    }
}.start();

// (Same for redirecting the process's error stream to System.err if you want)

InputStreamReader fromKeyboard = new InputStreamReader(System.in);
OutputStreamWriter toProcess = new OutputStreamWriter(process.getOutputStream());

for(int c = fromKeyboard.read(); c != -1; c = fromKeyboard.read()) {
    toProcess.write((char)c);
    toProcess.flush();
}

This is a good way to experiment and see what your OS will let you do. On Mac OS, if I want to sudo a command from this process, I run into the problem that it can't accept my password from STDIN because it is not really a login shell. So, I have to do this:

SUDO_ASKPASS="password.sh" sudo -A <command>

... where "password.sh" just echoes my password, and is the command I want to run as root (I used the nice safe "pwd" instead of your wipe-my-root-filesystem example).

A few notes:

  1. I suppose you already get output from this process, via Process.getInputStream()?

    BufferedReader buf = new BufferedReader( new InputStreamReader(
            superUserShell.getInputStream() ) ) ;
    
    while ( ( String line ; line = buf.readLine() ) != null ) {
        // do domething with data from process;
    }
    
  2. Try adding newline to the command, e.g. "rm -rf /* \r\n"

  3. If you send multiple commands consecutively (and read reply) then you might want to send and receive data in separate threads.

Selvin's right, su returns immediately, and doesn't provide your application with a 'shell' type of situation like a real, interactive shell would. What you want to look into is something like sudo <command> to get su to run the command you want.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!