如何在不作为标准命令的情况下将字符串发送到终端?
我正在用 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;
相关文章