package com.chenyang.nse.bussiness.tools.net;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import org.apache.commons.io.IOUtils;

public class SSHTool {
   private static Connection conn;
   private static String ip;
   private static String osUsername;
   private static String password;
   private static String charset = Charset.defaultCharset().toString();
   private static final int TIME_OUT = 300000;

   public SSHTool(String ip, String usr, String pasword) {
      SSHTool.ip = ip;
      osUsername = usr;
      password = pasword;
   }

   private static boolean login() throws IOException {
      conn = new Connection(ip);
      conn.connect();
      return conn.authenticateWithPassword(osUsername, password);
   }

   public static int exec(String cmds) throws Exception {
      InputStream stdOut = null;
      InputStream stdErr = null;
      String outStr = "";
      String outErr = "";
      int ret = -1;

      try {
         if (!login()) {
            throw new Exception("登录远程机器失败" + ip);
         }

         Session session = conn.openSession();
         session.execCommand(cmds);
         stdOut = new StreamGobbler(session.getStdout());
         outStr = processStream(stdOut, charset);
         stdErr = new StreamGobbler(session.getStderr());
         outErr = processStream(stdErr, charset);
         session.waitForCondition(32, 300000L);
         System.out.println("outStr=" + outStr);
         System.out.println("outErr=" + outErr);
         ret = session.getExitStatus();
      } finally {
         if (conn != null) {
            conn.close();
         }

         IOUtils.closeQuietly(stdOut);
         IOUtils.closeQuietly(stdErr);
      }

      return ret;
   }

   private static String processStream(InputStream in, String charset) throws Exception {
      byte[] buf = new byte[1024];
      StringBuilder sb = new StringBuilder();

      while(in.read(buf) != -1) {
         sb.append(new String(buf, charset));
      }

      return sb.toString();
   }

   public static void main(String[] args) throws Exception {
      SSHTool executor = new SSHTool("192.168.42.111", "root", "123456");
      System.out.println(exec("/test.sh"));
   }
}
