By Pankaj Kumar
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.
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.
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
I think there are many tools which include JSch and provide extra features on top of that…
- Sandeep
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
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
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
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
Hi Pankaj, I found your tutorials extremely useful. Lots to learn from your blogs. I have a requirement and would like to know your feedback. - Can we have more than one host login from the same java program? - how can we do x11 forwarding with this? I want to run a simple java - jar via ssh. the jar needs x11 forwarding and this fails with Jsch framework. is there any others ways to do it . Thanks in advance ! Roshan
- roshan
I am trying to run this program, but its taking ages after channel.connect(); and nothing happens after it. Please tell what could be the reason
- anjali
Hi Pankaj, Thanks a lot for the sample code. It has been very useful for me and it will allow me to build the tools that I was having in mind. Gracias y adiós, Tomeu
- Tomeu Mir
Hi Pankaj, Code is working after set the calss path like set classpath= c:\program files\Java\jdk1.5.0_22\bin;D:\UNIXTooL\jsch-0.1.47.jar;%path%; through command line. But once login into SSH , we have to provide the password second time also.So, on such cases what we supposed to do & how can we enter the password 2nd time on the same same session / channel. Plz provide sample code for the same. Regards, GKrishna.
- GEETHA KRISHNA
This code is working fine for me to execute a shell script placed on remote server(Wellogic in my case) from java program. Also code is working fine when i used the same code in a web application that is deployed on tomcat server. It ran script successfully. But when same application deployed on jBoss Server, shell script is not able to execute. Permissions are set to 777, and i am not getting any error or exception on server logs of JBoss. Exit status is also showing as 0. Please help as problem occurs when application deployed on JBoss while it works fine on tomcat.
- Joginder
Hi Pankaj, Thanks for your code. We facing strange issue, while working with your code. above code are works very well as a standalone java application. but when we call this java class inside the jsp. then it doesnt works. it gives class not found exceptions for " com.jcraft.jsch.JSch " and " com.jcraft.jsch.Session" jars, even we are included in build path. we convert this java program to jsp file and try to run this. but still its not runing as a jsp file. Please check it. make it in jsp… you will observe the error. please guide us to resolve this.
- vivek
I got error like this while executing your program… com.jcraft.jsch.JSchException: java.net.ConnectException: Connection refused at com.jcraft.jsch.Util.createSocket(Util.java:349) at com.jcraft.jsch.Session.connect(Session.java:215) at com.jcraft.jsch.Session.connect(Session.java:183) at test.NewClass.main(NewClass.java:32) Caused by: java.net.ConnectException: Connection refused at java.net.PlainSocketImpl.socketConnect(Native Method) at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339) at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200) at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182) at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392) at java.net.Socket.connect(Socket.java:579) at java.net.Socket.connect(Socket.java:528) at java.net.Socket.(Socket.java:425) at java.net.Socket.(Socket.java:208) at com.jcraft.jsch.Util.createSocket(Util.java:343) … 3 more BUILD SUCCESSFUL (total time: 1 second) Whats the problem in it?
- A.Mohamed Bilal
Error: Main method not found in class com.test105, please define the main method as: public static void main(String[] args) or a JavaFX application class must extend javafx.application.Applicatio
- th
hi Pankaj, while running your code i am getting the error:“com.jcraft.jsch.JSchException: java.net.ConnectException: Connection refused: connect”. can you please suggest me to solve this ASAP.
- shyam
I tried the program, it seems to work for listing kind of commands but when I execute a shell script e.g. a script having mkdir a b c command, it executes the script but do not create folders. I tried taking backup of mysql database, it performs the thing but is not creating .sql file. Am I missing something? many thanks ~Nix
- nix
hi pankaj, I got a Error from this code the error is com.jcraft.jsch.jschException:java.net.UnknownHostException what will be the error and how to resolve it.
- kumara
Hi, I have tried this, but how can call a shell script is particular directory?
- bhargavi
how to run this code in unix, i will get lot of error, it’s not working
- kumara
I am getting following error. Not sure why. Please suggest any solution: com.jcraft.jsch.JSchException: java.net.ConnectException: Connection refused: connect at com.jcraft.jsch.Util.createSocket(Util.java:349) at com.jcraft.jsch.Session.connect(Session.java:215) at com.jcraft.jsch.Session.connect(Session.java:183) at oehp.ssh.SSHCommandExecutor.main(SSHCommandExecutor.java:29) Caused by: java.net.ConnectException: Connection refused: connect at java.net.DualStackPlainSocketImpl.connect0(Native Method) at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79) at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339) at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200) at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182) at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172) at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392) at java.net.Socket.connect(Socket.java:579) at java.net.Socket.connect(Socket.java:528) at java.net.Socket.(Socket.java:425) at java.net.Socket.(Socket.java:208) at com.jcraft.jsch.Util.createSocket(Util.java:343) … 3 more
- Jayant
Hi pankaj i want to execute one command which is in another folder…i changed directory by using cd directory name.now i want to execute one command invoke_sat.sh how sholud i try for this one
- varsha
Hi Pankaj, I have a problem statement like there is a product installed on remote linux server. I need to instantiate it from junit script running on my local windows machine. I used JSch to connect, create session, open a channel, get inputstream. Now I want to import configuration and start the instance of the product, which i script in junit. But I am unable to do so. Any suggestions/guidance you can give? Many thanks in advance to revert.
- Nayana Ratnani
I want to automate putty with selenium/java code . Need to run scripts using putty . Can you help me how to communicate with java and putty.
- Teju
Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.
Full documentation for every DigitalOcean product.
The Wave has everything you need to know about building a business, from raising funding to marketing your product.
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
Scale up as you grow — whether you're running one virtual machine or ten thousand.
Sign up and get $200 in credit for your first 60 days with DigitalOcean.*
*This promotional offer applies to new accounts only.