Java JSch Example to run Shell Commands on SSH Unix Server

Filed Under: Java
Jsch Java Api

Today we will look into the JSch example tutorial. We can use JSch for creating an SSH connection in java. Earlier I wrote a program to connect to remote database on SSH server. Today, I am presenting a program that can be used to connect to the SSH-enabled server and execute shell commands. I am using JSch to connect to remote ssh server from java program.

JSch Example

You can download JSch jar from its official website. You can also get the JSch jars using below maven dependency.


Below is a simple JSch example program to run the “ls -ltr” command on the server.


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="";
	    String user="sshuser";
	    String password="sshpwd";
	    String command1="ls -ltr";
	    	java.util.Properties config = new java.util.Properties(); 
	    	config.put("StrictHostKeyChecking", "no");
	    	JSch jsch = new JSch();
	    	Session session=jsch.getSession(user, host, 22);
	    	Channel channel=session.openChannel("exec");
	        InputStream in=channel.getInputStream();
	        byte[] tmp=new byte[1024];
	            int, 0, 1024);
	            System.out.print(new String(tmp, 0, i));
	            System.out.println("exit-status: "+channel.getExitStatus());
	          try{Thread.sleep(1000);}catch(Exception ee){}
	    }catch(Exception e){



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.


  1. Sitakanta says:

    Transfer file using scp command

    JSch jsch = new JSch();
    Session session = jsch.getSession(“root”,”″,”22″);

    ChannelExec channel= session.openChannnel(“exec”);
    channel.setCommand(“scp file:// android_asset/situ.txt” root@ /mnt/internal_storage);

    After executing this command using SCP. we need to pass yes or no, then need to provide a password.
    After providing the password then file transfer is possible.
    How we can do this.Please help me to resolve this issue.

  2. Hemant says:

    nice ! it works .. just changed password to private key .. Thank you

    1. Fares says:

      Hi Hemant, how it works with Private Key could you Please share an Example of it, I’m struggling with the same issue and can’t get the connection up 🙁

  3. Sailu says:

    Hi Pankaj,

    I need to enter password after executing pbrun command. In terminal I will get password question and need to enter the password after the question prompts.

    How can I automate the scenario.

    Please help me.


  4. Anmol Chadha says:

    Hi Pankaj,

    Great article. But I was looking for a way to implement this dynamically. Like a scenario where input commands are spread across time.
    For example, the user enters one command, then observes its output, then enters another, and then more. And all commands are sent over single channel

    How can that be achieved ?

  5. Aakash says:

    I am executing a command using JSch which starts a process on port 80
    That process does not start. When I do ssh using putty and execute the same command, then also it does not work (after doing Jsch)
    Although, If I use the same command before doing Jsch, then that command works pretty fine.

    I am running this on Lighsail ubuntu instance.

  6. Oleksandr Mudryi says:

    For example I try to change txt file. Manually in ubuntu command line the command works. Your code is running without errors but the txt file is not changed

  7. Oleksandr Mudryi says:

    Hi. Could you help me? When I try to setCommand(“sudo apt install …”) – command with some action -> this script doesn’t work. When I set this command manually in linux console it works. I my testing, your code works only when we need to print information from console. How can I do some action by your code? Maybe need to use another protocol

  8. Shashank Jha says:

    Hi Pankaj,

    Thanks for the solution but it seems I am facing issue while executing the command, I am able to connect my server but command execution is not happening. I am getting this error 👇

    “ls” isn’t allowed to be executed.
    exit-status: 1

    Could you please help me with this, it will be great help. Thank you in advance.

  9. Palak says:

    SHELL PARSER FAILURE: ‘echo’ – no matching entry found: I am getting this error for every command I am trying to execute. Please help

  10. Preethi says:

    How to open the command prompt using session.openChannel and run the bat file?

  11. Brijendra Singh says:

    i have to run below command suu -t- r “comments” .After running this command i should have to set the passord or bypasss it .Once done user should get change and display impersonated user after running command whoami.

    Right now using your code its not impersonating user. Please help.

    1. Srini says:

      Can you please explain about suu command. Also please help me to find some documents about suu command along with examples.

  12. Neeraja says:

    I just want to know that how to send a modify command to putty from java

    Below is the command to modify a username in putty
    useradd -c oldusername newusername

    So, How to send above command from java

  13. Rashmita Deka says:

    How to change directory in jsch command?unable to change directory using exec channel.Could you please provide me the solution?

  14. Rahul Kumar says:

    Hi Pankaj,
    Recently our sFTP server migrated and upgraded to NEW. Now we are start getting connection issue and not able connect to NEW FTP server..I’ve tried upgrading the Jsch*.jar to recent version(previously jsch-0.1.50.jar).

    Getting Error …GetFileXXFromSFTP – Session.connect: End of IO Stream Read ()


    session = jsch.getSession(userID,host,port);
    Properties config = new Properties();
    config.put(“StrictHostKeyChecking”, “no”);
    session.connect(); \\ Failed here
    channel = session.openChannel(“sftp”);
    channelSftp = (ChannelSftp)channel;
    if(remoteDirectory!=null && remoteDirectory.length()>0){;

  15. Venky says:

    Caused by: com.jcraft.jsch.JSchException: Auth fail excpetion thrown . But i am able to login through ssh

  16. Mike says:

    In this code, Why do we need to set the input stream to null, and then why do we get the input stream before we connect, rather than after. I found that doing so after causes a loss of the first read, for some reason, but I don’t understand why.



  17. Arts says:

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

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

    please help. am getting above error

  19. 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:


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

  20. saket kumar says:

    Hi, How to run multiple commands connecting putty?

    1. sujay says:

      Did you get answer for this?

  21. PRavin says:

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

  22. Manish says:

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

  23. 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(
    at com.jcraft.jsch.Session.connect(
    at com.jcraft.jsch.Session.connect(
    at controllers.Application.Slicing(

    1. Arasan says:

      Use lates jsch jar to solve this problem.

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

  25. Doris says:

    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?


    1. roopkumar says:

      Exactly I am working same scenario.
      ->su-” “(root username)
      -Executing commands
      If any body knows, please post here

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

  27. 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)

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

  29. prabhu says:


    when i a executing the following echo command in putty session directly ia m getting this output:
    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”;

    Checking current state. [FAIL]

    but same echo command when i run though jshell , its giving wrong output.
    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”;

    Checking current state. [ ]-
    [KChecking current state. [ ]FAIL

    please help me in debugging this

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

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

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

  33. 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; ./”;

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

  35. subbu says:

    How to set password after executing sudo command?

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

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

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

    1. March says:

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

      Vector list =“*.out”);

      1. March says:

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

  38. CN says:

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

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

    1. Prafulla says:

      I have also same problem. I need the run the script from remote server. But remote server will connection from putty unix terminal. How will code java selenium automation code for running the script from remote server through host unix server.

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

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


    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?

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


      connect to occvt1d user occvtds1 using password__12345

      Thanks in advance,

      1. Arvind says:

        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.

  43. 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)ssh fbepr90040-man
    2)sudo su – sli
    3)cd data/incoming

    Can you please insight me how to do this?

    Thanks & Regards,

    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)ssh fbepr90040-man
      2)sudo su – sli
      3)cd data/incoming

      Can you please help how to achieve this.

  44. Brian says:

    Has anyone found a solution to this exception?
    com.jcraft.jsch.JSchException: Session.connect: Prime size must be multiple of 64, and can only range from 512 to 2048 (inclusive)

  45. 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:, Platform Status: 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;


    JSch jsch = new JSch();
    java.util.Properties config = new java.util.Properties();
    session = jsch.getSession(“passwd”, “server-name”,22);
    config.put(“StrictHostKeyChecking”, “no”);




    String command1=”/u/myScript”;



    byte[] tmp=new byte[1024];
    int, 0, 1024);
    System.out.print(new String(tmp, 0, i));
    System.out.println("exit-status: "+channel.getExitStatus());
    //try{Thread.sleep(1000);}catch(Exception ee){}
    }catch(Exception ex){
    }catch(Exception ex){


    1. Prafulla says:

      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.

  46. 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. ./ 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.

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

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


    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(
      at com.jcraft.jsch.Session.connect(
      at com.jcraft.jsch.Session.connect(
      at CustomerDelete.JSchExampleSSHConnection.main(

  49. Yusuf says:

    Super article , it’s works for me, Thanks

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

    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.

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

      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


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

  53. Narendra says:

    hi Pankaj ,
    I tried your program as well as the program from this link : “”
    i am getting the error “Auth fail”

  54. 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(

  55. Anas says:

    I’m trying to execute your code but i get the following error:

    Establishing Connection…
    Connection established.
    Creating Channel.
    erreur :
    Unknown application ‘ls’
    exit-status: 0

    Can anyone help me please !!

  56. Umar Faraz says:


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

    I am getting the error as show below.

    sudo: no tty present and no askpass program specified
    exit-status: 1

  57. Shreyas says:

    I’m trying to run a perl script., but i’m getting this error – “bash: ./ 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?

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


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

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



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

  62. sujata says:

    I am getting below exception:

    com.jcraft.jsch.JSchException: Auth fail
    at com.jcraft.jsch.Session.connect(
    at com.jcraft.jsch.Session.connect(

    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(“”, “”, );

  63. says:

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

  64. nur says:

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

    please help

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

  66. Valli says:

    can use this same program to connect to windows 2000 server?

    I tried it but it gives as below.
    exit-status: -1

    any help Please

    1. Xeye says:

      I’ve the same error..


      Did you got solution Valli ???

  67. Ankit says:

    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

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

  69. 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: 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 “ ” . Best wish!

  70. nagarjuna says:

    isClosed() method is not availble inside channel class

    pls check and let me know

  71. Ashenafi Desalegn says:

    Thank you very much. It worked for me. Displaying the result as follows

    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
    BUILD SUCCESSFUL (total time: 1 second)

  72. Karthik says:


    If we want to execute commands one after another then how to code?

    From above command I need to change the directory path(Ex: cd D:)
    In command 2 I need to execute jar file (Ex: java -jar runJarFile.jar)


    1. nur says:

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


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

  73. irshad says:

    when i am running program i have getting this error
    com.jcraft.jsch.JSchException: Session.connect: Prime size must be multiple of 64, and can only range from 512 to 2048 (inclusive)
    at com.jcraft.jsch.Session.connect(
    at com.jcraft.jsch.Session.connect(
    at com.New.CommandExecuter.main(
    what should i do

    1. Rathishkumar Nair says:

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

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

  75. Sijo says:

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

  76. 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 com.canopy.compose.ApplicationCommonTest.testApplication(
    at com.canopy.compose.ApplicationsTest.testAWSApplications(
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(
    at java.lang.reflect.Method.invoke(
    at org.testng.internal.MethodInvocationHelper.invokeMethod(
    at org.testng.internal.InvokeMethodRunnable.runOne(
    at java.util.concurrent.Executors$
    at java.util.concurrent.ThreadPoolExecutor.runWorker(
    at java.util.concurrent.ThreadPoolExecutor$

  77. Noe says:

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


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

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

  80. varsha says:

    Hi pankaj
    i want to execute one command which is in another folder..i changed directory by using cd directory i want to execute one command 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.

  81. Jayant says:

    I am getting following error. Not sure why. Please suggest any solution:
    com.jcraft.jsch.JSchException: Connection refused: connect
    at com.jcraft.jsch.Util.createSocket(
    at com.jcraft.jsch.Session.connect(
    at com.jcraft.jsch.Session.connect(
    at oehp.ssh.SSHCommandExecutor.main(
    Caused by: Connection refused: connect
    at Method)
    at com.jcraft.jsch.Util.createSocket(
    … 3 more

    1. ThulsZ says:


      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.

  82. kumara says:

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

  83. bhargavi says:

    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 @


    2. Brijendra says:

      How we can Bypass or enter password after prompting after using below commands

      suu-t- “comment”

  84. kumara says:

    hi pankaj,

    I got a Error from this code
    the error is
    what will be the error and how to resolve it.

    1. says:

      I was getting this issue when I was using
      String host=”ssh.″

      Issue got resolved on removing ssh , i.e.
      String host=”″

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


  86. shyam says:

    hi Pankaj,
    while running your code i am getting the error:”com.jcraft.jsch.JSchException: Connection refused: connect”.

    can you please suggest me to solve this ASAP.

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

  88. A.Mohamed Bilal says:

    I got error like this while executing your program..

    com.jcraft.jsch.JSchException: Connection refused
    at com.jcraft.jsch.Util.createSocket(
    at com.jcraft.jsch.Session.connect(
    at com.jcraft.jsch.Session.connect(
    at test.NewClass.main(
    Caused by: Connection refused
    at Method)
    at com.jcraft.jsch.Util.createSocket(
    … 3 more
    BUILD SUCCESSFUL (total time: 1 second)

    Whats the problem in it?

  89. bharat says:

    Good Job…….Thanx

  90. sachin says:

    Good example. Thanks.

  91. ramya says:

    Thanks for the code .
    Really helpful

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

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

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


    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

  95. 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,

    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

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

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

  98. John W Schlinz says:

    I tried this and get the following error. Doe’s this mean it can’t connect?

    at conntecttoDB8.SSHCommandExecutor.main(

  99. Vaishnavi says:

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

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

    Satish Vemuri

  101. Kishore Garapati says:

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

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

  103. 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
    I want to enter username . How can i do this. Please help

    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.


    2. Nav says:

      Use Channel channel=session.openChannel(“shell”);
      instead of session.openChannel(“exec”) to emulate a shell. An example “” is provided on the JCraft website.

      1. rahul says:

        Use ; semicolon

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

  105. Thanks for the post says:

    When i tried to execute 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.

  106. noo says:


    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

  107. Dileep says:

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

  108. Ashok Kumar says:

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

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

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

  111. 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(
    at com.jcraft.jsch.Session.connect(

    Please help.

  112. 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”);
    ((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.

  113. 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:

      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?


    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

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

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


  116. 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(
    Caused by: java.lang.ClassNotFoundException: com.jcraft.jsch.JSch
    at Method)
    at java.lang.ClassLoader.loadClass(
    at sun.misc.Launcher$AppClassLoader.loadClass(
    at java.lang.ClassLoader.loadClass(
    at java.lang.ClassLoader.loadClassInternal(

    Can you please help in finding resolution for this.

    1. Pankaj says:

      It looks like JSCH jar is not in classpath.

  117. Ashish Dugar says:

    I want to execute multiple unix command through java code.

    let say first command 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:

      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

      3. sangeeta says:

        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

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

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

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

  121. Alexander says:

    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.

  122. Abhinav says:

    Can anyone reply for my question?

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

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



  125. 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();

      String command=JOptionPane.showInputDialog(“Enter command”,
      “set|grep SSH”);

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

      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?

  126. Natraj A says:

    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:
    at com.jcraft.jsch.UserAuthNone.start(Unknown Source)
    at com.jcraft.jsch.Session.connect(Unknown Source)
    at com.ssh2.SSHCommandExecutor.main(

    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.

  127. Jayashree says:


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


    1. MaT says:

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

    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?


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

  129. Sindhu says:


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


    1. Pankaj says:

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

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

  131. 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(
    at com.jcraft.jsch.Session.connect(
    at TestUnix.main(

    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

  132. Haritosh says:

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

  133. Rufatet says:

    All good. thanks for code. But I want to ask , in client can I open image from server use this API?

    Best regards,

    1. Pankaj says:

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

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

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

  136. kpolo says:

    Apache mina provides ssh server and client libraries in java.

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

Comments are closed.

Generic selectors
Exact matches only
Search in title
Search in content
Post Type Selectors