首页 > 解决方案 > 下面的代码是否正确连接到远程 Linux 主机并使用 Apache Mina 完成一些任务?

问题描述

我想从 Jsch 切换到 Apache Mina 来查询远程 Linux 主机并完成一些任务。我需要实现远程主机的列表文件、更改目录、获取文件内容、将文件放入远程主机等,

我能够使用 session.executeRemoteCommand() 成功连接并执行一些 shell 命令。

public byte[] getRemoteFileContent(String argDirectory, String fileName)
      throws SftpException, IOException {

    ByteArrayOutputStream stdout = new ByteArrayOutputStream();

    StringBuilder cmdBuilder = new StringBuilder("cat" + SPACE + remoteHomeDirectory);
    cmdBuilder.append(argDirectory);
    cmdBuilder.append(fileName);

    _session.executeRemoteCommand(cmdBuilder.toString(), stdout, null, null);
    return stdout.toByteArray();
}


public void connect()
 throws IOException {

_client = SshClient.setUpDefaultClient();
 _client.start();

ConnectFuture connectFuture = _client.connect(_username, _host, portNumber);
 connectFuture.await();
 _session = connectFuture.getSession();
shellChannel = _session.createShellChannel();
 _session.addPasswordIdentity(_password);

// TODO : fix timeout
 _session.auth().verify(Integer.MAX_VALUE);

_channel.waitFor(ccEvents, 200);
 }

我有以下问题,

  1. 如何在 API 级别(不是 Shell 命令级别)轻松地将 ZIP 文件发送到远程主机?以及 API 级别的所有其他操作。
  2. 我可以通过证书保护本地主机和远程之间的连接吗?
  3. 到目前为止,我正在使用 SSHD-CORE 和 SSHD-COMMON 2.2.0 版。这些库是否足够,还是我需要包含任何其他库?
  4. executeRemoteCommand() 是无状态的,我怎样才能保持状态?

标签: apache-mina

解决方案


我需要 sshd-sftp 及其 API 来完成文件传输工作。下面的代码得到了正确的 API, sftpClient = SftpClientFactory.instance().createSftpClient(clientSession); 在 sftpClinet 上,我调用了 read() 和 write() 方法来完成任务。这完全回答了我的问题。


推荐阅读