如何从java程序向终端发送用户输入(即通过编程方式)? [英] How to send user input to terminal from java program (i.e by programmatically)?

查看:334
本文介绍了如何从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 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

这篇关于如何从java程序向终端发送用户输入(即通过编程方式)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