Tutorial

Java JSch Example to run Shell Commands on SSH Unix Server

Published on August 3, 2022
Default avatar

By Pankaj

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.

<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 us


About the authors
Default avatar
Pankaj

author

Still looking for an answer?

Ask a questionSearch for more help

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

Transfer file using scp command JSch jsch = new JSch(); Session session = jsch.getSession(“root”,“192.168.0.1”,“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@192.168.0.1: /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

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    August 27, 2021

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

    - Hemant

      JournalDev
      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

        JournalDev
        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

          JournalDev
          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

            JournalDev
            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

              JournalDev
              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

                JournalDev
                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

                  JournalDev
                  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

                    JournalDev
                    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!

                      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