Java JSch Example to run shell commands on SSH Unix

Filed Under: Java
Jsch Java Api

Today we will look into the JSch example tutorial. We can use JSch for creating 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.


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 pretty straight forward example of JSch to create SSH connection in java program.

You can download JSch jar file from its official website.

Comments

  1. Arts says:

    How do i get host server message reply to string using java

  2. BNR says:

    4 *-* Call JOBCTL, mLogFile, “I01D0201”, “HEADER”
    REX0043E: Error 43 running /projects/ingenium70/pr/server/batch/job/I01D0201 line 4: Routine not found
    REX0417E: Error 43.1: Could not find routine “JOBCTL”
    exit-status: 213
    DONE

    please help. am getting above error

  3. Tausif says:

    I want to execute a command which requires a password.
    The above code holds good to have a connection and execute some basic commands which is working fine for me.

    1. Mohammad Khalid says:

      Hi,

      Did you find the answer. I have the same requirement to send environment parameters and password in a series of commands.

      Can you guide me..?

  4. saket kumar says:

    Hi, How to run multiple commands connecting putty?

    1. sujay says:

      Did you get answer for this?

  5. PRavin says:

    Hi, I am getting below Message. Please advise.
    Connected
    This account is currently not available.
    exit-status: 1
    DONE

  6. Manish says:

    Using Java code I have to copy into Linux box , please suggest.

  7. Dorris says:

    Hi, I used this code, however a came to error result
    com.jcraft.jsch.JSchException: Algorithm negotiation fail
    at com.jcraft.jsch.Session.receive_kexinit(Session.java:520)
    at com.jcraft.jsch.Session.connect(Session.java:286)
    at com.jcraft.jsch.Session.connect(Session.java:150)
    at controllers.Application.Slicing(Application.java:1088)

    1. Arasan says:

      Use lates jsch jar to solve this problem.

  8. sudarshan says:

    I have one query, how many time as default it try to connect if password is wrong. I see with this code 2. But default value of MaxAuthTries is 6. so can you explain why only it shows 2 failure at target host.

  9. Doris says:

    Hello,
    I have a question needing your advice.

    What it depends on to define the executed completely command? I would like to set a prompt for the command, then the command output should be captured to that prompt.
    For an example, I have a command: “su -root”. and the prompt that I want to set is: “:”.
    Expected output: Password:

    Could anyone help me?
    Thanks,

    Doris

  10. Shikha says:

    I used your code but getting auth failed error. Public key is already added in .SSH file. Please let me know the solution for this issue. Manually when i try to ssh without password I can login successfully

  11. Gopi says:

    why your code was not able to execute dzdo su -someusr command it was going to infinite loop in the statement while(true)

  12. rahul saini says:

    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.

  13. prabhu says:

    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

  14. Shalini says:

    I need to execute the command “pm 34601221946|grep send” it is showing command not found error. Please help me if you can.

  15. Pritam says:

    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

  16. ehant says:

    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.

  17. Anil says:

    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.

    1. Faiz says:

      Use “;” to separate two commands in the same string.

      example as below

      String command1=”cd $directory_where_script_is_placed; ./abc.sh”;

  18. charles radley says:

    I pasted the example exactly into eclipse, and it gives this compile error:

    The public type JSchExampleSSHConnection must be defined in its own file

    1. charles radley says:

      never mind, I figured it out, changed the file name

  19. subbu says:

    How to set password after executing sudo command?

  20. Neeraj says:

    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

  21. Ravi Beli says:

    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?
    http://epaul.github.io/jsch-documentation/javadoc/com/jcraft/jsch/ChannelSftp.LsEntry.html#getAttrs–

    Please can you share if you have any example for this??

    1. March says:

      ChannelSftp sftpChannel = (ChannelSftp) channel;
      sftpChannel.cd(“/var/log/hbase/”);

      Vector list = sftpChannel.ls(“*.out”);

      1. March says:

        Channel channel=session.openChannel(“sftp”);

  22. CN says:

    Hi, is there any other way to make connection without using external library?

  23. Sailendra Jena says:

    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

  24. Willy says:

    Hi Pankaj,
    Is there a way that we run sudo commands using the above code?

    Thanks in advance

    1. Willy says:

      I tried o run a sudo command and as the terminal is not open, am not able to provide the password which leads to the error “sudo: no tty present and no askpass program specified” and I am not sure how to proceed.

      1. Alex says:

        @Willy Define an outputstream and do out.print(“password\n”.getBytes());
        Should do it

        1. R.K says:

          @Alex Hi defining an output stream did not work , is there any other way I can sudo to m/c provide password and execute other commands . It would be very helpful if you provide a piece off code.

          @Willy did it work for you , if yes can you please provide me that code.

  25. K. Vikram says:

    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.

    1. Pankaj says:

      use full name in touch command and see if it works?

  26. Suresh Jannu says:

    Thank you so much, It works for me to run multiple commands by separating them with semi colon (;).

    1. Srinivas says:

      Hi Suresh,

      Can you please show me where to separate them with colon. I’ve below commands to execute one by one

      cd /opt/IBM/db2/V10.5/bin

      ./db2

      connect to occvt1d user occvtds1 using password__12345

      Thanks in advance,
      Srinivas

      1. Arvind says:

        Hey,
        U just can execute multiple commands using the following method:-
        String command1= “echo ‘hello’ ; echo ‘hi'”;
        String cmd2 = “echo ‘Hey'”;
        String cmd3 = “ls “;

        Channel channel=session.openChannel(“exec”);
        ((ChannelExec)channel).setCommand(command1 + “&&” +cmd2 + “&&” +cmd3);

    2. Arvind says:

      can you please post a snippet of the multiple line code.

  27. Ravi Shankar says:

    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

    1. manish says:

      Hi Pankaj,
      We are automating some connections as a part of my work in my project.

      So,I want to check my connections of unix server through Java code.
      For this i need to execute commands for checking the connections

      1)Login
      2)Password
      1)ssh fbepr90040-man
      2)sudo su – sli
      3)cd data/incoming

      Can you please help how to achieve this.

  28. Brian says:

    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)

  29. Atul says:

    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();
    }
    }
    }

    }

  30. Rasmiranjan says:

    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.

    1. Darshan K s says:

      you can’t get the pid of process running in other sessions just by using ps. You need to use the command ps -aux to see all the process running under user X.

  31. Mike says:

    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

  32. Pradipta B says:

    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

    1. Som says:

      I am also facing the same issue please provide solution for this.
      com.jcraft.jsch.JSchException: Algorithm negotiation fail
      at com.jcraft.jsch.Session.receive_kexinit(Session.java:540)
      at com.jcraft.jsch.Session.connect(Session.java:288)
      at com.jcraft.jsch.Session.connect(Session.java:145)
      at CustomerDelete.JSchExampleSSHConnection.main(JSchExampleSSHConnection.java:24)

  33. Yusuf says:

    Super article , it’s works for me, Thanks

  34. Sreenu says:

    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

    1. Chandu says:

      Did you able to do it without password when my jsch is running on windiow and want to connect to Linux using SSH keys?

    2. CodeMonkey1101 says:

      If you use the .addIdentity() when declaring the connection itself then you can use a key file.

  35. Yanni Leckel says:

    Can I stay in the SSH-Connection and only send new commands into it?

    I dont want to log out.

    Is it possible?

    1. Pankaj says:

      Not sure, I haven’t tried it.

    2. Darshan K s says:

      Yes you can do it. Create a session and keep it as session variable, using that session variable open executable channel and set the desired command to be executed. Here is a sample code

      Channel channel = session.openChannel(“exec”);
      ((ChannelExec)channel).setCommand(desired_command);

      Only thing to be taken care here is, the session expires after 15 minutes. So you need to send keep alive message to the server. It can be done using the command

      session.sendKeepAliveMsg();

  36. Harshita Sethi says:

    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?

  37. Narendra says:

    hi Pankaj ,
    I tried your program as well as the program from this link : “http://www.zehon.com/sftp/samples/UsePrivateKeySample.java”
    i am getting the error “Auth fail”

  38. shankar says:

    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)

  39. Anas says:

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

  40. Umar Faraz says:

    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”

  41. Shreyas says:

    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?

  42. Rahul Bhore says:

    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

    1. omkar says:

      great code thanks a lot !!!

    2. Sourin says:

      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

  43. knightofdawn says:

    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.

  44. Jagadeesh says:

    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

    1. Jagadeesh says:

      making it clear. I will not have to type password rather I will have to use PPK file for login

      1. zarra says:

        so ,how you use it?
        is it enough to read the file as password ?

  45. SREEPAL GUMMALLA says:

    Hi

    I am executing tail -f anaconda.log command it is printing console output how can i capture that to output file

  46. sujata says:

    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)

    1. Rakesh says:

      I am also getting the same error. should we generate a private key to resolve this. please advise.

      1. Shreyas says:

        This might work. Well it did, for me 🙂

        java.util.Properties config = new java.util.Properties();
        config.put(“StrictHostKeyChecking”, “no”);
        Session session = jsch.getSession(“”, “”, );
        session.setPassword(“”);
        session.setConfig(config);

  47. prateekshrivastava76@gmail.com says:

    Awesome friend….It helps me a lot ….
    Thumbs up 🙂
    Keep posting (y)

  48. nur says:

    hey,
    could you please suggest me how to run abc.ksh (arg) in remote directory. with set command it is not running.

    please help

  49. Suresh says:

    Hi Pankaj,

    Could you please tell me how to run the commands one by one using this code. The solutions given earlier didnt work.

  50. Valli says:

    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

    1. Xeye says:

      I’ve the same error..

      exit-status:1

      Did you got solution Valli ???

  51. Ankit says:

    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

  52. Phani Kumar says:

    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.

    1. digi says:

      Just put a semicolon near your first command and enter second command. Pass them as single string in command1 variable.

  53. liu.dun says:

    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!

  54. nagarjuna says:

    isClosed() method is not availble inside channel class

    pls check and let me know

  55. Ashenafi Desalegn says:

    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)

  56. Karthik says:

    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.

    1. nur says:

      i wonder did you find any solution for this.if you please share the idea.

      Thanks
      nur

    2. Harshita Sethi says:

      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”);

  57. irshad says:

    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

    1. Rathishkumar Nair says:

      Just wondering if you have resolved this issue? I’m getting the same error.

  58. Anantha Sairam says:

    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.

  59. Sijo says:

    Thanks Pankaj! Is it possible to execute sudo commands with JSch?

  60. Chetan says:

    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)

  61. Noe says:

    This works perfectly, thank you so much for sharing it.

    Noe

  62. Teju says:

    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.

    1. ThulsZ says:

      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.

  63. Nayana Ratnani says:

    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.

  64. varsha says:

    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

    1. ThulsZ says:

      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)

      1. meghana says:

        It si not working.It says The method setCommand(String) in the type ChannelExec is not applicable for the arguments (String, String) .Please suggest what to do for multiple commands.

  65. Jayant says:

    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

    1. ThulsZ says:

      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.

  66. kumara says:

    how to run this code in unix, i will get lot of error, it’s not working

  67. bhargavi says:

    Hi,
    I have tried this, but how can call a shell script is particular directory?

    1. nur says:

      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

  68. kumara says:

    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.

    1. ankur_chd11@yahoo.com says:

      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″

  69. nix says:

    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

  70. shyam says:

    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.

  71. th says:

    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

  72. A.Mohamed Bilal says:

    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?

  73. bharat says:

    Good Job…….Thanx

  74. sachin says:

    Good example. Thanks.

  75. ramya says:

    Thanks for the code .
    Really helpful

  76. vivek says:

    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.

  77. Joginder says:

    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.

    1. Ashka Sha says:

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

  78. GEETHA KRISHNA says:

    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.

    1. Cagri says:

      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

  79. Tomeu Mir says:

    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

    1. Tomeu Mir says:

      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 http://tomeuwork.wordpress.com/2014/09/24/java-program-to-run-ssh-commands/comment-page-1/#comment-3

  80. anjali says:

    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

  81. roshan says:

    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

  82. John W Schlinz says:

    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)

  83. Vaishnavi says:

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

  84. Satish Vemuri says:

    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

  85. Kishore Garapati says:

    Super bro… It’s working great.. Thank you.. 🙂

  86. mkz says:

    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

  87. Vipin ahuja says:

    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

    1. Pankaj says:

      I don’t think it will work, it doesn’t support interactive sessions as far as I know.

      1. Vipin ahuja says:

        Hi Pankaj,

        Thanks for replying Is there any other way to do this.

        Regards
        Vipin

    2. Nav says:

      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.

      http://www.jcraft.com/jsch/examples/Shell.java.html

      1. rahul says:

        Use ; semicolon

  88. Nazeer says:

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

    1. Ashish says:

      suppose you want to execute the cd /abc and then ls -lrt. then you will write cd /abc; ls -lrt.

  89. Thanks for the post says:

    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.

  90. noo says:

    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

  91. Dileep says:

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

  92. Ashok Kumar says:

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

  93. Souvik says:

    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”

    1. Pankaj says:

      I haven’t tried this scenario where multiple logins are required.

  94. shalini says:

    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.

  95. Amol says:

    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.

  96. Manoj says:

    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.

    1. Pankaj says:

      Does user have access to remove the directory? Try with “rm -rf” command.

  97. Nagaraj says:

    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..?

    1. Pari says:

      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

    2. Joginder says:

      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

  98. Rahul says:

    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

  99. vikranth says:

    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

  100. Huynh Duy says:

    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.

    1. Pankaj says:

      It looks like JSCH jar is not in classpath.

  101. Ashish Dugar says:

    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.

    1. Pankaj says:

      You can create command string like this “cd SCS;ls -ltr” and execute it. I have checked it and it works fine.

      1. Ashish Dugar says:

        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.

        1. Pankaj says:

          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

      2. vandana says:

        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

  102. Ankit says:

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

    1. Pankaj says:

      Its not working because SSH is not supported in Windows. Putty software provides utility software for SSH.

      1. Subhasish Choudhury says:

        Is this code will not work in windows system.

  103. Kalyan says:

    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

    1. Pankaj says:

      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.

  104. Alexander says:

    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.

  105. Alexander says:

    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.

  106. Abhinav says:

    Can anyone reply for my question?

  107. Abhinav says:

    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

    1. Pankaj says:

      Sorry for late reply but I haven’t explored it that much. Let others know through comments if you have found anything.

  108. Edgar says:

    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

  109. Rajan Kurunju says:

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

    1. Pankaj says:

      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

    2. Karthikeyan says:

      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?

  110. Natraj A says:

    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.

    1. Pankaj says:

      Use the latest JSCH jar, current version is 0.1.50 and above code is tested with it and working fine.

  111. Jayashree says:

    Awesome

  112. MaT says:

    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

    1. MaT says:

      Forgot the link I downloaded the files…
      Here it is!

      http://www.jcraft.com/jsch/

    2. Pankaj says:

      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.

    3. Don Freeman says:

      Hi MaT,

      I am having the same problem. Did you ever get it resolved? If so, can you share the resolution?

      Thanks,
      Don

      1. Pankaj says:

        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.

        1. Rajendra says:

          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%;

  113. Sindhu says:

    hi,

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

    Thanks,
    Sindhu

    1. Pankaj says:

      Its the name of the ssh system, try to ping your ssh server and see its working?

  114. Kadir Sert says:

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

    1. Pankaj says:

      Can you connect to same server using SSH login and run this command? Is it working there?

  115. Saurabh says:

    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.

    1. Pankaj says:

      Do you have user/password authentication of Key based authentication?

      1. Aditya says:

        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?

    2. Deividas says:

      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

      http://wiki.jsch.org/index.php?Manual%2FExamples%2FJschPubkeyAuthExample

  116. Haritosh says:

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

  117. Rufatet says:

    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

    1. Pankaj says:

      I have not tried it but please try it and let us know the results.

  118. Thomas says:

    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.

    1. Pankaj says:

      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?

  119. Paulo says:

    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

    1. Cheyenne says:

      p0ET9r Kudos! What a neat way of thinking about it.

  120. kpolo says:

    Apache mina provides ssh server and client libraries in java.

  121. Sandeep says:

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

    1. Pankaj says:

      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.

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages