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)

4

1 回答 1

2

您可以使用-Ssudo 选项来执行此操作:

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

但我不确定它是否值得推荐。

我不是作者,我在那里找到了这个:http: //www.coderanch.com/t/517209/java/java/provide-password-prompt-through-Java

于 2012-05-30T09:46:46.697 回答