如何发送字符串到终端,而不是它是一个标准的命令? [英] How to send a string to the terminal without having it to be a standard command?

查看:134
本文介绍了如何发送字符串到终端,而不是它是一个标准的命令?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在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("\n------------Sending Login Command------------\n");
    String cmd="qskdjqhsdqsd";
    Runtime rt = Runtime.getRuntime();
    Process p=rt.exec(cmd);
}
public Process sendPassword(String password) throws IOException
{
    System.out.println("\n------------Sending Password------------\n");
    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("\n------------Reading Terminal Output------------\n");
    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;
}

这里,程序正确发送th p4 login命令,请求密码。
当我使用与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;

这篇关于如何发送字符串到终端,而不是它是一个标准的命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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