1. Introduction

SSH or Secure Shell is a network protocol used for secure communication between two computers over an unsecured network. In this short tutorial, we'll show how to connect to the SSH server, execute ls command (list files) on its console, and then return the console output. For this purpose, we'll be using Apache Mina SSHD, which supports the SSH protocol on both client and server-side.

2. Implementation

Apache Mina SSHD has a lot of available Maven dependencies (for example FTP, SCP, etc.), but since we're using only core functionalities, we'll only add core Maven dependency to our project:

<dependency>
    <groupId>org.apache.sshd</groupId>
    <artifactId>sshd-core</artifactId>
    <version>2.5.1</version>
</dependency>

Let's see how the code looks like:

import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.util.EnumSet;
import java.util.concurrent.TimeUnit;

import org.apache.sshd.client.SshClient;
import org.apache.sshd.client.channel.ClientChannel;
import org.apache.sshd.client.channel.ClientChannelEvent;
import org.apache.sshd.client.session.ClientSession;
import org.apache.sshd.common.channel.Channel;

public class ApacheSshdDemo {

 public String getFileList(String host, String username, 
   String password, int port, long defaultTimeout) throws Exception {
     SshClient client = SshClient.setUpDefaultClient();
     client.start();
     try (ClientSession session = client.connect(username, host, port)
      .verify(defaultTimeout, TimeUnit.SECONDS)
       .getSession()) {
         session.addPasswordIdentity(password);
         session.auth()
          .verify(defaultTimeout, TimeUnit.SECONDS);
         try (ByteArrayOutputStream responseStream = 
               new ByteArrayOutputStream();
              ByteArrayOutputStream errorStream = 
               new ByteArrayOutputStream();
              ClientChannel channel = 
               session.createChannel(Channel.CHANNEL_SHELL)){
             channel.setOut(responseStream);
             channel.setErr(errorStream);
             try {
                 channel.open()
                   .verify(defaultTimeout, TimeUnit.SECONDS);
                 try (OutputStream pipedIn = channel.getInvertedIn()) {
                     pipedIn.write("ls\n".getBytes());
                     pipedIn.flush();
                 }
                 channel.waitFor(EnumSet.of(ClientChannelEvent.CLOSED),
                  TimeUnit.SECONDS.toMillis(defaultTimeout));
                 String error = new String(errorStream.toByteArray());
                 if(!error.isEmpty()) {
                  throw new Exception(error);
                 }
                 return new String(responseStream.toByteArray());                   
             } finally {
                 channel.close(false);
             }
         }
     } finally {
         client.stop();
     }
 }
}

First, we create an SSHD session and then a client channel that we'll use to send a command and receive console output. Notice that SSHD asks for a timeout in many places. In the example above, we used a default timeout for all purposes.

3. Public SSH servers for testing

There are few open/public SSH servers that you can use for test purposes. Check this list for more details. 

4. Conclusion

In this tutorial, we saw how to connect to the SSH server with Java and Apache Mina SSHD library. If you want to use JSch (Java Secure Channel) for this purpose, check out this tutorial.