JSch: How to keep the session alive and up

jsch(); session
jsch session close
jsch get session
jsch session vs channel
jsch session and channel
jsch timeout
jsch sftp
jsch example

I'm writing Java GUI program for static route management using SSH. My code is as follows:

import com.jcraft.jsch.*;
import java.io.*;

public class Konsep {
    String status;
    static String username;
    static String hostname;
    String inputcommand;
    String output;
    static Session session;

    JSch jsch = new JSch();

    public String status(String stringstatus) {
        stringstatus = status;
        return stringstatus;
    }

    public String InputCommand(String inputcommandstatus) {
        inputcommandstatus = inputcommand;
        return inputcommandstatus;
    }

    public void connect(String usernamelokal, String hostnamelokal,
            String password, int port) {
        //        JSch jsch=new JSch();
        try {
            Session sessionlokal = jsch.getSession(usernamelokal,
                    hostnamelokal, port);
            sessionlokal.setPassword(password);
            UserInfo ui = new UserInfoku.Infoku();
            sessionlokal.setUserInfo(ui);
            sessionlokal.setTimeout(0);
            sessionlokal.connect();
            status = "tersambung \n";
            username = usernamelokal;
            hostname = hostnamelokal;
            session = sessionlokal;
            System.out.println(username + " " + hostname);
        } catch (Exception e) {
            System.out.println(e);
            status = "Exception = \n " + e + "\n";

        }
    }

    public void disconnect() {
        //        JSch jsch=new JSch();
        try {
            Session sessionlokal = jsch.getSession(username, hostname);
            //            System.out.println(username +" "+ hostname);
            sessionlokal.disconnect();
            status = "wes pedhoott \n";
        } catch (Exception e) {
            System.out.println(e);
            status = "Exception = \n " + e + "\n";
        }

    }

    public void addRoute() {
        //        JSch jsch=new JSch();
        System.out.println(username + " " + hostname);
        try {
            Session sessionlokal = session; // =jsch.getSession(username, hostname);
            Channel channel = sessionlokal.openChannel("exec");
            ((ChannelExec) channel).setCommand(inputcommand);
            channel.setInputStream(null);
            channel.connect();
            ((ChannelExec) channel).setErrStream(System.err);
            InputStream 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;
                }
                try {
                    Thread.sleep(1000);
                } catch (Exception ee) {
                }
            }

            channel.disconnect();
        } catch (Exception e) {
            System.out.println(e);
        }
    }
}      

The problem is when I call the connect method and then calling the addroute, the program returns

root 192.168.50.2
root 192.168.50.2
com.jcraft.jsch.JSchException: session is down

I've been trying to get session status with either

Session sessionlokal=session; //returns com.jcraft.jsch.JSchException: ChannelExec

or

Session sessionlokal=jsch.getSession(username, hostname); //returns session is down

I've also tried to use keepalive, but its not working either.

My intention is to create a session to host (log in), while leaving the session up, execute a command or commands and maybe executing other commands later, and then closing the session when its not needed (log out). I've been searching on this forum and I found this question but the code is create a method to define a command to execute first, and then creating the session, call the command's method and close the session.

Any ideas about how to do as I mentioned above ?

After trying Session.sendKeepAliveMsg() without success, I came to the following solution which seems to be rather stable:

private Session getSession() throws Exception {
    try {
        if (!session.isConnected()) {
            logger.info("Session successfully tested, use it again.");
            session.connect();
        }
    } catch (Throwable t) {
        logger.info("Session terminated. Create a new one.");
        session = jsch.getSession(user, host, port);
        session.setConfig(config);
        session.connect();
    }
    return session;
}

Update: Some days later it failed.

I tried to test it by killing the open session on the server. All prior versions I tested this way showed the exact same behavior, regardless whether the problem popped up after waiting some days or killing the server process, so I thought this test - and its outcome for the above solution - to be meaningful. Unfortunately, it isn't.

I'm going to try some other ways to fix it and keep you up to date.

