How to implement telnet in Java to access switch ports?

In order to obtain port information from a switch using Java, you can establish a Telnet connection by using Java’s Socket and TelnetClient classes. Below is a simple example code.

import org.apache.commons.net.telnet.*;

public class TelnetExample {
    public static void main(String[] args) {
        String host = "交换机IP";
        int port = 23;
        String user = "用户名";
        String password = "密码";

        try {
            TelnetClient client = new TelnetClient();
            client.connect(host, port);

            // 获取输入流和输出流
            InputStream in = client.getInputStream();
            PrintStream out = new PrintStream(client.getOutputStream());

            // 登录
            readUntil(in, "Username:");
            write(out, user);
            readUntil(in, "Password:");
            write(out, password);

            // 执行命令
            write(out, "show interfaces brief");

            // 读取命令输出结果
            String result = readUntil(in, "交换机提示符");

            // 处理命令输出结果
            // ...

            // 关闭连接
            client.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void write(PrintStream out, String value) {
        out.println(value);
        out.flush();
    }

    private static String readUntil(InputStream in, String pattern) throws IOException {
        StringBuilder sb = new StringBuilder();
        char lastChar = pattern.charAt(pattern.length() - 1);
        char[] chars = new char[1024];
        int read;
        while ((read = in.read(chars)) != -1) {
            sb.append(chars, 0, read);
            if (sb.charAt(sb.length() - 1) == lastChar) {
                if (sb.toString().endsWith(pattern)) {
                    return sb.toString();
                }
            }
        }
        return sb.toString();
    }
}

Please be sure to replace the following variables in the code:

  1. host: IP address of the switch
  2. Port: Default port for Telnet is 23.
  3. User: Telnet login username
  4. Password: Telnet login password
  5. Command to execute in order to obtain port information: “show interfaces brief”
  6. “Switch Prompt”: The prompt of a switch, used in the command output to determine when the command has been executed.

You need to replace the placeholders in the code above with actual values, and handle them accordingly based on the command output format of the Telnet switch you are using.

bannerAds