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