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)

6
  • 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 Commented May 30, 2012 at 9: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. Commented May 30, 2012 at 9:40
  • May be terminal program requires input in a definite format. Commented May 30, 2012 at 9:45
  • yes,I also try using '\n' character after password but problem remains same Commented May 30, 2012 at 9:45
  • @Ruju I'm trying to do something similar, can you provide the shell script you said is working fine for you? Commented May 23, 2018 at 18:22

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.