Thursday, October 26, 2017

Execute Shell script in Java Program


import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;

import org.apache.log4j.Logger;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.UIKeyboardInteractive;
import com.jcraft.jsch.UserInfo;

public class ExecuteScriptInServer {
 private static final Logger logger = Logger.getLogger(ExecuteScriptInServer.class);

 public static void main(String[] args) {
  JSch jsch = new JSch();
  Session session = null;
  try {
   InetAddress addr = InetAddress.getLocalHost();
   logger.info("Local HostAddress: " + addr.getHostAddress());
   String hostname = addr.getHostName();
   logger.info("Local host name: " + hostname);
   session = jsch.getSession("root", "10.1.11.4", 22);//UserName, Pasword, Port
   jsch.setKnownHosts(new FileInputStream(new File("known_hosts.txt")));// This file can be generated using ssh-keygen -t rsa Command in the Unix Machine.
   UserInfo ui = new MyUserInfo();
   session.setUserInfo(ui);
   logger.info("Connecting...");
   session.setPassword("password".getBytes());
   session.connect();
   System.out.println("Connected");
   executeCommand(session, "pwd");
   session.disconnect();

   logger.info("Connected");
  } catch (JSchException e) {
   logger.info(e.getMessage());
   e.printStackTrace();
  } catch (Exception e) {
   e.printStackTrace();
   logger.info(e.getMessage());
  } finally {
   session.disconnect();
   logger.info("Disconnected....");
  }
 }

 private static void executeCommand(Session session, String command) throws JSchException, IOException {
  Channel channel = session.openChannel("exec");
  ((ChannelExec) channel).setCommand(command);
  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();
 }

 public static class MyUserInfo implements UserInfo, UIKeyboardInteractive {

  @Override
  public String getPassphrase() {
   return null;
  }

  @Override
  public String getPassword() {
   return null;
  }

  @Override
  public boolean promptPassphrase(String arg0) {
   return false;
  }

  @Override
  public boolean promptPassword(String arg0) {
   return false;
  }

  @Override
  public boolean promptYesNo(String arg0) {
   return false;
  }

  @Override
  public void showMessage(String arg0) {
  }

  @Override
  public String[] promptKeyboardInteractive(String arg0, String arg1, String arg2, String[] arg3,
    boolean[] arg4) {
   return null;
  }
 }

}