1

does anybody know how to read output from telnet with Java? I'm able to connect to the server and execute some commands, but I need output from that commands.

For example, command ls gives a list of all files and directory so I want to get that list and do something with it in my Java code.

I had tried 3rd party libraries for Telnet like apache-commons and sinetfactory(www.jscape.com ) but with no results for my case...

Igor

Igor
  • 11
  • 2

2 Answers2

3

You can read the output from the process InputStream, something like this:

final Process process =
    new ProcessBuilder("path/to/telnet", "and", "some", "args").start();
final AtomicBoolean running = new AtomicBoolean(true);
final InputStream processData = process.getInputStream();

// start a thread to read process output
new Thread(new Runnable(){

    @Override
    public void run(){
        while(running.get()){

            // read processData

        }

    }
}).start();
process.waitFor();
running.set(false);
Sean Patrick Floyd
  • 292,901
  • 67
  • 465
  • 588
  • 1
    I can start telnet session using Process or ProcessBuilder classes but then I can't execute commands on that process. I tried by opening output stream of process but it didn't work. For example, Process p = Runtime.getRuntime().exec("telnet ip port"); PrintWriter out = new PrintWriter(p.getOutputStream()); out.println("ls"); out.close(); but nothing recieved... – Igor Mar 15 '11 at 12:22
  • not sure if you still need a solution but I made something [simple](http://stackoverflow.com/questions/5988029/java-telnet-library/14098926#14098926) (and EXTREMELY limited in scope) that might help – Boon Dec 31 '12 at 07:46
0

I know you are asking for a java solution, but the expect scripting language was developed for this type of thing. http://expect.sourceforge.net/

If it has to be java, then please disregard.

map
  • 19