How to run (interact) prompt commands by Java?(Linux and Windows)

Asked

Viewed 909 times

1

Hey, you guys. I need to develop a java program that runs commands as if it were on promt/cmd, and in a way even interact with it. Do you know when we run some kind of command at the prompt and it gives a reply or asks for a password? Exactly that, I need a java function that I can connect with a device via SSH, enter the access password. And then run all the commands I need to configure that device. Researching already found some things, and I’ve even managed to run a command.

**But there is a case, in my real scenario, where I need to run a command, and then the prompt is waiting for the password, but I could not get the JAVA soon send the password and I followed up with the next commands.

Follow below what I already have.

    public static void main(String[] args) {
     String[] cmds = {
                "ssh -S none admin@ip_aqui"
                /*"admin",
                "enable",
                "senhaaqui",
                "configure terminal",
                "gpon",
                "gpon-olt 1",
                "show onu info" */              
            };

     try {
                //ProcessBuilder a = new Proce
                ProcessBuilder builder = new ProcessBuilder("cmd", "/c",
                    String.join("& ", cmds));

                builder.redirectErrorStream(true);

                Process p = builder.start();
                if ( p.waitFor() == 0){
                    System.out.println("Executado.");  
                }               
                else{
                    System.out.println("ERRO");
                }
                BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));
                String line;

                while (true) {
                    line = r.readLine();
                    if (line == null) {
                        break;
                    }

                    System.out.println(line);
                }
            } catch(Exception e) {
                System.err.println(e);
            }
    }

In my command array there is commented because I was testing, but in this case, after the first command, the prompt is waiting for the password, which is the second command, but java cannot send the password at the right time, causing error.

  • Well, try inserting a "Builder.Join() after initializing the thread, so you’ll make sure it runs step by step your commands until the end.

  • Thank you for the reply Alexandre, but I could illustrate it better. My Builder doesn’t have this Join method. And on which line would that be?

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.