要通過Java實(shí)現(xiàn)Telnet交換機(jī)獲取端口信息,你可以使用Java的Socket和TelnetClient類來建立一個(gè)Telnet連接。下面是一個(gè)簡(jiǎn)單的示例代碼:
import org.apache.commons.net.telnet.*;
public class TelnetExample {
public static void main(String[] args) {
String host = "交換機(jī)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);
// 執(zhí)行命令
write(out, "show interfaces brief");
// 讀取命令輸出結(jié)果
String result = readUntil(in, "交換機(jī)提示符");
// 處理命令輸出結(jié)果
// ...
// 關(guān)閉連接
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();
}
}
請(qǐng)注意替換代碼中的以下變量:
你需要將以上代碼中的占位符替換為實(shí)際的值,并根據(jù)你所使用的Telnet交換機(jī)的命令輸出格式進(jìn)行相應(yīng)的處理。