我怎样才能使 JSch 中的会话持续更长时间?

How can I make a session in JSch to last longer?

我是 JSch 的新手,我正在使用它连接到远程 linux 机器。我正在创建一个会话并打开一个通道以在 linux 机器上执行命令。该命令执行并给出输出需要将近半个小时。但是会话在 15 分钟后过期。在命令完成执行之前,我需要会话处于活动状态。我怎样才能使会话持续更长时间?

即使使用 sendKeepAliveMsg() 功能也不会使会话保持活动状态不超过 15 分钟。

我使用的代码如下

JSch jsch=new JSch();
java.util.Properties config = new java.util.Properties(); 
config.put("StrictHostKeyChecking", "no");
Session session = null;
try
{
    session = jsch.getSession(user,client_ip,22);
    session.setPassword(secure_pwd);
    session.setConfig(config);
    session.connect();
    session.sendKeepAliveMsg();
    Channel channel = null;
    channel = session.openChannel("exec");
    ((ChannelExec)channel).setCommand(command);
    InputStream in = null;
    in = channel.getInputStream();
    channel.connect();
    byte[] tmp=new byte[1024];
    while(true)
    {
        while(in.available()>0)
        {
            int i=in.read(tmp, 0, 1024);
            if(i<0)
                break;
            System.out.print(new String(tmp, 0, i));
        }
        if(channel.isClosed())
        {
            System.out.println("exit-status: "+channel.getExitStatus());
            break;
        }
    }
}
catch(Exception e)
{
    System.out.println(e.toString());
}

提前致谢

可以使用以下方法调整 jsch 的空闲超时 setServerAliveInterval

另外一些其他连接相关的超时也可以在代码中指定,例如

session.connect(5000);

您必须定期致电 sendKeepAliveMsg

启动时调用一次无效。

虽然更容易(@Aniruddh 也回答了)让 JSch 自动发送保活。只需调用 Session.setServerAliveInterval.