Search code examples
javaunixpom.xmltelnetspring-tool-suite

Telnet Java code working in Windows but not in Unix


I am trying to Telnet to a server from the method SwitchClient and authenticate using a password. I have written 2 methods, readUntil to read and traverse till the output end, and write to write the password.

I am using Spring Tool Suite for my development and building a Jar file. Additionally I am using UTF-8 encoding in the pom.xml. This same piece of code is working fine in Windows machine while its failing in UNIX with "Password Timeout" at write method and printing junk values.

One interesting fact: I tried to create a jar with this standalone class file, and executed in Unix box. To my surprise it worked fine without any issues. Whereas the jar created from Spring Tool Suite still does not work. Please help.

public SwitchClient(String server, String user, String password) {
  try {         
    telnet.connect(server, 23);
    in = telnet.getInputStream();
    out = new PrintStream(telnet.getOutputStream(),false,"UTF-8");
    readUntil("Enter Password: ");
    write("password");
  } catch (Exception e) {
    e.printStackTrace();
  }
}

public String readUntil(String pattern) {
  try {
    char lastChar = pattern.charAt(pattern.length() - 1);
    StringBuffer sb = new StringBuffer();
    char ch = (char) in.read();
    while (true) {
      System.out.print(ch);
      sb.append(ch);
      if (ch == lastChar) {
        if (sb.toString().endsWith(pattern)) {
          return sb.toString();
        }
      }
    ch = (char) in.read();
    }
  } catch (Exception e) {
    e.printStackTrace();
  }
  return null;
}

public void write(String value) {
  try {
    out.println(value);
    out.flush();
  } catch (Exception e) {
    e.printStackTrace();
  }
}

Solution

  • I am able to fix this issue by just adding write("\r\n"); after the write("password");

    Thanks all for your efforts. :-)

    Please refer this URL