본문 바로가기

IT/java

[java] J2ssh 사용하여 서버에 command 실행 및 결과 받아 오기

import java.util.StringTokenizer;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.sshtools.j2ssh.SshClient;
import com.sshtools.j2ssh.authentication.AuthenticationProtocolState;
import com.sshtools.j2ssh.authentication.PasswordAuthenticationClient;
import com.sshtools.j2ssh.connection.ChannelInputStream;
import com.sshtools.j2ssh.connection.ChannelOutputStream;
import com.sshtools.j2ssh.session.SessionChannelClient;
import com.sshtools.j2ssh.transport.IgnoreHostKeyVerification;

 

public class J2sshClient
{
 private Log log = LogFactory.getLog(this.getClass());
 private SshClient client = null;
 private SessionChannelClient session = null;
 private String hostPrompt = null;

 public J2sshClient(String server, int port, String user, String pwd)
 throws Exception
 {
  PasswordAuthenticationClient auth = null;

  try {
   if (server == null || user == null ||  pwd == null) {
    System.out.println("Parameter is null!");
   }
   client = new SshClient();
   client.setSocketTimeout(70000);
   client.connect(server, port, new IgnoreHostKeyVerification());
//   client.connect(server, port);
   auth = new PasswordAuthenticationClient();
   auth.setUsername(user);
   auth.setPassword(pwd);
   int result = client.authenticate(auth);
   if (result != AuthenticationProtocolState.COMPLETE) {
    throw new Exception("Login failed");
   }
   // SSH 터미널 커맨드 실행용
   session = client.openSessionChannel();
   session.requestPseudoTerminal("vt100", 80, 25, 0, 0 , "");
   session.startShell();
  } catch (Exception e) {
   e.printStackTrace();
   log.error(e);
   throw e;
  }
 }
 /*
  * 커맨드 실행 함수(ex : ls -l\n)
  */
 public String exec(String cmd) throws Exception
 {

  String returnVal = "";
  StringBuffer bufferVal = null;
  boolean promptReturned = false;
  byte[] buffer = null;
  ChannelOutputStream out = null;
  ChannelInputStream in = null;
  int read;
  String response = null;
  int i = 0;
  byte[] command = cmd.getBytes();


  try {
   if (session == null) {
    log.error("Session is not connected!");
    throw new Exception("Session is not connected!");
   }

   out = session.getOutputStream();
   out.write(command, 0, cmd.length());
   in = session.getInputStream();
   buffer = new byte[255];
   bufferVal = new StringBuffer(300);


   while(promptReturned == false && (read = in.read(buffer) )> 0) {
    response = new String(buffer, 0, read);
    System.out.println("promptReturned="+promptReturned + " / read=" + read + " / message=" + response);
    if (i == 1){
     bufferVal.append(response.toString());
    }
    if (!(response == null ||  "".equals(response)) && response.indexOf(this.hostPrompt) >= 0) {
     ++i;
     if (i >= 2) {
      promptReturned = true;
     }
    }
   }
   log.error("returnValue : " + bufferVal.toString());

   // bufferVal에 담기는 값은 명령어까지 함께 담기기 때문에 한줄 당위로 분리해서 결과값만 returnVal에 담는다.
   StringTokenizer st = new StringTokenizer(bufferVal.toString(),"\n");
   if ( st.hasMoreTokens() ) {
    st.nextToken();
    returnVal = st.nextToken();
   }
  } catch (Exception e) {
   e.printStackTrace();
   log.error(e);
  }
  return returnVal;
 }

 public boolean isClosed() throws Exception
 {
  boolean rtn = true;
  try {
   if (session != null)
    rtn = session.isClosed();
  } catch(Exception e) {
   e.printStackTrace();
   log.error(e);
  }
  return rtn;
 }

 public boolean logout() throws Exception
 {
  boolean rtn = false;
  try {
   if (session != null) {
    session.getOutputStream().write("exit\n".getBytes());
    session.close();
   }
   if (client != null)
    client.disconnect();
   rtn = true;
  } catch(Exception e) {
   e.printStackTrace();
   log.error(e);
  }
  return rtn;
 }

 public String getHostprompt() {
  return this.hostPrompt;
 }

 public void setHostprompt(String hostPrompt) {
  this.hostPrompt = hostPrompt;
 }

 public static void main(String[] args)
 {
  try {
   /* ssh exec command */
   J2sshClient jsclient = new J2sshClient("linux5" ,22 ,"root" ,"manager1234");
   jsclient.setHostprompt("[root@linux5 ~]# ");
   String result = jsclient.exec("crontab -l \n");
   System.out.println("jsclient.exec :" + result);
   jsclient.logout();
   System.out.println("isClosed : " + jsclient.isClosed());
  } catch (Exception e) {
   System.out.println(e);
  }
 }
}