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

1

Hey guys. I need to develop a java program that runs commands like it was in promt / cmd, and somehow even interact with it. Do you know when we run some kind of command at the prompt and it gives an answer or asks for a password? Exactly this, I need a java function that I can connect with a device via SSH, enter the access password. And in the sequence I run all the commands that I need to configure that device. Searching already found some things, and I 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 JAVA to immediately send the password and I followed with upcoming commands.

Below is 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 array of commands there is commented because I was testing, but in the case, after the first command, the prompt is waiting for the password, which is the second command, but java can not send the password at the correct time, causing error.

    
asked by anonymous 29.09.2017 / 20:49

0 answers