如何发送用户input到terminal从Java程序(即通过编程)?

我正在执行像Java程序的命令

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(); 

但问题是,它再次要求我的密码,因为我已经通过我的程序输出stream发送密码。 为了解决这个问题,我试了很多次,但实际上并没有完成。

通过使用shell脚本,我能够提供密码给terminal,我的程序工作正常,但它不是最灵活的方式。

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

你可以使用sudo的-S选项来做到这一点:

 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