How to send a string to the terminal without having it to be a standard command?(如何在不作为标准命令的情况下将字符串发送到终端?)
问题描述
我正在用 Java 编写一个需要使用终端命令才能工作的程序.我的功能基本上是这样的:
I am writing a program in Java that needs to use terminal command to work. My function basically looks like this :
public void sendLoginCommand() throws IOException
{
System.out.println("
------------Sending Login Command------------
");
String cmd="qskdjqhsdqsd";
Runtime rt = Runtime.getRuntime();
Process p=rt.exec(cmd);
}
public Process sendPassword(String password) throws IOException
{
System.out.println("
------------Sending Password------------
");
String cmd=password;
Runtime rt = Runtime.getRuntime();
Process p=rt.exec(cmd);
return p;
}
public void login(String password) throws IOException
{
sendLoginCommand();
Process p = sendPassword(password);
System.out.println("
------------Reading Terminal Output------------
");
Reader in = new InputStreamReader(p.getInputStream());
in = new BufferedReader(in);
char[] buffer = new char[20];
int len = in.read(buffer);
String s = new String(buffer, 0, len);
System.out.println(s);
if(s.equals("Password invalid.")) loggedIn=false;
else loggedIn=true;
}
在这里,程序正确发送了 p4 登录命令,但随后终端要求输入密码.当我使用与 sendLoginCommand() 相同的行时,程序返回错误.显然,我们只能通过 Process 发送标准命令.我希望有人知道如何向终端发送普通字符串
Here, the program sends correctly th p4 login command, but then, the terminal asks for a password. When I use the same lines that with the sendLoginCommand(), the program returns an error. Apparently, we can send only standard commands throught Process. I was hoping that someone knew how to send a normal string to the terminal
提前谢谢你
推荐答案
我找到了我的问题的答案.
I have found the answer to my question.
问题是终端的第二个响应实际上是在第一个响应中,并且必须在其中发送密码.这是代码(我同意,我的解释有点模糊):
The problem was that the second response of the terminal was in fact in the first one, and the password had to be sent in the middle of it. Here is the code (I agree, my explanation is a little vague) :
String s="";
Process p = Runtime.getRuntime().exec("p4 login");
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
char a=(char)in.read();
while(a>0 && a<256)
{
a=(char)in.read();
if(nb==14) new PrintWriter(p.getOutputStream(),true).println(password);
if(nb>16) s=s+a;
nb++;
}
if(s.startsWith("User")) loggedIn=true;
else loggedIn=false;
这篇关于如何在不作为标准命令的情况下将字符串发送到终端?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在不作为标准命令的情况下将字符串发送到终端?
基础教程推荐
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01
- 如何对 HashSet 进行排序? 2022-01-01
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01
- 如何强制对超级方法进行多态调用? 2022-01-01
- 在螺旋中写一个字符串 2022-01-01
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01