Search code examples
javalinuxsessionsshjsch

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


I am new to JSch and i am using it to connect to a remote linux machine. I am creating a session and opening a channel to execute a command on the linux machine. This command takes nearly half an hour to execute and give an output. But the session expires after 15 minutes. I need the session to be active till the command completes execution. How can I make the session last longer?

Even the usage of sendKeepAliveMsg() function is not keeping the session active for not more than 15 minutes.

The code i am using is as below

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());
}

Thanks in advance


Solution

  • You have to call the sendKeepAliveMsg regularly.

    Calling it once at start has no effect.

    Though easiers is (as @Aniruddh also answered) to let JSch send the keepalives automatically. Just call Session.setServerAliveInterval.