Search This Blog

Thursday, July 12, 2012

How to run a unix command remotely using java

 

Download the jar file from ,

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

http://nchc.dl.sourceforge.net/project/jsch/jsch.jar/0.1.48/jsch-0.1.48.jar

package test1;
import com.jcraft.jsch.*;
import java.io.*;
public class Class2 {
  public Class2() {
    super();
  }
  public static void main(String[] args) throws Exception {
    testconnect();
  }
      public static void testconnect() throws JSchException, IOException {
           String userName = "xxxx";
           String password ="xxxx";
           String hostName = "xxx.xx.oracle.com";
           int port = 22;
        String sdstestCommand = "env";
              JSch jsch = new JSch();
              Session session = jsch.getSession(userName, hostName, port);
              session.setConfig("StrictHostKeyChecking", "no");
              session.setPassword(password);
              session.connect();    
              ChannelExec channel = (ChannelExec) session.openChannel("exec");
              channel.setCommand(sdstestCommand);
              channel.setInputStream(null);
              ((ChannelExec) channel).setErrStream(System.err);
              InputStream in = channel.getInputStream();
              channel.connect();
              System.out.println("Unix system connected...");
              byte[] tmp = new byte[1024];
              while (true){
                  while (in.available() > 0) {
                      int i = in.read(tmp, 0, 1024);
                      if (i < 0) {
                          break;
                      }
                      String line = new String(tmp, 0, i);
                      System.out.println("Unix system console output: " +line);
                  }
                  if (channel.isClosed()){
                      break;
                  }
                  try {
                      Thread.sleep(1000);
                  } catch (Exception ee){
                      //ignore
                  }
              }
              channel.disconnect();
              session.disconnect();     
          }
    }

1 comment:

Unknown said...

When I m using this code in my web-application and deploying it on Weblogic then the code works fine but when the session.disconnect() method got excuted after that nothing happens like no further execution of the code and no exception is coming and the server logs also not updating after this.

Any help is appreciated..