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:


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.setConfig("StrictHostKeyChecking", "no");
            channel = (ChannelExec) session.openChannel("exec");
            ByteArrayOutputStream responseStream = new ByteArrayOutputStream();
            ByteArrayOutputStream errorStream = new ByteArrayOutputStream();
            while (channel.isConnected()) {
            response = new String(responseStream.toByteArray());
            String errorResponse = new String(errorStream.toByteArray());
            if(!errorResponse.isEmpty()) {
                throw new Exception(errorResponse);
        } finally {
            if (session != null)
            if (channel != null)
        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.