2

I am using the sshj library for java.

I need to open an ssh session on a remote server, execute a command which could run for many minutes, and then continue on executing in my java code. Once the command running on the remote server is finished, i would like the ssh session to close, and the sshclient to disconnect.

I have seen the following code example:

public class Exec {
   public static void main(String... args) throws IOException {
        final SSHClient ssh = new SSHClient();
        ssh.loadKnownHosts();

        ssh.connect("localhost");
        try {
            ssh.authPublickey(System.getProperty("user.name"));
            final Session session = ssh.startSession();
            try {
                final Command cmd = session.exec("ping -c 1 google.com");
                System.out.println(IOUtils.readFully(cmd.getInputStream()).toString());
                cmd.join(5, TimeUnit.SECONDS);
                System.out.println("\n** exit status: " + cmd.getExitStatus());
            } finally {
                session.close();
            }
        } finally {
            ssh.disconnect();
        }
    }
}

Basically I don't want to wait for the command to finish (no cmd.join call) and I need the session.close() and ssh.disconnect() to be called automatically once the command has exited. Is this possible?

Amit
  • 15,217
  • 8
  • 46
  • 68
bob smith
  • 41
  • 6

1 Answers1

2

I may not be able to exactly answer my question, but maybe provide help for others trying to do something similar to what I was doing. When I posted, I was under the impression that the ssh session had to stay open for the command to finish, but I don't think that is the case.

So what I was trying to do was start a remote ssh session via java, and run a shell script on the remote machine. The shell script could take up to 10-15 mins to complete. I tested a short timeout (5 secs) and the script continued to run after the session was disconnected... which is what I wanted.

bob smith
  • 41
  • 6