Update 2: Final solution, guaranteed inelegant and working:

private Session getSession() throws Exception {
    try {
        ChannelExec testChannel = (ChannelExec) session.openChannel("exec");
        testChannel.setCommand("true");
        testChannel.connect();
        if(logger.isDebugEnabled()) {
            logger.debug("Session successfully tested, use it again.");
        }
        testChannel.exit();
    } catch (Throwable t) {
        logger.info("Session terminated. Create a new one.");
        session = jsch.getSession(user, host, port);
        session.setConfig(config);
        session.connect();
    }
    return session;
}

This version runs several weeks in a productive environment. Once a day I have the info message logged.

The costs of opening a channel and performing some do-nothing-command are somewhat annoying, but I found no other way to be definitely sure about the state of the session.

Java Code Examples com.jcraft.jsch.Session.setServerAliveInterval, Java Code Examples for com.jcraft.jsch.Session.setServerAliveInterval() Project: SqlSauce File: SshTunnel.java Source Code and License, Vote up, 6 votes keep alive too low or you might suffer from a breaking connection during start up  Jsch: how to keep the session alive and up I'm writing java GUI program for static route management using SSH. My code is as follows: import com.jcraft.jsch.*; import java.io.*; public class Konsep { String status; static String username; static String hostname; String inputcommand; String ou

You can try by invoking the following method before invoking Session#connect().

Session#setServerAliveInterval(int milliseconds)

Although I found one more function Session#sendKeepAliveMsg() which can be tried.

com.jcraft.jsch.Session.setServerAliveInterval java code examples , setPassword(password); // pinging server for every 1 minutes to keep the connection alive final int serverAliveIntervalInMillis = 60 * 1000; session. I've already tryed it with Session#setServerAliveInterval(int milliseconds) but it didn't work. Is there any posibility to keep the session and channel alive? I've seen the solution of this user but this doesn't work for me because it's important that the connection between server and service is always up.

JSch / Re: [JSch-users] Keeping the connection alive, Although it can't "wake up" a frozen connection it might prevent the situation to happen in the first place. More questions Does Jsch also support TCPKeepAlive  I'm not sure I completely understand the difference between the two but after doing some googling it seems that TCPKeepAlive is mainly used to detect lost peers (and then disconnect and start all over I guess) while ServerAliveInterval is used to actually keep the connection alive so that the remote end doesn't assume that we are gone.

Session (JSch API), Lists the registered remote port forwarding. int, getServerAliveCountMax(). Returns setting for the threshold to send keep-alive messages. Jsch - One Session Multiple Channels. Ask Question Asked 8 years, 9 months ago. Active 3 years, 4 months ago. JSch: How to keep the session alive and up. 0.

🤜 JSch: How to keep a session alive and up, Having tried Session.sendKeepAliveMsg() unsuccessfully, I came up with the following solution, which seems pretty stable: private Session getSession() throws  Silly me, it's all in the JDK docs. Looks like for my application I'll want to set socket.setSoTimeout(0); session.setTimeout(0); session.connect(60000) in order to achieve a 60 second timeout for connecting, but never drop the connection due to inactivity (i.e. wait forever until something happens).

Jsch ssh keep alive, How can I keep an SSH connection alive without actively using it. JSch: How to keep the session alive and up. java The following are top voted examples for  sets the server alive interval property. This is also as the timeout value (and nowhere else). If zero is specified, no keep-alive message must be sent. The default interval is zero.

Comments
  • nice solution, just one hint: I'd add testChannel.exit(); after successful check, otherwise you end up with one more sftp-server daemon processes on the sever side for each check
  • Thanks. Added testChannel.exit().
  • I had deadlock issues when opening multiple channels. Making getSession() synchronized solved this, but it's a bit of a performance hit. Do you know which part might need to be synchronized? Perhaps the test channel connect = disconnect?
  • ChannelExec doesn't have an .exit method (ver. 0.1.54 and 0.1.55)