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.
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.
I think there are many tools which include JSch and provide extra features on top of that…
- Sandeep
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
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
p0ET9r Kudos! What a neat way of thinking about it.
- Cheyenne
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
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
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
I have not tried it but please try it and let us know the results.
- Pankaj
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
Do you have user/password authentication of Key based authentication?
- Pankaj
I am also getting the same error… I do have username and password for the system which i have already used in the program. Can u please provide the solution for the same?
- Aditya
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
ls -l command is ok. But when i used for instance “chkconfig” command, exit status is 1. Why is it?
- Kadir Sert
Can you connect to same server using SSH login and run this command? Is it working there?
- Pankaj
hi, I tried to connect to router.But authentication is failing. I want to know,hostname corresponds to what? Thanks, Sindhu
- Sindhu
Its the name of the ssh system, try to ping your ssh server and see its working?
- Pankaj
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
Forgot the link I downloaded the files… Here it is! https://www.jcraft.com/jsch/
- MaT
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
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
You need to include the jar file to the project build path, if running from command line make sure you have jar file in classpath.
- Pankaj
I am also facing same problem as package com.jacraft.jsch does not exist I have set classpath as set CLASSPATH = C:\jdk1.8.0_25\bin;C:\jdk1.8.0_25\bin\jsch-0.1.51.jar;%path%;
- Rajendra