How To Simulate Telnet Session in Java

By Angsuman Chakraborty, Gaea News Network
Thursday, February 16, 2006

Often we come across procedures which need to be performed by issuing commands in a telnet session. It is relatively easy to do it manually but is definitely not suitable for automation. Let’s see how you can easily automate such tasks using Java software. Sample code included.

Here is the core code:

// Conversation; Simulating telnet session with James server
readLines(r, 3);
writeLine(w, login);
readLines(r, 1);
writeLine(w, password);
readLines(r, 1);
writeLine(w, SHUTDOWN);
readLines(r, 1);

readLines() reads and discards specified number of lines (response).

Here are the key functions:

    /** Read and discard count lines from BufferedReader r */
    public static void readLines(BufferedReader r, int count) throws IOException {
        for(int i = 0;i < count;i++) {
            String t = r.readLine();
            if(DEBUG) System.out.println(t);
        }
    }

    /** Write out to BufferedWriter w and flush */
    public static void writeLine(BufferedWriter w, String out) throws IOException {
        w.write(out + CRLF, 0, (out + CRLF).length());
        w.flush();
    }

You can download the code here. It is used to shutdown Apache James Mail Server. The utility is fully described along with the options in - Shutdown Apache James Mail Server - Java Utility

Discussion

Alan Neville
March 13, 2008: 10:59 pm

Hey,

I have a question re the above code. I attempted to modify this for use with a Cisco Catalyst 3500 swtich to return the the mac address tale using the “sh mac-address-table” command. However, I’m having a problem where, using the above code, i need to specify the number of lines to read back. But, depending on the amount of clients physically collected into the switch, the number varies. I attempted to write a while((line = in.readLine()) != null) { .. } block of code but tis fails where, once it reaches the end, it sits there as if expecting more. It never receives a NULL at the end.

In another attempt, i assumed the last line should contain a prompt. However, this also failed. It seems readLine() discards prompts but should replace them with NULL. But this doesn’t seem to be true for me.

My question is this, is there a way to adapt your code so that it can read an unknown number of lines and store the output?

Many Thanks,

A


gaurav
YOUR VIEW POINT
NAME : (REQUIRED)
MAIL : (REQUIRED)
will not be displayed
WEBSITE : (OPTIONAL)
YOUR
COMMENT :