Report this

What is the reason for this report?

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

Pankaj Kumar
Pankaj Kumar
Author
See author profile

Java and Python Developer for 20+ years, Open Source Enthusiast, Founder of https://www.askpython.com/, https://www.linuxfordevices.com/, and JournalDev.com (acquired by DigitalOcean). Passionate about writing technical articles and sharing knowledge with others. Love Java, Python, Unix and related technologies. Follow my X @PankajWebDev

Category:
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?

Was this helpful?

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

- Sandeep

Apache mina provides ssh server and client libraries in java.

- kpolo

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

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

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

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

- Haritosh

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

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

- Kadir Sert

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

- Sindhu

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

Awesome

- Jayashree

Pankaj, Thanks for the tutorial first. When I tried running, I am getting following errors: 1. channel.isClosed() is not found, says there it is not defined. 2. null pointer exception when I commented the lines which is giving me compilation issues. It says as below: java.lang.NullPointerException at com.jcraft.jsch.UserAuthNone.start(Unknown Source) at com.jcraft.jsch.Session.connect(Unknown Source) at com.ssh2.SSHCommandExecutor.main(SSHCommandExecutor.java:36) I am unable to proceed, can you help me? FYI, I have added only jar to this project namely, jsch-0.1.16.jar. Please validate.

- Natraj A

Thank you very much Pankaj. Can you please extend this coding with code to pass the output of command to a file or variable?

- Rajan Kurunju

Hi Pankaj, Great post I must say, but I’m curious to know if it’s possible to run a telnet command within a ssh session or an extra ssh session on top of the current session? If yes how can I establish that? Greetinsgs, Edgar

- Edgar

Thanx for such a wonderful code, i just want to run GUI based commands(xclock, xterm) or jar files instead of "ls -ltr"on remote linux server from linux client machine. i am not able to do so. I want X enabled ssh connection to server from my linux machine and execution of commands like xclock, xterm and java -jar sample.jar. look forward to your reply

- Abhinav

Can anyone reply for my question?

- Abhinav

Hi. I have question. How will the code if I need to run on the remote side of a lot of command (more than 500), the command are in the TXT file. Need to get the answer of the system after any command. Thanks.

- Alexander

Hello Pankaj, How will the code if I need to run on the remote side of a lot of teams (more than 500), the teams are in the TXT file. Need to get the answer of the system after any command. Thanks.

- Alexander

Hi Pankaj, I am Pretty Much familiar to this code, I need small help in this. I am doing SSH to linux machine and login to root I am unable to read Password Prompt after executing sudo command Please help me. Thanks in Advance

- Kalyan

Hey i am able to make ssh connection with PUTTY client but when i try the same with java code it gives “AUTH CANCEL” error so any help???

- Ankit

I want to execute multiple unix command through java code. let say first command 1.cd SCS 2. ls -lrt i want to list all the files of SCS folder.What changes have to make in above code.

- Ashish Dugar

Thanks for the tutorial first. When I tried running, I am getting following errors: java SSHCommandExecutor Exception in thread “main” java.lang.NoClassDefFoundError: com/jcraft/jsch/JSch at SSHCommandExecutor.main(SSHCommandExecutor.java:24) Caused by: java.lang.ClassNotFoundException: com.jcraft.jsch.JSch at java.net.URLClassLoader$1.run(URLClassLoader.java:217) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:205) at java.lang.ClassLoader.loadClass(ClassLoader.java:321) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:294) at java.lang.ClassLoader.loadClass(ClassLoader.java:266) at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:334) Can you please help in finding resolution for this.

- Huynh Duy

Can we connect to Windows system from Linux machine using Java Code. After successfully establishing the the connection we need to copy one file from linux to windows machine and we need to execute one command on windows machine. Is this possible using java??? Thanks&Regards M.Vikranth

- vikranth

Thanks Pankaj for this. looking forward to have more add ons on this program like change to SuperUser and then execute a command e.g “mv” command

- Rahul

