Search code examples
javaauthenticationsshjschmulti-level

Multi-level SSH login in Java


I'm currently using JSch as the library for connecting to my remote server. In one of the scenarios, I should be able to log in to a server2, through server1. That is, I should first log in to server1, then ssh to another server (server2) and execute my command. Moreover, sometimes I should be able to connect to a server3 from server2.

So, basically, I'm looking for a way to have a multilevel ssh connection which I don't know how to handle in Java, as I cannot execute more than one command in each Exec Channel of a session.

Any insight will be appreciated.

Thanks, Reza


Solution

  • So you can already SSH to server1 without problems, and you're familiar with sending a command to run on that server.

    This is just a matter of recursion through the server layers, like Russian dolls. Let's assume that the command you want to run on server2 is ls (though the actual command doesn't affect this example). Then, if you were already logged into server1, you'd run this command as

    $ ssh server2 ls
    

    right?

    And right there we have both parts of the solution, because you already know how to run a command when logging into a host. SSH into server 1 and run that command, and you've got your multi-level login working.

    To extend this to three (or more) hosts, the idea is the same. If you were already logged into server2 and wanted to run the command, you'd run

    $ ssh server3 ls
    

    So if you're on server 1, you'd run

    $ ssh server2 ssh server3 ls
    

    hence your overall command is

    $ ssh server1 ssh server2 ssh server3 ls
    

    and at this point I think it's clear how this can be extended to arbitrary levels... :-)