如何从java程序向终端发送用户输入(即通过编程方式)?

问题描述:

我正在从java程序执行命令,如

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.

通过使用shell脚本,我能够为终端提供密码,我的程序运行正常
,但这不是最灵活的方式。

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.

你能建议我通过我的java程序提供密码吗? (而不是shell编程)

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

你可以使用 -S $ c $来完成c> sudo的选项:

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.

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

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