4

I need to run two commands Linux using java code like this:

 Runtime rt = Runtime.getRuntime();
          
           
            Process  pr=rt.exec("su - test");
            String line=null;
            BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream()));
          
            while((line=input.readLine()) != null) {
                
                System.out.println(line);
            }
           pr = rt.exec("whoami");
             input = new BufferedReader(new InputStreamReader(pr.getInputStream()));

             line=null;

            while((line=input.readLine()) != null) {
                 System.out.println(line);
            }               
            int exitVal = pr.waitFor();
            System.out.println("Exited with error code "+exitVal);              
        } catch(Exception e) {
            System.out.println(e.toString());
            e.printStackTrace();
        }

The problem is the output of the second command ("whoami") doesn't display the current user which used on the first command ("su - test")! Is there any problem on this code please?

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
ATEF CHAREF
  • 387
  • 5
  • 8
  • 18

3 Answers3

7

In the general case, you need to run the commands in a shell. Something like this:

    Process  pr = rt.exec(new String[]{"/bin/sh", "-c", "cd /tmp ; ls"});

But in this case that's not going to work, because su is itself creating an interactive subshell. You can do this though:

    Process  pr = rt.exec(new String[]{"su", "-c", "whoami", "-", "test"});

or

    Process  pr = rt.exec(new String[]{"su", "test", "-c", "whoami"});

Another alternative is to use sudo instead of su; e.g.

    Process  pr = rt.exec(new String[]{"sudo", "-u", "test", "whoami"});

Note: while none of the above actually require this, it is a good idea to assemble the "command line" as an array of Strings, rather than getting exec to do the "parsing". (The problem is that execs splitter does not understand shell quoting.)

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
3

As stated in the Javadoc for Runtime.exec():

Executes the specified string command in a separate process.

each time you execute a command via exec() it will be executed in a separate subprocess. This also means that the effect of su ceases to exist immediately upon return, and that's why the whoami command will be executed in another subprocess, again using the user that initially launched the program.

su test -c whoami

will give you the result you want.

fvu
  • 32,488
  • 6
  • 61
  • 79
0

If you want to run multiple commands in a way the commands would execute in a subshell if need be see the response here

How can I run multiple commands in just one cmd windows in Java? (using ProcessBuilder to simulate a shell)

Community
  • 1
  • 1
sysuser
  • 1,072
  • 1
  • 13
  • 30