Java 使用JSch在远程SSH会话上运行telnet命令后执行挂起
我正在寻找一种解决方案,先通过SSH连接,然后通过java将Telnet连接到远程系统。由于使用telnet连接,我只能在远程机器上执行该特定命令 在浏览了很多次之后,我找到了这个答案“”,但是在执行“telnet localhost 4444”之后,程序执行挂起&永远不会从while循环中出来。正因为如此,在建立telnet连接后,我无法执行其他命令 我的代码是:-Java 使用JSch在远程SSH会话上运行telnet命令后执行挂起,java,ssh,telnet,jsch,Java,Ssh,Telnet,Jsch,我正在寻找一种解决方案,先通过SSH连接,然后通过java将Telnet连接到远程系统。由于使用telnet连接,我只能在远程机器上执行该特定命令 在浏览了很多次之后,我找到了这个答案“”,但是在执行“telnet localhost 4444”之后,程序执行挂起&永远不会从while循环中出来。正因为如此,在建立telnet连接后,我无法执行其他命令 我的代码是:- public static void main(String[] arg) { try { Sy
public static void main(String[] arg) {
try {
System.out.println(telnetConnection(command, puttyUserName,
puttyPassword, puttyHostName));
} catch (Exception e) {
e.printStackTrace();
}
}
public static String telnetConnection(String command, String user, String password, String host)
throws JSchException, Exception {
JSch jsch = new JSch();
jsch.addIdentity(puttyPublicKey, puttyPassword);
Session session = jsch.getSession(user, host, 22);
session.setConfig("StrictHostKeyChecking", "no");
session.connect(500);//This timeout is not working as mentioned in the example. Program execution never stops.
Channel channel = session.openChannel("shell");
channel.connect(500);
DataInputStream dataIn = new DataInputStream(channel.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(dataIn));
DataOutputStream dataOut = new DataOutputStream(channel.getOutputStream());
System.out.println("Starting telnet connection...");
dataOut.writeBytes("telnet localhost 4444\r\n"); after this no commands executes
dataOut.writeBytes(command + "\r\n");
dataOut.writeBytes("quit\r\n");
//使用quit,我可以退出telnet会话,同时通过putty手动退出,因为退出不起作用
dataOut.writeBytes("exit\r\n"); // exit from shell
dataOut.flush();
String line = reader.readLine();
String result = line + "\n";
while (!(line = reader.readLine()).equals("Connection closed by foreign host"))
{
result += line + "\n";
System.out.println("heart beat" + result);
}
System.out.println("after while done");
dataIn.close();
dataOut.close();
channel.disconnect();
session.disconnect();
System.out.println("done");
return result;
}
}
输出//
心跳telnet本地主机4444
启动转换器ABCLOC高
退出
出口
[XYZ]$telnet localhost 4444
正在尝试x.x.x.1
已连接到localhost.localdomain(x.x.x.1)
转义字符为“^]”
连接到接口层
心跳telnet本地主机4444
启动转换器ABCLOC高
退出
出口
[XYZ]$telnet localhost 4444
正在尝试x.x.x.1
已连接到localhost.localdomain(x.x.x.1)
转义字符为“^]”
连接到接口层
键入“help”以获取命令列表
////在这个程序挂起之后&没有执行任何操作我没有像您一样在端口4444上运行相同的服务器,但是我在本地测试中得到了类似的行为,在JSch中发出“telnet localhost 80”和“GET/”。在我的案例中,解决方法是小心“连接关闭”消息的准确性。在我的情况下,服务器将发送: 连接被外部主机关闭 而您的代码正在检查 外部主机关闭的连接
(没有句号)这样循环就永远不会终止。您可以在Thank@Phil上找到我的测试代码,但我也尝试了您提到的连接关闭消息。结果是一样的。主要问题是在执行Telnet localhost 4444之后,它不允许我发送/执行任何其他命令。。。我发现这类问题在很多网站上都是公开的。。。对于ex-[link]()