Jsch java ssh client is not getting disconnected a

2019-08-12 13:58发布

问题:

I am using java ssh client (http://www.jcraft.com/jsch/) to connect to remote machine and execute the command. The code is working fine till i connect to remote machine and execute the command. however, the issue is , the channel and session are not getting disconnected even after command executed successfully.

I have called session.disconnect and channel.disconnect as well but still the issue.

Here is my code:

    JSch jsch = new JSch();
    String host = null;
    host = "192.168.102.211";
    String privateKey = "C:\\test\\key";
    String cmd = "a";
    String command = "b";

    jsch.addIdentity(privateKey);
    Session session = jsch.getSession("user1", host, 22);
    Channel channel = session.openChannel("shell");

    UserInfo ui = new MyUserInfo() {
        public boolean promptYesNo(String message) {
            return true;
        }
    };
    session.setUserInfo(ui);
    session.connect(30000);

    OutputStream ops = channel.getOutputStream();
    PrintStream ps = new PrintStream(ops, true);

    channel.connect();
    ps.println(cmd);
    ps.println(command);
    ps.close();

    InputStream in = channel.getInputStream();
    byte[] bt = new byte[1024];
        while (in.available() > 0) {
        //  int i = in.read(bt, 0, 1024);
            for (int i = in.read(); i >=0; i--)
                    {
            String str = new String(bt, 0, i);
            System.out.print(str);
                    }
            break;

    }

 if (channel != null) {
        channel.disconnect();
        session.disconnect();
        System.out.println(channel.isConnected());
    }
}

Please suggest

回答1:

Update your question with a relevant code. just a hint, you should do something like.

} finally {
    if (channel != null) {
        Session session = channel.getSession();
        channel.disconnect();
        session.disconnect();
        System.out.println(channel.isConnected());
    }
}


标签: java ssh