Search code examples
javaapache-minasshd

Using SSH connection for inter application communication


I want to write an application that would be a custom SSH server with two types of connection:

  • A sync channel, where clients type a command and the server would return the output
  • An stream channel where the user connects and starts reading the IO, the server publishes data continuously.

I am doing that in Java, I think Apache Mina SSHD in the right tool for that. I managed to write some code for authentication (thanks to resources found on the net) and could run the /bin/sh on my connection so I am all setup I guess. The problem is that from now I am stuck, due to lack of knowledge on how these things works and how Mina works specifically.

Basically I would need to have access to the input and output stream for each SSH connection, after that I can sort out things on my own, buy what's the right way to get that?

Should I make a custom Channel ? A custom Shell ? A custom set of commands ?

Could any one point me to resources on the subject ?


Solution

  • I have found the solution:

    First you have to implement a Command factory, which is done as follow:

    class CommandFactory extends Factory[Command] {
    
      override def create():Command = {
        new Command() {
          def destroy() {}
    
          def setInputStream(in: InputStream) {}
    
          def setErrorStream(err: OutputStream) {}
    
          def setOutputStream(out: OutputStream) {}
    
          def start(env: Environment) {}
    
          def setExitCallback(callback: ExitCallback) {}
        }
      }
    }
    

    Then you set up your ssh server like that:

    sshd.setShellFactory(new CommandFactory())
    

    Of course you can extend the implementation to pass anything you need to the command.

    The implementation of the command is where you define the behaviour of your shell.