It should look like this:
import java.io.*;
import java.lang.String;
public class Commands
{
static final Runtime run = Runtime.getRuntime();
static Process pro;
static BufferedReader read;
public static void main(String[] args)
{
String[] cmds = {
"telnet ...", //primeiro telnet
"comando após o telnet",
"telnet ...", //segundo telnet
"comando após o telnet",
};
try {
ProcessBuilder builder = new ProcessBuilder("cmd", "/c",
String.join("& ", cmds));
builder.redirectErrorStream(true);
Process p = builder.start();
BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while (true) {
line = r.readLine();
if (line == null) {
break;
}
System.out.println(line); //Exibe a resposta
}
} catch(Exception e) {
System.err.println(e);
}
}
}
You said preferably java , this means that it does not delete other ways, you can use windows .bat, or .sh on linux or unix systems (depending on your case), see below:
Windows
If it's Windows you can put all the commands in a file with the extension .bat
, something like create a file, comandos.bat
and add a content like this:
@echo off
telnet etc etc etc
pause
Unix / Linux
If it is a Unix or Linux core system, you can create a file with the extension .sh
(it is optional), you can call it comando.sh
and add the commands like this:
#!/bin/bash
telnet etc etc etc
After creating the .sh file you should set the executable permission:
cd pasta/aonde/esta/o/seu/script
chmod +x comando.sh
The above command sets permission for anyone to be able to run your script, but perhaps only your user (script owner) can be the only one to use it, so run chmod
like this:
chmod u+x comando.sh
Important Note
/bin/bash
is the bash path, but it can change from operating system to operating system, there is no default path between the various systems with Linux and Unix based kernels, read this for more details: