2

I am executing command from java program like

Process myProcess = Runtime.getRuntime().exec("sudo cat /etc/sudoers"); //It asks for password so I send password through outputstream from my program.

InputStream inputStream = myProcess.getInputStream();
OutputStream outputStream = myProcess.getOutputStream();
outputStream.write("mypassword".getBytes()); // write password in stream
outputStream.flush();
outputStream.close();

But problem is that, it again ask to me for password as I already send the password through outputstream from my program. For solving this I tried so many times but not actually done.

By using shell script,I am able to provide password to terminal and my program works fine but it is not the most flexible way.

Can you suggest me any way for providing password through my java program ? (instead of shell programming)

Ruju
  • 961
  • 1
  • 12
  • 24
  • this is too much of working around for simple task. Just send the username/password to the command while calling it. Reade up on those commands for exact syntax – MozenRath May 30 '12 at 09:38
  • Did you try sending `\n` character after your password? It might be required by the external app you are running to end input with `CR` and/or `LF`. – npe May 30 '12 at 09:40
  • May be terminal program requires input in a definite format. – UVM May 30 '12 at 09:45
  • yes,I also try using '\n' character after password but problem remains same – Ruju May 30 '12 at 09:45
  • @Ruju I'm trying to do something similar, can you provide the shell script you said is working fine for you? – Nikhil Wagh May 23 '18 at 18:22
  • I have worked on it long time back. You can convert the same authentication steps to shell script file and call that script file directly from java. It will work surely. – Ruju May 24 '18 at 18:27

1 Answers1

2

You can do it using the -S option of sudo :

String[] cmd = {"/bash/bin","-c","echo yourpassword| sudo -S your command"}; 
Runtime.getRuntime.exec(cmd); 

But I'm not sure it's recommendable.

I'm not the author, I found this there : http://www.coderanch.com/t/517209/java/java/provide-password-prompt-through-Java

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758