0

I have a legacy app the needs to connect to a remove server on port 22 to establish the connection with userName and PWD. Then need to connect to a different port to send a request and receive response and close the session. At the moment I am using JSCH library to create a session and a channel then using Telnet command to submit request and receive response. But this call is taking 2-5s and doesn't scale well also.

Here is the sample code that I have:

public static void telnetConnection(String payload, int targetPOrt) throws JSchException, Exception {
    // Session session = null;
    DataOutputStream dataOut = null;
    DataInputStream dataIn = null;
    BufferedReader reader = null;
    Channel channel = null;
    StopWatch stopWatch = new StopWatch();
    stopWatch.start();
    Session JSCH_SESSION = null;
    try {
        JSch jsch = new JSch();
        JSCH_SESSION = jsch.getSession(userName, HOST, 22);
        JSCH_SESSION.setPassword(password);
        // It must not be recommended, but if you want to skip host-userName check,
        JSCH_SESSION.setConfig("StrictHostKeyChecking", "no");
        JSCH_SESSION.connect(30000);
        JSCH_SESSION.setServerAliveInterval(2000);
        JSCH_SESSION.sendKeepAliveMsg();
        StringBuffer buffer = new StringBuffer(" (");
        buffer.append("echo ");
        buffer.append("\'" + payload + "'");
        buffer.append(" && echo && sleep 2 ) | ");
        buffer.append(" telnet localhost " + targetPOrt + " \r\n ");
        channel = JSCH_SESSION.openChannel("shell");
        channel.connect(30000);
        dataOut = new DataOutputStream(channel.getOutputStream());
        System.out.println("Starting telnet connection...");
        String command = buffer.toString();
        dataOut.writeBytes(" bash \r\n");
        dataOut.flush();
        dataIn = new DataInputStream(channel.getInputStream());
        reader = new BufferedReader(new InputStreamReader(dataIn));
        dataOut.writeBytes(command);
        dataOut.flush();
        String line = reader.readLine();
        String result = line + "\n";
        while (!(line = reader.readLine()).contains("Connection closed by foreign host")) {
            result += line + "\n";

        }

        handleResponse(result);

    } catch (Exception e) {
        e.printStackTrace();
    } finally {

        if (dataIn != null) {
            dataIn.close();
        }
        if (dataOut != null) {
            dataOut.close();
        }
        if (channel != null) {
            channel.disconnect();
        }

        if (JSCH_SESSION != null) {
            JSCH_SESSION.disconnect();
        }
    }

}

Telnet connection command is working but doesn't scale well and is taking too long. I even cached the session and try to reuse it w/o creating for every request by just closing the Readers and channel for every request. I am wondering if there is any other API that I can use to make this work.

Adam
  • 186
  • 1
  • 4
  • 20

0 Answers0