How to run shell commands using SSH connection in Java

How to Run shell commands using SSH connection in Java

In this tutorial we will see how to run shell commands on a SSH enabled server using Java. I am using JSch java library to connect to remote ssh server and execute the shell commands.

You can download the latest version of JSch.jar file from the official website. If you are having a maven project, you can add the following maven dependency to download the jar.

Java program to run SSH commands

Below is a simple Java program to connect to SSH server and execute shell commands. The program has been written with JSch version 0.1.54.

Below is a sample output of the above program.

In the above program I have used a free public SSH server You can also use the same server for testing purpose. The program shows the output of executing the command ‘ls -ltr‘. This command is used to list the files and directories in long format, sorted by create date in reverse order.

In this tutorial you have learned the Java Program to run shell commands on SSH enabled server. You can get more examples of JSch from the official website.

The following two tabs change content below.
Working as a Java developer since 2010. Passionate about programming in Java. I am a part time blogger.
  1. Facing issue with non library commands how to execute them.
    Example ls -l, pwd, keystore… etc, these commands am able to execute when it come to custom commands givening the ksh not found.

    Could anyone suggest me the solution here.

  2. Not working for me. I’m try to connect RHEL via ssh from Windows machine.
    Then i run you script i get message on console:
    Kerberos username [My_local_username]:
    Kerberos password []:

    I don’t understand how to resolve this problem.

  3. i am facing a issue with this is that my UNIX command is a shell script which contain, 2 sub process scripts.
    when m executing this program its not waiting for those subprocess scripts to execute its directly jumping to end thus failing the script.
    the shell script is working in putty.

Add Comment

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