gpt4 book ai didi

java - 如何将用户输入从 java 程序发送到终端(即以编程方式)?

转载 作者:太空狗 更新时间:2023-10-29 12:20:27 24 4
gpt4 key购买 nike

我正在从 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();

但问题是,它再次向我询问密码,因为我已经通过程序的输出流发送了密码。为了解决这个问题,我尝试了很多次但没有真正完成。

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

你能建议我通过我的 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

关于java - 如何将用户输入从 java 程序发送到终端(即以编程方式)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10813608/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com