JSch library to execute shell commands on a Unix

In today’s tutorial, we will explore the example of JSch. JSch is a tool in Java that allows us to establish an SSH connection. I have previously written a program to connect to a remote database on an SSH server. Today, I will be sharing a program that connects to an SSH-enabled server and executes shell commands. For this task, I will be utilizing JSch to establish the connection from a Java program.

Example of JSch

You have the option to download the JSch jar from its official website or obtain the JSch jars through the provided maven dependency.


Here is a basic program written in JSch to execute the command “ls -ltr” on the server.

import java.io.InputStream;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;

public class JSchExampleSSHConnection {

	 * JSch Example Tutorial
	 * Java SSH Connection Program
	public static void main(String[] args) {
	    String host="ssh.scdev.com";
	    String user="sshuser";
	    String password="sshpwd";
	    String command1="ls -ltr";
	    	java.util.Properties config = new java.util.Properties(); 
	    	config.put("StrictHostKeyChecking", "no");
	    	JSch jsch = new JSch();
	    	Session session=jsch.getSession(user, host, 22);
	    	Channel channel=session.openChannel("exec");
	        InputStream in=channel.getInputStream();
	        byte[] tmp=new byte[1024];
	            int i=in.read(tmp, 0, 1024);
	            System.out.print(new String(tmp, 0, i));
	            System.out.println("exit-status: "+channel.getExitStatus());
	          try{Thread.sleep(1000);}catch(Exception ee){}
	    }catch(Exception e){



If you encounter any issues with running the JSch example program, please inform me. This program demonstrates a simple method in JSch to establish an SSH connection in a Java program. The JSch jar file can be obtained from the official website.


More Tutorials

Common errors that occur when using Nginx for connections.(Opens in a new browser tab)

Using Telnet Commands in Linux/Unix(Opens in a new browser tab)

Server Configurations Frequently Used for Your Web Application(Opens in a new browser tab)

Spring Boot CLI(Opens in a new browser tab)

multithreading in Java that you need to know(Opens in a new browser tab)

Leave a Reply 0

Your email address will not be published. Required fields are marked *