I tried this program… working perfectly … but as soon as I execute the program I m seeing “Kerberos username/password” msg in the console. If I enter the correct password only I could see the output… But I want do it in some other way… like as soon as I execute the program it should show the results without asking for username/password … Can u suggest me something about this…?

- Nagaraj

It is working fine with command “ls -ltr” but when I execute “rm -r ABC” it’s not executing. Actually I need to remove the dir (say ABC) and want to create dir ABC for one of my task. So in between the removal of dir and creating new dir I have added thread so my code goes like this below : From line 31 ((ChannelExec)channel).setCommand(“rm -r ABC”); Thread.sleep(10000); ((ChannelExec)channel).setCommand(“mkdir ABC”); But ((ChannelExec)channel).setCommand(“rm -r ABC”); is not working. Can I get an help to resolve this issue. Thanks in advance.

- Manoj

Hi, I am getting below exception when tried to run code from Unix server com.jcraft.jsch.JSchException: Auth fail at com.jcraft.jsch.Session.connect(Session.java:464) at com.jcraft.jsch.Session.connect(Session.java:158) Please help.

- Amol

The code is working fine for me. I made a small modification to it and trying to grep a line from a file in the remote server. If the file is missing it simply enters the infinite loop while(true). I just guessed the if(channel.isclosed()) is returning false if the file is not available. Please help me with the solution.

- shalini

Hi Pankaj, You got an excellent blog, Super !!! Now regarding my problem, I am stuck with connecting ubuntu server through java. Actually I am into selenium automation and I am currently automating a scenario where I need to connect to an ubuntu server and edit certain XML, which would reflect in UI (kind of stub testing). With your code I can connect to the tunnel easily, however I am not able to connect to the server. Usually we connect to the tunnels first using putty and then connect to the server to edit its XML. Please let me know how do I achieve this. Moreover some of the commands are not working , like “ll”

- Souvik

This code work on my system… thank you… please post Java Program to run commands on TELENET enabled System

- Ashok Kumar

Thank you Pankaj i spend lot of time on this to get “tail -f” from remote machine for log file.

- Dileep

hi, i’m try using this code. but unsuccessfully. i got this message: com.jcraft.jsch.JSchException: Auth fail at com.jcraft.jsch.Session.connect(Unknown Source) at com.jcraft.jsch.Session.connect(Unknown Source) any setting that i should do in that server

- noo

When i tried to execute zip xyz.zip xyz command program is unable to create a zip on remote server. Please check once and let me know if any one tried this.

- Thanks for the post

This is really very useful, kindly let me know how can I execute multiple commands in this program

- Nazeer

Hi Pankaj, Thanks for posting this code it is really useful . I have one query that how can i fire more than one command in same session . Suppose my first command is “telnet xyz.zyz.zuz” it works fine . Than prompts come like this Username: I want to enter username . How can i do this. Please help Regards Vipin

- Vipin ahuja

Hi Pankaj, I have installed a cygwin openssh on a remote windows server and trying to run a batch file remotely. My code is something like the one you posted above. I can execute the bat script but when it comes to predefined varibales in batch file like %Date% then it is not executed. I think that the user that is executeing the the script via ssh does not have access to system variables because it does not open a shell. Can you please tell me how to change the above code to parse the .profile. Thanks and best regards mkz

- mkz

Super bro… It’s working great… Thank you… :)

- Kishore Garapati

Hi Pankaj, I am new to Java and what all i need is connect to remote server, execute shell script, script generates output file which i need to copy back to local machine. Could you please help me on this. Regards Satish Vemuri

- Satish Vemuri

Great. Thanks a lot. I was searching for it for past days but in vain.And atlast, I got it right here.

- Vaishnavi

I tried this and get the following error. Doe’s this mean it can’t connect? java.lang.NullPointerException at conntecttoDB8.SSHCommandExecutor.main(SSHCommandExecutor.java:26)

- John W Schlinz

Creative CommonsThis work is licensed under a Creative Commons Attribution-NonCommercial- ShareAlike 4.0 International License.
Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

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.