Tutorial

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

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.

<dependency>
    <groupId>com.jcraft</groupId>
    <artifactId>jsch</artifactId>
    <version>0.1.53</version>
</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";
	    try{
	    	
	    	java.util.Properties config = new java.util.Properties(); 
	    	config.put("StrictHostKeyChecking", "no");
	    	JSch jsch = new JSch();
	    	Session session=jsch.getSession(user, host, 22);
	    	session.setPassword(password);
	    	session.setConfig(config);
	    	session.connect();
	    	System.out.println("Connected");
	    	
	    	Channel channel=session.openChannel("exec");
	        ((ChannelExec)channel).setCommand(command1);
	        channel.setInputStream(null);
	        ((ChannelExec)channel).setErrStream(System.err);
	        
	        InputStream in=channel.getInputStream();
	        channel.connect();
	        byte[] tmp=new byte[1024];
	        while(true){
	          while(in.available()>0){
	            int i=in.read(tmp, 0, 1024);
	            if(i<0)break;
	            System.out.print(new String(tmp, 0, i));
	          }
	          if(channel.isClosed()){
	            System.out.println("exit-status: "+channel.getExitStatus());
	            break;
	          }
	          try{Thread.sleep(1000);}catch(Exception ee){}
	        }
	        channel.disconnect();
	        session.disconnect();
	        System.out.println("DONE");
	    }catch(Exception e){
	    	e.printStackTrace();
	    }

	}

}

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 our products

About the author(s)

Pankaj Kumar
Pankaj Kumar
See author profile
Category:
Tutorial
Tags:

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.

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
February 21, 2011

I think there are many tools which include JSch and provide extra features on top of that…

- Sandeep

JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
February 22, 2011

I found out that JSch is easy to learn and worked well in my case. If you have known some other tools, please comment. I will also have a look at them.

- Pankaj

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    February 22, 2011

    Apache mina provides ssh server and client libraries in java.

    - kpolo

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      February 22, 2011

      I thought JSch a kinda low level API. When I needed to dispatch some ssh job I prefered to use jsch-ant taks through groovy AntBuilder

      - Paulo

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      April 11, 2011

      p0ET9r Kudos! What a neat way of thinking about it.

      - Cheyenne

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        June 30, 2011

        I tried this program but no luck. I am able to connect to the server. Upto line 36 everything works fine. But the program is going in an infinite loop, beacsue the in.available is never greater than zero. I am not sure why the input stream is empty. Any input is appreciated.

        - Thomas

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        October 17, 2012

        I am not sure what is the problem at your end but it works fine for me, I have tried it on multiple servers. Can you post the exception stack trace?

        - Pankaj

          JournalDev
          DigitalOcean Employee
          DigitalOcean Employee badge
          January 26, 2012

          All good. thanks for code. But I want to ask , in client can I open image from server use this API? Thanks, Best regards, rufatet

          - Rufatet

          JournalDev
          DigitalOcean Employee
          DigitalOcean Employee badge
          October 17, 2012

          I have not tried it but please try it and let us know the results.

          - Pankaj

            JournalDev
            DigitalOcean Employee
            DigitalOcean Employee badge
            February 22, 2012

            use “\n” if you want to execute multiple commands in one string.

            - Haritosh

              JournalDev
              DigitalOcean Employee
              DigitalOcean Employee badge
              April 10, 2012

              I have tried this program and I am getting an error like com.jcraft.jsch.JSchException: Auth fail Exceptioncom.jcraft.jsch.JSchException: Auth fail at com.jcraft.jsch.Session.connect(Session.java:482) at com.jcraft.jsch.Session.connect(Session.java:160) at TestUnix.main(TestUnix.java:21) TestUNix is my classname Can you please help in finding resolution for this.

              - Saurabh

              JournalDev
              DigitalOcean Employee
              DigitalOcean Employee badge
              October 17, 2012

              Do you have user/password authentication of Key based authentication?

              - Pankaj

                JournalDev
                DigitalOcean Employee
                DigitalOcean Employee badge
                July 12, 2018

                Try and see the example provided in link bellow. Most likely public key authentication is established on the server and password only is not enough https://wiki.jsch.org/index.php?Manual%2FExamples%2FJschPubkeyAuthExample

                - Deividas

                  JournalDev
                  DigitalOcean Employee
                  DigitalOcean Employee badge
                  May 23, 2012

                  ls -l command is ok. But when i used for instance “chkconfig” command, exit status is 1. Why is it?

                  - Kadir Sert

                  JournalDev
                  DigitalOcean Employee
                  DigitalOcean Employee badge
                  October 17, 2012

                  Can you connect to same server using SSH login and run this command? Is it working there?

                  - Pankaj

                    JournalDev
                    DigitalOcean Employee
                    DigitalOcean Employee badge
                    July 11, 2012

                    hi, I tried to connect to router.But authentication is failing. I want to know,hostname corresponds to what? Thanks, Sindhu

                    - Sindhu

                    JournalDev
                    DigitalOcean Employee
                    DigitalOcean Employee badge
                    October 17, 2012

                    Its the name of the ssh system, try to ping your ssh server and see its working?

                    - Pankaj

                      JournalDev
                      DigitalOcean Employee
                      DigitalOcean Employee badge
                      January 8, 2013

                      Hi Pankaj and All, I am a total new Java developer. I am currently trying to run your code, since I am trying to open an ssh session with a server ang giving simple commands to it. However, I always take error messages for the imported classes like the following: package com.jacraft.jsch does not exist I downloaded the .jar files and the .zip files from the following address and I copied them in the Java folder of my C:. I also set the classpath and path variables again. However, I always take the same error message. Kindly please, anyone, give me your lights!!! Thanks a lot!!! MaT

                      - MaT

                      JournalDev
                      DigitalOcean Employee
                      DigitalOcean Employee badge
                      January 8, 2013

                      Forgot the link I downloaded the files… Here it is! https://www.jcraft.com/jsch/

                      - MaT

                        JournalDev
                        DigitalOcean Employee
                        DigitalOcean Employee badge
                        January 8, 2013

                        Are you trying to run the program from Eclipse or any other Java IDE? or via command line. Since you are new, there might be some issues with setting classpath, so please try to run through IDE.

                        - Pankaj

                          JournalDev
                          DigitalOcean Employee
                          DigitalOcean Employee badge
                          August 28, 2013

                          Hi MaT, I am having the same problem. Did you ever get it resolved? If so, can you share the resolution? Thanks, Don

                          - Don Freeman

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

                            Please complete your information!

                            Become a contributor for community

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

                            DigitalOcean Documentation

                            Full documentation for every DigitalOcean product.

                            Resources for startups and SMBs

                            The Wave has everything you need to know about building a business, from raising funding to marketing your product.

                            Get our newsletter

                            Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

                            New accounts only. By submitting your email you agree to our Privacy Policy

                            The developer cloud

                            Scale up as you grow — whether you're running one virtual machine or ten thousand.

                            Get started for free

                            Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

                            *This promotional offer applies to new accounts only.