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 JSch, a Java library that implements SSH2.

2. Implementation

First, let's add Maven dependency to our project:

<dependency>
    <groupId>com.jcraft</groupId>
    <artifactId>jsch</artifactId>
    <version>0.1.55</version>
</dependency>

Let's see how the code looks like:

import java.io.ByteArrayOutputStream;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;

public class JschDemo {

    public static void main(String args[]) throws Exception {
        String host = "your.ssh.server";
        String username = "username";
        String password = "password";
        int port = 22;
        String command = "ls";
        listFiles(username, password, host, port, command);
    }

    public static String listFiles(String host, String username, 
     String password, int port, String command) throws Exception {
        Session session = null;
        ChannelExec channel = null;
        String response = null;
        try {
            JSch jsch = new JSch(); 
            session = jsch.getSession(username, host, port);
            session.setPassword(password);
            session.setConfig("StrictHostKeyChecking", "no");
            session.connect();
            channel = (ChannelExec) session.openChannel("exec");
            channel.setCommand(command);
            ByteArrayOutputStream responseStream = new ByteArrayOutputStream();
            ByteArrayOutputStream errorStream = new ByteArrayOutputStream();
            channel.setOutputStream(responseStream);
            channel.setErrStream(errorStream);
            channel.connect();
            while (channel.isConnected()) {
                Thread.sleep(100);
            }
            response = new String(responseStream.toByteArray());
            String errorResponse = new String(errorStream.toByteArray());
            if(!errorResponse.isEmpty()) {
                throw new Exception(errorResponse);
            }
        } finally {
            if (session != null)
                session.disconnect();
            if (channel != null)
                channel.disconnect();
        }
        return response;
    }
}

First, we create a JSch session and add some configuration parameters to it. We can set StrictHostKeyChecking to no if we trust the SSH hosts we're connecting to. This means that JSch will not check if the host is among known hosts. If we set it to yes and the host is not in your known_hosts file, the application will throw an exception. 

Since we're planning to execute a command on the remote server, we'll use the ChannelExec channel that indicates to JSch that we're planning to use the remote shell.

Then, we'll set the command that will be executed on the remote shell by using channel.setCommand() method.

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 using Java and JSch library. If you want to use Apache Mina SSHD for this purpose, check out this tutorial.