[英]Execution hangs after Running telnet command on remote SSH session using JSch
我一直在寻找一种解决方案,可以通过SSH连接,然后通过java通过Telnet连接到远程系统。 由于仅使用telnet连接,因此我可以在远程计算机上执行该特定命令。
经过大量浏览后,我找到了这个答案“ https://stackoverflow.com/questions/27146991/running-telnet-command-on-remote-ssh-session-using-jsch “,但是在执行“ telnet localhost 4444 ”程序之后执行挂起并且永远不会从while循环中出来。 因此,在进行telnet连接后,我无法执行其他命令。
我的代码是:-
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");
//使用退出我可以退出telnet会话,同时通过腻子手动完成退出操作
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
启动翻译员高级翻译
放弃
出口
[XYZ] $ telnet localhost 4444尝试xxx1 ...
已连接到localhost.localdomain(xxx1)。
转义字符为'^]'。
连接到INTERFACE LAYER心跳telnet本地主机4444
启动翻译员高级翻译
放弃
出口
[XYZ] $ telnet localhost 4444尝试xxx1 ...
已连接到localhost.localdomain(xxx1)。
转义字符为'^]'。
连接到界面层键入“ help”以获取命令列表
////在此程序挂起并且不执行任何操作之后
我没有在端口4444上运行同一台服务器,但是在本地测试中,在JSch中发出“ telnet localhost 80”和“ GET /”时,我得到了类似的行为。 在我看来,解决方法是对“连接已关闭”消息的准确性进行小心。 在我的情况下,服务器发送:
外部主机关闭连接。
而您的代码正在检查
外部主机关闭连接
(没有句号),因此循环永远不会终止。 您可以在https://github.com/pgleghorn/JSchTest中找到我的测试代码
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.