Java JSch Example to run Shell Commands on SSH Unix Server

Published on August 3, 2022


Java JSch Example to run Shell Commands on SSH Unix Server

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Today we will look into the JSch example tutorial. We can use JSch for creating an SSH connection in java. Earlier I wrote a program to connect to remote database on SSH server. Today, I am presenting a program that can be used to connect to the SSH-enabled server and execute shell commands. I am using JSch to connect to remote ssh server from java program.

JSch Example

You can download JSch jar from its official website. You can also get the JSch jars using below maven dependency.


Below is a simple JSch example program to run the “ls -ltr” command 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.journaldev.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){



Let me know if you face any problem with the execution of the JSch example program. It’s a pretty straight forward example of JSch to create an SSH connection in java program. You can download JSch jar file from its official website.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about us

About the authors
Default avatar


Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
DigitalOcean Employee
DigitalOcean Employee badge
September 6, 2021

Transfer file using scp command JSch jsch = new JSch(); Session session = jsch.getSession(“root”,“”,“22”); session.setPassword(“IQANIOT850”); session.setConfig(confing); session.connect(); ChannelExec channel= session.openChannnel(“exec”); channel.setPty(try); channel.setCommand(“scp file:// android_asset/situ.txt” root@ /mnt/internal_storage); After executing this command using SCP. we need to pass yes or no, then need to provide a password. After providing the password then file transfer is possible. How we can do this.Please help me to resolve this issue.

- Sitakanta

    DigitalOcean Employee
    DigitalOcean Employee badge
    August 27, 2021

    nice ! it works … just changed password to private key … Thank you

    - Hemant

      DigitalOcean Employee
      DigitalOcean Employee badge
      August 12, 2021

      Hi Pankaj, I need to enter password after executing pbrun command. In terminal I will get password question and need to enter the password after the question prompts. How can I automate the scenario. Please help me. Thanks

      - Sailu

        DigitalOcean Employee
        DigitalOcean Employee badge
        February 19, 2021

        Hi Pankaj, Great article. But I was looking for a way to implement this dynamically. Like a scenario where input commands are spread across time. For example, the user enters one command, then observes its output, then enters another, and then more. And all commands are sent over single channel How can that be achieved ?

        - Anmol Chadha

          DigitalOcean Employee
          DigitalOcean Employee badge
          July 25, 2020

          I am executing a command using JSch which starts a process on port 80 That process does not start. When I do ssh using putty and execute the same command, then also it does not work (after doing Jsch) Although, If I use the same command before doing Jsch, then that command works pretty fine. I am running this on Lighsail ubuntu instance.

          - Aakash

            DigitalOcean Employee
            DigitalOcean Employee badge
            May 25, 2020

            For example I try to change txt file. Manually in ubuntu command line the command works. Your code is running without errors but the txt file is not changed

            - Oleksandr Mudryi

              DigitalOcean Employee
              DigitalOcean Employee badge
              May 25, 2020

              Hi. Could you help me? When I try to setCommand(“sudo apt install …”) - command with some action -> this script doesn’t work. When I set this command manually in linux console it works. I my testing, your code works only when we need to print information from console. How can I do some action by your code? Maybe need to use another protocol

              - Oleksandr Mudryi

                DigitalOcean Employee
                DigitalOcean Employee badge
                May 24, 2020

                Hi Pankaj, Thanks for the solution but it seems I am facing issue while executing the command, I am able to connect my server but command execution is not happening. I am getting this error 👇 Connected “ls” isn’t allowed to be executed. exit-status: 1 DONE Could you please help me with this, it will be great help. Thank you in advance.

                - Shashank Jha

                  DigitalOcean Employee
                  DigitalOcean Employee badge
                  April 24, 2020

                  SHELL PARSER FAILURE: ‘echo’ - no matching entry found: I am getting this error for every command I am trying to execute. Please help

                  - Palak

                    DigitalOcean Employee
                    DigitalOcean Employee badge
                    April 18, 2020

                    How to open the command prompt using session.openChannel and run the bat file?

                    - Preethi

                      Try DigitalOcean for free

                      Click below to sign up and get $200 of credit to try our products over 60 days!

                      Sign up

                      Join the Tech Talk
                      Success! Thank you! Please check your email for further details.

                      Please complete your information!

                      Featured on Community

                      Get our biweekly newsletter

                      Sign up for Infrastructure as a Newsletter.

                      Hollie's Hub for Good

                      Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

                      Become a contributor

                      Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

                      Welcome to the developer cloud

                      DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

                      Learn more
                      DigitalOcean Cloud Control Panel