使用SSH连接进行应用程序间通信

时间:2012-10-05 11:41:46

标签: java apache-mina sshd

我想编写一个应用程序,它是一个具有两种连接类型的自定义SSH服务器:

  • 同步通道,其中客户端键入命令,服务器将返回输出
  • 用户连接并开始读取IO的流通道,服务器不断发布数据。

我在Java中这样做,我认为Apache Mina SSHD就是正确的工具。我设法编写了一些用于身份验证的代码(感谢网上找到的资源),并且可以在我的连接上运行/ bin / sh,所以我想我都是设置的。问题是,从现在开始,由于缺乏关于这些事情如何运作以及Mina如何专门工作的知识,我才陷入困境。

基本上我需要访问每个SSH连接的输入和输出流,之后我可以自己解决问题,买什么是正确的方法来获得它?

我应该制作自定义频道吗?自定义Shell?一组自定义命令?

有没有人能指出我有关这个问题的资源?

2 个答案:

答案 0 :(得分:2)

我找到了解决方案:

首先,你必须实现一个Command工厂,完成如下:

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) {}
    }
  }
}

然后你设置你的ssh服务器:

sshd.setShellFactory(new CommandFactory())

当然,您可以扩展实现以将所需的任何内容传递给命令。

该命令的实现是您定义shell行为的地方。

答案 1 :(得分:0)

这是我对问题本身发表的评论的后续跟进。

要允许客户端(客户端)直接访问远程计算机(服务器)上的端口,或通过SSH访问与服务器(网关)在同一网络上的另一台计算机,您只需使用-L标志。

直接从客户端到服务器(客户端计算机上的端口8080将隧道连接到服务器上的80):

ssh -L 8080:localhost:80 server

通过网关从客户端到服务器(客户端计算机上的端口8080将隧道连接到服务器上的80):

ssh -L 8080:server:80 gateway

在ssh的手册页中,以下是使用-L标志的方法:

     -L [bind_address:]port:host:hostport
         Specifies that the given port on the local (client) host is to be
         forwarded to the given host and port on the remote side.  This
         works by allocating a socket to listen to port on the local side,
         optionally bound to the specified bind_address.  Whenever a
         connection is made to this port, the connection is forwarded over
         the secure channel, and a connection is made to host port
         hostport from the remote machine.  Port forwardings can also be
         specified in the configuration file.  IPv6 addresses can be
         specified by enclosing the address in square brackets.  Only the
         superuser can forward privileged ports.  By default, the local
         port is bound in accordance with the GatewayPorts setting.
         However, an explicit bind_address may be used to bind the
         connection to a specific address.  The bind_address of
         ``localhost'' indicates that the listening port be bound for
         local use only, while an empty address or `*' indicates that the
         port should be available from all interfaces.
相关问题