Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to keep SSH connections alive using SSHJ?

I am developing a library that uses SSHJ for SFTP transfer. Since requests are frequent, I have wondered whether I could just keep the connection open.

Obviously, this will achieve nothing if the server frequently times out the connection. Since I have no control of the server, I have to keep the connection alive: With a regular SSH client, I could specify a ServerAliveInterval and have the client do it for me.

I'd like to do the same with SSHJ, but I do not know what message to send.

The SSH manual just states that ServerAliveInterval

Sets a timeout interval in seconds after which if no data has been received from the server, ssh(1) will send a message through the encrypted channel to request a response from the server.

So I'm wondering: What message is sent? How could I reproduce this message through SSHJ?

like image 793
Urs Reupke Avatar asked Apr 27 '12 13:04

Urs Reupke


People also ask

How long can an SSH connection last?

In theory, an SSH connection can last indefinitely. It can be explicitly terminated by either side at the SSH layer (with a FIN packet) or abnormally terminated at the TCP layer (with a RST packet). A RST can happen if one side sends a packet and doesn't get a TCP acknowledgement in a reasonable amount of time.

What is server alive interval SSH config?

3.1. This configuration is specifying the settings to be applied only when the SSH session is connected to the example domain. ServerAliveInterval is the amount of time in seconds before the client will send a signal to the server.


2 Answers

Sorry this isn't documented, but you can set a heartbeat:

https://github.com/hierynomus/sshj/blob/master/examples/src/main/java/net/schmizz/sshj/examples/RemotePF.java#L51

like image 169
shikhar Avatar answered Sep 27 '22 20:09

shikhar


Starting from version 0.11.0, you can use built-in KeepAliveProvider:

public class KeepAlive {

    public static void main(String... args)
            throws IOException, InterruptedException {
        DefaultConfig defaultConfig = new DefaultConfig();
        defaultConfig.setKeepAliveProvider(KeepAliveProvider.KEEP_ALIVE);
        final SSHClient ssh = new SSHClient(defaultConfig);
        try {
            ssh.addHostKeyVerifier(new PromiscuousVerifier());
            ssh.connect(args[0]);
            ssh.getConnection().getKeepAlive().setKeepAliveInterval(5); //every 60sec
            ssh.authPassword(args[1], args[2]);
            Session session = ssh.startSession();
            session.allocateDefaultPTY();
            new CountDownLatch(1).await();
            try {
                session.allocateDefaultPTY();
            } finally {
                session.close();
            }
        } finally {
            ssh.disconnect();
        }
    }
}

To send heartbeats, you may use KeepAliveProvider.HEARTBEAT.

like image 36
Marboni Avatar answered Sep 27 '22 21:09

Marboni