首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用JSch在远程SSH会话上运行telnet命令后挂起执行

使用JSch在远程SSH会话上运行telnet命令后挂起执行
EN

Stack Overflow用户
提问于 2017-03-21 19:28:02
回答 1查看 1.1K关注 0票数 0

我正在寻找一种解决方案,采用SSH连接,然后通过java将Telnet连接到远程系统。由于只使用telnet连接,所以我可以在远程计算机上执行该特定命令。

在浏览了很多之后,我找到了这个答案"https://stackoverflow.com/questions/27146991/running-telnet-command-on-remote-ssh-session-using-jsch“,但是在执行"telnet 4444”之后,程序执行挂起&永远不会从while循环中出来。因此,在获得telnet连接后,我无法执行其他命令。

我的代码是:-

代码语言:javascript
复制
    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会话,同时通过putty手动执行,因为退出不起作用

代码语言:javascript
复制
    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.1.

连接到localhost.localdomain (x.1)。

转义字符是“^]”。

连接到接口层心脏跳动telnet本地主机4444

启动翻译程序ABCLOC高

退出

出口

XYZ$ telnet localhost 4444尝试x.1.

连接到localhost.localdomain (x.1)。

转义字符是“^]”。

连接到接口层,键入命令列表的“帮助”

/在此程序挂起之后&不执行任何操作

EN

回答 1

Stack Overflow用户

发布于 2017-03-31 14:33:55

在端口4444上运行的服务器与您不同,但在JSch中发出“80”和"GET /“的本地测试中也有类似的行为。在我的例子中,修正是要小心“连接关闭”消息的精确性。在我的例子中,服务器发送:

外部主机已关闭连接。

而您的代码正在检查

由外国主机关闭的连接

(没有句号),所以循环永远不会终止。您可以在https://github.com/pgleghorn/JSchTest找到我的测试代码

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42936473

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档