Search code examples
javasshsudossh-keys

Execute an ssh connection as a different user in Java


I have a web server (jetty) that needs to perform operations on a remote host using ssh. The server runs as root and I would like it to stay that way.

On the webServer machine, as root, I can run sudo -su user ssh user@sshServer.com. This command opens an ssh session to sshServer using "user" as the user. The nice thing about this is that it starts the ssh session using user's ssh-keys file and does not require a password.

I would like to mimic this operation in Java. I've tried using several ssh libraries but couldn't get it to work. Whenever I try to connect as a different user, I am required to provide user's password. In other words, I can ask Java to logon to the sshServer as "user" but I can't ask Java to run the ssh-connection-command as "user". I believe that the keys file will be used only when executing the ssh-connection-command as "user".

Please note that user is my designated user for logging on to the sshServer. root itself doesn't have an ssh keys file and it is not a registered user that I can logon to sshServer with. I'd like to avoid storing user's password in the code or via some other obfuscation method. I also can't create other users whose passwords I can jeopardize in any way.

If someone knows of a library that will allow this or an alternate way to perform the operation, I'd be grateful.


Solution

  • JSCH certificate based authentication:

    JSch jsch = new JSch();
    
    // Here privateKey is a file path like "/home/me/.ssh/secret_rsa "
    // passphrase is passed as a string like "mysecr"
    jsch.addIdentity(privateKey, passphrase);
    
    session = jsch.getSession(user, host, port);
    session.setConfig("StrictHostKeyChecking", "no"); 
    // Or yes, up to you. If yes, JSch locks to the server identity so it cannot
    // be swapped by another with the same IP.
    
    session.connect();
    channel = session.openChannel("shell");
    out = channel.getOutputStream();
    channel.connect();
    

    HTH,

    Gal