DenisM
DenisM

Reputation: 223

Telnet client for cisco router

I am writing telnet client for cisco router using apache.commons.net.telnet. But i have problem. Here is code sample:

static TelnetClient telnetClient = new TelnetClient();

public static void main(String[] args) throws IOException {
    setOptionHandlers();
    telnetClient.connect("192.168.127.100");
    read();
    telnetClient.disconnect();
}

private static void setOptionHandlers() throws IOException {
    ArrayList<TelnetOptionHandler> optionHandlers = 
        new ArrayList<TelnetOptionHandler>();
    optionHandlers.add(new TerminalTypeOptionHandler("VT100", false, false, true, false));
    optionHandlers.add(new EchoOptionHandler(true, false, true, false));
    optionHandlers.add(new SuppressGAOptionHandler(true, true, true, true));
    for (TelnetOptionHandler handler : optionHandlers) {
        try {
            telnetClient.addOptionHandler(handler);
        }
        catch (InvalidTelnetOptionException e) {
            System.err.println("Error registering option handler "
                    + handler.getClass().getSimpleName());
        }
    }
}

public static void write(byte[] data) throws IOException {
    telnetClient.getOutputStream().write(data);
    telnetClient.getOutputStream().flush();
}

public static void read() throws IOException {
    System.out.println("Read");
    byte[] buff = new byte[1024];
    int read;
    if((read = telnetClient.getInputStream().read(buff)) > 0) {
        System.out.println(new String(buff, 0, read));
    }
    System.out.println("read="+read);
}

In some cases it works correctly and shows prompt for password entering. But is other cases it works incorrectly - hangs by reading from telnet input stream. Run conditions are the same. Why do I get this situation? If anyone has tips for writing cisco telnet client, i'll be glad to hear them!

Upvotes: 4

Views: 3895

Answers (1)

Phaedrus
Phaedrus

Reputation: 497

I can reproduce this problem every time.

The problem can be worked-around by changing your read buffer size to 1 byte.

This accounts for why the readUntil() function from Looking for Java Telnet emulator works, at it simply calls read() for 1 byte.

That said, does this indicate a bug in org.apache.commons.net.telnet.TelnetClient?

Edit: Rolled back to an earlier version of Commons Net and the problem disappeared !

Upvotes: 1

Related Questions