How to send user input to the terminal from a java program (i.e., programmatically)?

I execute a command from a 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 the problem is that it again asks me for the password, since I already send the password through the output stream from my program. To solve this, I tried so many times, but did not.

Using a shell script, I can provide a password for the terminal, and my program works fine but this is not the most flexible way.

Can you suggest me a way to provide a password through my java program? (instead of shell programming)

+2
source share
1 answer

You can do this using the -Ssudo parameter :

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

But I'm not sure if this is recommended.

, : http://www.coderanch.com/t/517209/java/java/provide-password-prompt-through-Java

+2

All Articles