Search code examples
javashsolarisruntime.exec

how to pass the user and pwd via the runtime.exec() in java


I'm trying to run a simple command using java 1.8 and OS Solaris 11. My program runs under a particular user and the command must run under SuperUser

here is the command:

Runtime.getRuntime().exec("su - root -c 'pargs -l 1111'");

if i run the command in shall its work fine and ask for password and wen i enter the password i will get the result.

the problem is wen i run it in java here is my code

Process proc = Runtime.getRuntime().exec("su - root -c 'pargs -l 1111'");
PrintWriter out = new PrintWriter(new OutputStreamWriter(proc.getOutputStream()));
out.println(password);
out.flush();
int exitCode= proc.waitFor();
System.out.println(exitCode);//exitCode = 1
BufferedReader pArgs= new BufferedReader( new InputStreamReader(proc.getInputStream()));
if((line=pArgs.readLine()) != null)
{
    //do something
}
else
{
    //something not working = ERROR 
}

i think that the line equal to null because something in the set of the password is not correct bat i'm not sure

what i'm doing wrong?


Solution

  • Thank you very much for all the answers. But my solution was a little different. It was decided to use an external file that could be written and read from both processes. The whole goal was to do a handshake again in case the process running at the root will fall (watchdog).

    So now there is no need to use the command

    Runtime.getRuntime().exec("su - root -c 'pargs -l 1111'");
    

    When the root process starts running, it records a time signature into a file. and if the process of the user (who reads the file every X time) finds that the signature has changed, he will do a handshake again.