要通過Java實現Telnet交換機獲取端口信息,你可以使用Java的Socket和TelnetClient類來建立一個Telnet連接。下面是一個簡單的示例代碼:
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();
}
}
請注意替換代碼中的以下變量:
你需要將以上代碼中的占位符替換為實際的值,并根據你所使用的Telnet交換機的命令輸出格式進行相應的處理。