Monday, November 4, 2019

Java execute shell commands on SSH Unix using JSch



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.

Reference :
Previous Post
Next Post

0 komentar: