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
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
Use the latest JSCH jar, current version is 0.1.50 and above code is tested with it and working fine.
- Pankaj
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
In above program, it’s printing the output to console, you have all the data that returns from the command execution, you can write it to file or send to any other methods also, it’s up to you and your requirements. If you are new to Java Files and IO, please go through Java IO Tutorial
- Pankaj
UserInfo ui=new MyUserInfo(); session.setUserInfo(ui); session.connect(); String command=JOptionPane.showInputDialog(“Enter command”, “set|grep SSH”); Channel channel=session.openChannel(“exec”); ((ChannelExec)channel).setCommand(command); I am unable to run ls $EMS_CONFIG_HOME etc. even echo $VARIABLE is not working. Some issue with $VARIABLES. i get exit status 0. Any solution?
- Karthikeyan
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
Sorry for late reply but I haven’t explored it that much. Let others know through comments if you have found anything.
- Pankaj
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
I think the reason is similar to why can’t we write a simple shell script to achieve this. Since a new password prompt comes up, the script is unable to send the password and I am not aware of any way to do it. But there should be something like this because its a common scenario, please dig deep and I am sure you will find something.
- Pankaj
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
Its not working because SSH is not supported in Windows. Putty software provides utility software for SSH.
- Pankaj
Is this code will not work in windows system.
- Subhasish Choudhury
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
Use the latest JSCH jar, current version is 0.1.50 and above code is tested with it and working fine.
- Pankaj
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
In above program, it’s printing the output to console, you have all the data that returns from the command execution, you can write it to file or send to any other methods also, it’s up to you and your requirements. If you are new to Java Files and IO, please go through Java IO Tutorial
- Pankaj
UserInfo ui=new MyUserInfo(); session.setUserInfo(ui); session.connect(); String command=JOptionPane.showInputDialog(“Enter command”, “set|grep SSH”); Channel channel=session.openChannel(“exec”); ((ChannelExec)channel).setCommand(command); I am unable to run ls $EMS_CONFIG_HOME etc. even echo $VARIABLE is not working. Some issue with $VARIABLES. i get exit status 0. Any solution?
- Karthikeyan
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
Sorry for late reply but I haven’t explored it that much. Let others know through comments if you have found anything.
- Pankaj
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
I think the reason is similar to why can’t we write a simple shell script to achieve this. Since a new password prompt comes up, the script is unable to send the password and I am not aware of any way to do it. But there should be something like this because its a common scenario, please dig deep and I am sure you will find something.
- Pankaj
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
Its not working because SSH is not supported in Windows. Putty software provides utility software for SSH.
- Pankaj
Is this code will not work in windows system.
- Subhasish Choudhury
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
You can create command string like this “cd SCS;ls -ltr” and execute it. I have checked it and it works fine.
- Pankaj
Thanks pankaj… One more doubt… Above code help me in login on the server but after login I have to add myself as superuser. I have to execute the /usr/seos/bin/sesu command after this command is hit on Unix it will ask for password. what changes are required for this.
- Ashish Dugar
I am sorry but I haven’t explored this scenario, why don’t you try to use Expect script, you can find about that in following article: https://www.journaldev.com/1405/expect-script-example-for-ssh-and-su-login-and-running-commands
- Pankaj
I want to run more than one command… but the next command based on previous command output. I mean I want to mimic the putty session… how to do that
- vandana
Hi Pankaj, saw ur solution it worked for me for a single command but i want to pass “DIR=”/etc/httpd/" if [ -d “$DIR” ]; then # Take action if $DIR exists. # echo “Installing config files in ${DIR}…” fi" this command also i saved it in .sh file on my windows system not the unix can i run this file using setcommand if yes how plz help
- sangeeta
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
It looks like JSCH jar is not in classpath.
- Pankaj
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
Hello I am facing the same problem. After i run the program, kerberose username and password is asked for. I want the program to directly give the result. Can someone pose a solution? Thanks
- Pari
java.util.Properties config = new java.util.Properties(); config.put(“StrictHostKeyChecking”, “no”); config.put(“PreferredAuthentications”, “publickey,keyboard-interactive,password”); use this code to avoid kerberose login problem
- Joginder
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
Does user have access to remove the directory? Try with “rm -rf” command.
- Pankaj
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
I haven’t tried this scenario where multiple logins are required.
- Pankaj
This code work on my system… thank you… please post Java Program to run commands on TELENET enabled System
- Ashok Kumar
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
You can create command string like this “cd SCS;ls -ltr” and execute it. I have checked it and it works fine.
- Pankaj
Thanks pankaj… One more doubt… Above code help me in login on the server but after login I have to add myself as superuser. I have to execute the /usr/seos/bin/sesu command after this command is hit on Unix it will ask for password. what changes are required for this.
- Ashish Dugar
I am sorry but I haven’t explored this scenario, why don’t you try to use Expect script, you can find about that in following article: https://www.journaldev.com/1405/expect-script-example-for-ssh-and-su-login-and-running-commands
- Pankaj
I want to run more than one command… but the next command based on previous command output. I mean I want to mimic the putty session… how to do that
- vandana
Hi Pankaj, saw ur solution it worked for me for a single command but i want to pass “DIR=”/etc/httpd/" if [ -d “$DIR” ]; then # Take action if $DIR exists. # echo “Installing config files in ${DIR}…” fi" this command also i saved it in .sh file on my windows system not the unix can i run this file using setcommand if yes how plz help
- sangeeta
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
It looks like JSCH jar is not in classpath.
- Pankaj
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
Hello I am facing the same problem. After i run the program, kerberose username and password is asked for. I want the program to directly give the result. Can someone pose a solution? Thanks
- Pari
java.util.Properties config = new java.util.Properties(); config.put(“StrictHostKeyChecking”, “no”); config.put(“PreferredAuthentications”, “publickey,keyboard-interactive,password”); use this code to avoid kerberose login problem
- Joginder
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
Does user have access to remove the directory? Try with “rm -rf” command.
- Pankaj
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
I haven’t tried this scenario where multiple logins are required.
- Pankaj
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
suppose you want to execute the cd /abc and then ls -lrt. then you will write cd /abc; ls -lrt.
- Ashish
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
I don’t think it will work, it doesn’t support interactive sessions as far as I know.
- Pankaj
Hi Pankaj, Thanks for replying Is there any other way to do this. Regards Vipin
- Vipin ahuja
Use Channel channel=session.openChannel(“shell”); instead of session.openChannel(“exec”) to emulate a shell. An example “Shell.java” is provided on the JCraft website. https://www.jcraft.com/jsch/examples/Shell.java.html
- Nav
Use ; semicolon
- rahul
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
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
I have done a modification which maybe interesting for people. I use your example for making searches in remote log files. The modifications returns the lines without being cut to a size of byte[1024]. Feel free at https://tomeuwork.wordpress.com/2014/09/24/java-program-to-run-ssh-commands/comment-page-1/#comment-3
- 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
Hi GEETHA KRISHNA, Even though its been a long time (4 years), I am in the same situation and try to solve this second password problem, if you have a solution for it, can you please share? Thanks
- Cagri
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 joginder,even i am working on trying to run shell script on remote host from java app on my local machine.I would like to ask your help for same. Please suggest some links or some reference pages to understand how to execute a shell script that installs weblogic server on a remote host from java app on windows. Please send any help on my email id. Thanks in advance!!
- Ashka Sha
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
Thanks for the code . Really helpful
- ramya
Good example. Thanks.
- sachin
Good Job…Thanx
- bharat
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
I was getting this issue when I was using String host=“ssh.192.168.172.141” Issue got resolved on removing ssh , i.e. String host=“192.168.172.141”
- ankur_chd11@yahoo.com
Hi, I have tried this, but how can call a shell script is particular directory?
- bhargavi
hi bhargavi, i am having the same problem. If you have the solution could you please share the code. i really appreciate your response. u can publish it here or email me @ nurshahjalal@gmail.com Thanks, Nur
- nur
How we can Bypass or enter password after prompting after using below commands suu-t- “comment”
- Brijendra
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, Are you sure the connection details like host, port number, user name and password are working fine? I mean, were you able to directly connect to that Linux server using the details in a putty? I used this code snippet for mine and it worked perfectly alright.
- ThulsZ
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
I didn’t try this but it’s on one of the reply. You can execute multiple commands by appending each command with a semi colon. For e.g, setcommand(command1;command2)
- ThulsZ
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
You mean you want your Java code to open putty and type in the commands automatically? The above program does the same thing and it prints the response of putty for any command you execute. Only difference is it establishes connection without the need of opening putty.
- ThulsZ
This works perfectly, thank you so much for sharing it. Noe
- Noe
I am trying to connect to ubuntu blueprint. Getting below error if i fetch command to execute: java.lang.AssertionError: session is down at org.testng.Assert.fail(Assert.java:94) at com.canopy.compose.ApplicationCommonTest.testApplication(ApplicationCommonTest.java:382) at com.canopy.compose.ApplicationsTest.testAWSApplications(ApplicationsTest.java:185) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:606) at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:84) at org.testng.internal.InvokeMethodRunnable.runOne(InvokeMethodRunnable.java:46) at org.testng.internal.InvokeMethodRunnable.run(InvokeMethodRunnable.java:37) at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471) at java.util.concurrent.FutureTask.run(FutureTask.java:262) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) at java.lang.Thread.run(Thread.java:745)
- Chetan
Thanks Pankaj! Is it possible to execute sudo commands with JSch?
- Sijo
I could login with this code. But after logging in, I need to find the status of the server using “server_status” command, but when I try this command, I’m getting ksh: command not found error. Help needed.
- Anantha Sairam
when i am running program i have getting this error com.jcraft.jsch.JSchException: Session.connect: java.security.InvalidAlgorithmParameterException: Prime size must be multiple of 64, and can only range from 512 to 2048 (inclusive) at com.jcraft.jsch.Session.connect(Session.java:558) at com.jcraft.jsch.Session.connect(Session.java:183) at com.New.CommandExecuter.main(CommandExecuter.java:42) what should i do
- irshad
Just wondering if you have resolved this issue? I’m getting the same error.
- Rathishkumar Nair
Hi, If we want to execute commands one after another then how to code? ((ChannelExec)channel).setCommand(command1); From above command I need to change the directory path(Ex: cd D:) ((ChannelExec)channel).setCommand(command2); In command 2 I need to execute jar file (Ex: java -jar runJarFile.jar) Thanks, Karthik.
- Karthik
i wonder did you find any solution for this.if you please share the idea. Thanks nur
- nur
you can put semicolon in between two commands and run them. For example :- ((ChannelExec)channel).setCommand(“cd /home/JAVA/New_Jar; java -jar DirectoryScanner.jar”);
- Harshita Sethi
Thank you very much. It worked for me. Displaying the result as follows run: Connected total 40 -rwxr----- 1 216 staff 1507 Mar 23 2015 .profile drwxr-xr-x 2 root system 4096 Sep 10 09:16 client_ffdc -rw------- 1 root system 9784 Sep 22 12:45 .sh_history exit-status: 0 DONE BUILD SUCCESSFUL (total time: 1 second)
- Ashenafi Desalegn
isClosed() method is not availble inside channel class pls check and let me know
- nagarjuna
hi! Pankaj: I have a question about JSCH.First,If I want to set cammand about “sftp” upload,what’s the cammad?second,the error “com.jcraft.jsch.JSchException: Session.connect: java.security.InvalidAlgorithmParameterException: Prime size must be multiple of 64, and can only range from 512 to 1024 (inclusive)” , can you give me some advice! Please contact me "courage_dun@yahoo.com " . Best wish!
- liu.dun
I have used the above code for connecting and communicating with ssh server and it worked fine. But I had a situation in which I need to execute two commands on the same shell environment like export DISPLAY=:0 and my command but I was unable to execute both these commands on the same shell environment. Could you please help me in resolving this issue.
- Phani Kumar
Just put a semicolon near your first command and enter second command. Pass them as single string in command1 variable.
- digi
Hi, I am trying to run simple command like rm /mydirectory/test.txt It executes but the file is not removed in server Also, it says, done, but with error The same command, I am able to execute from server
- Ankit
can use this same program to connect to windows 2000 server? I tried it but it gives as below. Connected exit-status: -1 DONE any help Please
- Valli
I’ve the same error… exit-status:1 Did you got solution Valli ???
- Xeye
Hi Pankaj, Could you please tell me how to run the commands one by one using this code. The solutions given earlier didnt work.
- Suresh
hey, could you please suggest me how to run abc.ksh (arg) in remote directory. with set command it is not running. please help
- nur
Awesome friend…It helps me a lot … Thumbs up :) Keep posting (y)
- prateekshrivastava76@gmail.com
I am getting below exception: com.jcraft.jsch.JSchException: Auth fail at com.jcraft.jsch.Session.connect(Session.java:464) at com.jcraft.jsch.Session.connect(Session.java:158)
- sujata
Hi I am executing tail -f anaconda.log command it is printing console output how can i capture that to output file
- SREEPAL GUMMALLA
Hi , My use case is to use PPK file and log in to remote server from my windows machine, in this case what should I do ? Now , I am using putty to login. I have to access the terminal using java program. Your help on this is much appreciated
- Jagadeesh
If I don’t know the password and I only have the .ppk to access the SSH. Should I need to input it in config variable with the absolute path of the fille? Please advise.
- knightofdawn
Hi There On Server there is one file with extension .cmd which is executable and I want to execute that particular file with some parameter input e. g. For ‘File1.cmd File1.env’ input string I am getting ksh: line 1: File1.cmd: not found For ‘./File1.cmd File1.env’ input string I am getting ./File1.cmd[25]: .: /fctgen.cmd: cannot open [No such file or directory] Please help me if anyone has idea about … Thanks in Advance
- Rahul Bhore
great code thanks a lot !!!
- omkar
You have to create a session object and pass a list of commands for it to execute all the commands one by one in the same session. So in your case, your 1st command would be "cd " and then 2nd command would be “./File1.cmd File1.env”. This way, it will first traverse to the said path and then execute the command from that path. Hope this helps. Regards, Sourin
- Sourin
I’m trying to run a perl script., but i’m getting this error - “bash: ./script_transaction.pl: No such file or directory” But I am able to run the same script on the same directory, through putty. Also, through my java program, I am able to perform “cd”, “mkdir” etc. commands…but not able to run the perl script. Any leads on this?
- Shreyas
Hi, I am trying to run a shell script which is in local system (ubuntu) i am trying to pass the path of script file in command1 parameter. i.e : String command1=“sh home/umar/start.sh”; I am getting the error as show below. “Connected sudo: no tty present and no askpass program specified exit-status: 1 DONE”
- Umar Faraz
Hello, I’m trying to execute your code but i get the following error: Establishing Connection… Connection established. Creating Channel. erreur : java.io.PrintStream@3603820e Unknown application ‘ls’ exit-status: 0 DONE Can anyone help me please !!
- Anas
i can able to ping my host but still unable to connect. getting Auth failed. com.jcraft.jsch.JSchException: Auth fail at com.jcraft.jsch.Session.connect(Unknown Source) at com.jcraft.jsch.Session.connect(Unknown Source) at com.bac.SSHCommandExecutor.main(SSHCommandExecutor.java:29)
- shankar
hi Pankaj , I tried your program as well as the program from this link : “https://www.zehon.com/sftp/samples/UsePrivateKeySample.java” i am getting the error “Auth fail”
- Narendra
I am trying to run a FNDLOAD command using the above code. It gives me error as command not found. Can you help me with that?
- Harshita Sethi
Can I stay in the SSH-Connection and only send new commands into it? I dont want to log out. Is it possible?
- Yanni Leckel
I successfully connected to the Linux by using the above code. Thank you so much. Can i use SSH keys instead of username and password. If possible can u please guide how to achieve it. Thanks
- Sreenu
Super article , it’s works for me, Thanks
- Yusuf
Hi Pankaj, I tried this but getting “Algorithm negotiation fail” exception. I am using jsch-0.1.52.jar Could you pls suggest the reason for the same. Thanks
- Pradipta B
Hi Pankaj i need your help how can i add a new command with tread.sleep. I tried to add ((ChannelExec)channel).setCommand(command2); but executed always only command1 and command2 was ignore Thanks a lot for your answer Have i nice day
- Mike
Hii Pankaj, Thanks in advance for the above code. It works fine for me. But when I m trying to execute a .sh file e.g. ./startup.sh. It is showing results in console that ‘server started successfully’. But manually when I m trying to find the PID it is not there.If anybody has the solution plz share.
- Rasmiranjan
Please help- I am lunching my shell script which writes the logs in RHEL server. When I tail logs I get following error message - Generic Status: Library Open failed, Library Name: libclntsh.so, Platform Status: libclntsh.so: cannot open shared object file: No such file or directory Here is the code - public class LinuxServerInteraction { public static void main(String[] args){ Session session = null; InputStream in= null; try{ JSch jsch = new JSch(); java.util.Properties config = new java.util.Properties(); session = jsch.getSession(“passwd”, “server-name”,22); config.put(“StrictHostKeyChecking”, “no”); config.put(“PreferredAuthentications”,“publickey,keyboard-interactive,password”); session.setPassword(“passwd”); session.setConfig(config); System.out.println(“Connecting”); session.connect(); System.out.println(“Connected”); String command1=“/u/myScript”; channel=session.openChannel(“exec”); channel.setInputStream(null); ((ChannelExec)channel).setErrStream(System.err); 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){} } }catch(Exception ex){ ex.printStackTrace(); }finally{ try{ in.close(); channel.disconnect(); session.disconnect(); }catch(Exception ex){ ex.printStackTrace(); } } } }
- Atul
Has anyone found a solution to this exception? com.jcraft.jsch.JSchException: Session.connect: java.security.InvalidAlgorithmParameterException: Prime size must be multiple of 64, and can only range from 512 to 2048 (inclusive)
- Brian
Hi Pavan, I am going to automate some connections as a part of my work in my project. So,I want to check my connections of unix server through Java code. And atleast i want to run these many commands for checking the connections 1)Login 2)Password 1)ssh fbepr90040-man 2)sudo su - sli 3)cd data/incoming Can you please insight me how to do this? Thanks & Regards, Ravi
- Ravi Shankar
Thank you so much, It works for me to run multiple commands by separating them with semi colon (;).
- Suresh Jannu
Hi Team, I used the above code and it is working fine for me. I am calling a script. /abc/xyz/pqr.ksh pqr.ksh script contains below simple code #!/bin/ksh touch callingfromjavatest.dat echo " file touched " chmod 777 callingfromjavatest.dat echo " permission changed " exit 0 The echo statements are being read well by JSch. But the Touch and chmod commands are not running. The file is not being created. Can you tell me what could possibly be going wrong here.
- K. Vikram
Hi Pankaj, Is there a way that we run sudo commands using the above code? Thanks in advance
- Willy
Hi All, I want to connect one server from another server in putty using Java Program. Like suppose i connected one server using putty and then i am trying to login into another server using ssh command but for connecting to another server then it required password also. So please tell me is there any possible in Java code to connect one server to another server with password in putty. Thanks & Regards Sailendra Narayan Jena
- Sailendra Jena
Hi, is there any other way to make connection without using external library?
- CN
I am looking for something like I want to read file size of a file in sftp server? Is JSch has option I read its documentation there is a way? https://epaul.github.io/jsch-documentation/javadoc/com/jcraft/jsch/ChannelSftp.LsEntry.html#getAttrs-- Please can you share if you have any example for this??
- Ravi Beli
Hi, I am looking to acess a file stored in client server from my local system through java code and get its content displayed on the web page. Kindly help me perform this task, Plz Post this code. Thanks in advance
- Neeraj
How to set password after executing sudo command?
- subbu
I pasted the example exactly into eclipse, and it gives this compile error: The public type JSchExampleSSHConnection must be defined in its own file
- charles radley
Above example works fine to me but i need to multiple commands after login, so how can i do that using above example ? what changes i need to do to above code.
- Anil
I have tried this code. i want to run sh command over the server on a particular folder . i tried so many times and search on the google still not getting any solution for that .can you provide the solution with coding.
- ehant
Hey i executed your code thanks a lot :) it was great help. I want to extract permissions from listing command, how can i do that
- Pritam
I need to execute the command “pm 34601221946|grep send” it is showing command not found error. Please help me if you can.
- Shalini
Hi, when i a executing the following echo command in putty session directly ia m getting this output: command: echo -e “Checking current state.\t[ ]\b\b\b\b\b-\r\u001B[KChecking current state.\t[ ]\b\b\b\b\bFAIL\n\r\u001B[K\n”; output: Checking current state. [FAIL] newline newline but same echo command when i run though jshell , its giving wrong output. command: echo -e “Checking current state.\t[ ]\b\b\b\b\b-\r\u001B[KChecking current state.\t[ ]\b\b\b\b\bFAIL\n\r\u001B[K\n”; output: Checking current state. [ ]- [KChecking current state. [ ]FAIL [K please help me in debugging this
- prabhu
I tried lots of code to do the same but yours ran smoothly without any error and was easy to understand also Thanks a lots for sharing the code.
- rahul saini