Search code examples
apache-mina

Is the below code correct to connect to a remote Linux host and get few tasks done using Apache Mina?


I want to switch from Jsch to Apache Mina to query remote Linux hosts and to get the few tasks done. I need to achieve things like list files of a remote host, change directory, get file contents, put a file into the remote host etc.,

I am able to successfully connect and execute a few shell commands using session.executeRemoteCommand().

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

I have the following questions,

  1. How can I send a ZIP file to a remote host much easily in API level (not the Shell commands level)? And all other operations in API level.
  2. Can I secure a connection between my localhost and remote through a certificate?
  3. As of now, I am using SSHD-CORE and SSHD-COMMON version 2.2.0. Are these libraries enough or do I need to include any other libraries?
  4. executeRemoteCommand() is stateless how can I maintain a state?

Solution

  • I needed sshd-sftp and its APIs to get the file transfer work. Below code gets the proper API, sftpClient = SftpClientFactory.instance().createSftpClient(clientSession); On sftpClinet I called read() and write() methods get the task done. This answers my question fully.