'Ant Java'에 해당되는 글 1건

  1. 2010.08.24 SSHTool을 사용하여 Ant Task 만들기


package test;

import java.io.InputStream;
import java.io.OutputStream;

import org.apache.commons.lang.StringUtils;

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

public class Test {
 SessionChannelClient session;

 /**
  * @param args
  * @throws Exception
  */
 public static void main(String[] args) throws Exception {
  Test test = new Test();
  test.connectServer("호스트명", "아이디", "비밀번호",포트);
  test.exec("1\n");
  Thread.sleep(1000);
   }

 public void connectServer(String host, String username, String password,
   int port) {
  SshClient sshClient = null;
  PasswordAuthenticationClient authentication = null;

  try {
   sshClient = new SshClient();
   sshClient.setSocketTimeout(10000);
   sshClient.connect(host, port, new IgnoreHostKeyVerification());

   authentication = new PasswordAuthenticationClient();
   authentication.setUsername(username);
   authentication.setPassword(password);

   String message = "##### Server(host : " + host + ", username : "
     + username + ") connect is";
   int result = sshClient.authenticate(authentication);
   session = sshClient.openSessionChannel();
   if (result == AuthenticationProtocolState.COMPLETE) {
    System.out.println(message + " complete!!!");
    if (session.requestPseudoTerminal("vt100", 80, 24, 0, 0, "")) {
     session.startShell();
     read();
     read();
    }
   }
  } catch (Exception e) {
   e.printStackTrace();
  }
 }

 public void read(){
  try {
   InputStream in = session.getInputStream();
   byte[] buf = new byte[4096];
   int readCount = 0;
   int count = 1;
   while ((readCount = in.read(buf)) != -1) {
    count++;
    String data = new String(buf, 0, readCount);
    System.out.println(data);
    if(data.indexOf(":")>0){
     break;
    }
   }
  } catch (Exception e) {
   e.printStackTrace();
  } finally{
  }
  
 }

 public void exec(String cmd) throws Exception {
  OutputStream out = session.getOutputStream();
  out.write(cmd.getBytes());
  read();
 }
}

신고
Posted by genius3k

티스토리 툴바