以下是一个使用 Java 实现 Telnet 登录、执行命令,并将结果保存到日志文件中的示例代码:
java
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.SocketException;
import org.apache.commons.net.telnet.TelnetClient;
public class TelnetExample {
public static void main(String[] args) {
String host = "your_host";
int port = 23;
String username = "your_username";
String password = "your_password";
String command = "your_command";
TelnetClient telnet = new TelnetClient();
try {
telnet.connect(host, port);
// 登录
BufferedReader reader = new BufferedReader(new InputStreamReader(telnet.getInputStream()));
PrintWriter writer = new PrintWriter(telnet.getOutputStream());
writer.println(username);
writer.println(password);
// 发送命令
writer.println(command);
// 读取结果并保存到文件
String line;
BufferedWriter logWriter = new BufferedWriter(new FileWriter("telnet_log.txt"));
while ((line = reader.readLine())!= null) {
logWriter.write(line + "\n");
}
logWriter.close();
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (telnet.isConnected()) {
telnet.disconnect();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
在上述代码中,您需要将以下部分替换为实际的值:
your_host
:Telnet 服务器的主机名或 IP 地址。your_username
:登录用户名。your_password
:登录密码。your_command
:要执行的命令。
运行代码后,它将连接到指定的 Telnet 服务器,执行命令,并将结果保存到 telnet_log.txt
文件中。