Example #1
0
  // login validateData
  private void validateData() {
    String host = jTextField1.getText();
    String username = jTextField2.getText();
    int port = 22;

    try {
      port = Integer.parseInt(jTextField3.getText());
    } catch (NumberFormatException e) {
      JOptionPane.showMessageDialog(this, "端口号必须为数字");
      return;
    }
    if (host.length() == 0) {
      JOptionPane.showMessageDialog(this, "必须填写主机");
      return;
    }
    if (username.length() == 0) {
      JOptionPane.showMessageDialog(this, "必须填写登陆用户名");
      return;
    }

    //		jTextField1.setVisible(false);
    //		jTextField2.setVisible(false);
    //		jTextField3.setVisible(false);
    //		jButton1.setVisible(false);
    //		jButton2.setVisible(false);

    ConService cs = null;
    // TODO must
    try {
      cs = new ConService(host, port, username);
      initPassword();
      // if failure while
      while (!cs.login(pass)) {
        initPassword();
      }
      // opensession
      Session sess = cs.getSession();

      int x_width = 90;
      int y_width = 20;

      sess.requestPTY("temp", x_width, y_width, 0, 0, null);
      sess.startShell();

      TerminalDialog td =
          new TerminalDialog(myframe, username + "@" + host, sess, x_width, y_width);

      /* The following call blocks until the dialog has been closed */

      td.setVisible(true);

      //			myframe.dispose();

    } catch (Exception e) {
      JOptionPane.showMessageDialog(this, e.getMessage());
    }
  }
  public static void main(String[] args) throws IOException {
    String hostname = "somehost";
    String username = "******";
    String password = "******";

    File knownHosts = new File("~/.ssh/known_hosts");

    try {
      /* Load known_hosts file into in-memory database */

      if (knownHosts.exists()) database.addHostkeys(knownHosts);

      /* Create a connection instance */

      Connection conn = new Connection(hostname);

      /* Now connect and use the SimpleVerifier */

      conn.connect(new SimpleVerifier(database));

      /* Authenticate */

      boolean isAuthenticated = conn.authenticateWithPassword(username, password);

      if (isAuthenticated == false) throw new IOException("Authentication failed.");

      /* Create a session */

      Session sess = conn.openSession();

      sess.execCommand("uname -a && date && uptime && who");

      InputStream stdout = new StreamGobbler(sess.getStdout());
      BufferedReader br = new BufferedReader(new InputStreamReader(stdout));

      System.out.println("Here is some information about the remote host:");

      while (true) {
        String line = br.readLine();
        if (line == null) break;
        System.out.println(line);
      }

      /* Close this session */

      sess.close();

      /* Close the connection */

      conn.close();

    } catch (IOException e) {
      e.printStackTrace(System.err);
      System.exit(2);
    }
  }
Example #3
0
  public static void main(String[] args) {
    String hostname = "127.0.0.1";
    String username = "******";

    File keyfile = new File("~/.ssh/id_rsa"); // or "~/.ssh/id_dsa"
    String keyfilePass = "******"; // will be ignored if not needed

    try {
      /* Create a connection instance */

      Connection conn = new Connection(hostname);

      /* Now connect */

      conn.connect();

      /* Authenticate */

      boolean isAuthenticated = conn.authenticateWithPublicKey(username, keyfile, keyfilePass);

      if (isAuthenticated == false) throw new IOException("Authentication failed.");

      /* Create a session */

      Session sess = conn.openSession();

      sess.execCommand("uname -a && date && uptime && who");

      InputStream stdout = new StreamGobbler(sess.getStdout());

      BufferedReader br = new BufferedReader(new InputStreamReader(stdout));

      System.out.println("Here is some information about the remote host:");

      while (true) {
        String line = br.readLine();
        if (line == null) break;
        System.out.println(line);
      }

      /* Close this session */

      sess.close();

      /* Close the connection */

      conn.close();

    } catch (IOException e) {
      e.printStackTrace(System.err);
      System.exit(2);
    }
  }
Example #4
0
 private void runCommand(final CommandToDo commandToDo) throws IOException {
   final SSHConnection sshConnection = context.getSSHConnection();
   final String requestPTY = context.getRequestPTY();
   final Session session = sshConnection.getConnection().openSession();
   try {
     if (requestPTY != null) {
       session.requestPTY(requestPTY, Const.TERMINAL_WIDTH, Const.TERMINAL_HEIGHT, 0, 0, null);
     }
     runCommand(commandToDo, session);
   } finally {
     session.close();
   }
 }
Example #5
0
 private int waitForData(final Session session, final long pollInterval) throws IOException {
   int condition;
   do {
     ThreadU.sleepMillis(pollInterval);
     condition = session.waitForCondition(Const.DATA, pollInterval);
   } while ((condition & Const.DATA) != 0);
   return condition;
 }
Example #6
0
 private void runCommand(final CommandToDo commandToDo, final Session session) throws IOException {
   final CommandWork commandWork = script.startCommand(commandToDo, UTF8Codec.Const.UTF8, null);
   Integer exitValue = null;
   try {
     session.execCommand(commandWork.getStdin());
     exitValue = monitorCommand(commandWork, session);
   } catch (IOException e) {
     commandWork.getByteBufferStderr().addString(e.getMessage());
   } finally {
     script.finishCommand(commandWork, exitValue);
     context.getSSHConnection().update(commandWork.getStart());
   }
 }
Example #7
0
 @SuppressWarnings({"PMD.GuardLogStatementJavaUtil", "PMD.GuardLogStatement"})
 private Integer monitorCommand(final CommandWork commandWork, final Session session)
     throws IOException {
   final ExecutorService executorStream = context.getExecutorStream();
   final long pollInterval = context.getPollInterval();
   final ByteBuffer bufferStdin = commandWork.getByteBufferStdin();
   final ByteBuffer bufferStdout = commandWork.getByteBufferStdout();
   final ByteBuffer bufferStderr = commandWork.getByteBufferStderr();
   final OutputStream stdin = session.getStdin();
   final InputStream stdout = session.getStdout();
   final InputStream stderr = session.getStderr();
   // allow for supplemental process input
   final OutputStreamRunnable runnableStdin =
       new OutputStreamRunnable(stdin, bufferStdin, pollInterval);
   executorStream.execute(runnableStdin);
   // monitor process
   final InputStreamRunnable runnableStdout =
       new InputStreamRunnable(stdout, bufferStdout, pollInterval);
   final InputStreamRunnable runnableStderr =
       new InputStreamRunnable(stderr, bufferStderr, pollInterval);
   final InputStreamRunnable[] streams = {runnableStdout, runnableStderr};
   for (final InputStreamRunnable stream : streams) {
     executorStream.execute(stream);
   }
   // monitor process
   final int conditionExit = session.waitForCondition(ChannelCondition.EXIT_STATUS, 0L);
   logger.finest("conditionExitStatus/" + conditionExit); // i18n log
   final int conditionData = waitForData(session, runnableStdout.getPollInterval());
   logger.finest("conditionData/" + conditionData); // i18n log
   final Integer exitValue = session.getExitStatus();
   // allow process complete
   runnableStdin.stop();
   for (final InputStreamRunnable stream : streams) {
     stream.waitForComplete();
   }
   // notify caller thread
   MutexU.notifyAll(this);
   return exitValue;
 }
Example #8
0
  static void increaseCPU(OnDemandAWS pc, String keyName) throws InterruptedException {

    File keyfile = new File(keyName + ".pem"); // or "~/.ssh/id_dsa"
    String keyfilePass = "******"; // will be ignored if not needed

    try {
      Connection conn = new Connection(pc.ipAddress);
      conn.connect();

      boolean isAuthenticated = conn.authenticateWithPublicKey("ec2-user", keyfile, keyfilePass);
      if (isAuthenticated == false) throw new IOException("Authentication failed.");

      Session sess = conn.openSession();
      System.out.println("Increasing CPU usage for " + pc.machineName);
      sess.execCommand("while true; do true; done");
      sess.close();
      conn.close();

    } catch (IOException e) {
      e.printStackTrace(System.err);
      System.out.println("Please use the attached script to start and stop cpu remotely");
    }
  }
Example #9
0
  public String executeCommand(List<String> commands) throws IOException, InterruptedException {
    InputStream stdout;
    InputStream stderr;
    Session sess = connection.openSession();
    sess.requestPTY("bash");
    sess.startShell();
    PrintWriter out = new PrintWriter(sess.getStdin());
    for (String command : commands) {
      out.println(command);
    }
    out.println("exit");
    out.flush();
    out.close();
    stdout = new StreamGobbler(sess.getStdout());
    stderr = new StreamGobbler(sess.getStderr());
    final BufferedReader stdoutReader =
        new BufferedReader(new InputStreamReader(stdout, tools.office.StringUtils.getUTF8String()));
    final BufferedReader stderrReader =
        new BufferedReader(new InputStreamReader(stderr, tools.office.StringUtils.getUTF8String()));

    final StringBuilder returnBuilder = new StringBuilder();
    final Thread readThread =
        new Thread() {
          public void run() {
            String line;
            while (true) {
              try {
                line = stdoutReader.readLine();
                if (line == null) {
                  break;
                }
                returnBuilder.append(line + tools.file.FileUtils.Line_SEP);
              } catch (IOException e) {
                returnBuilder.append(e.getCause() + e.getMessage());
                break;
              }
            }
          }
        };
    Thread readErrThread =
        new Thread() {
          public void run() {
            String errline;
            while (true) {
              try {
                errline = stderrReader.readLine();
                if (errline == null) {
                  break;
                }
                returnBuilder.append(errline + tools.file.FileUtils.Line_SEP);
              } catch (IOException e) {
                returnBuilder.append(e.getCause() + e.getMessage());
                break;
              }
            }
          }
        };
    stdoutReader.close();
    stderrReader.close();
    readThread.start();
    readErrThread.start();
    readThread.join();
    readErrThread.join();
    sess.close();

    return returnBuilder.toString();
  }
Example #10
0
  /**
   * Validates the Flow target given by attempting to retrieve data
   *
   * @param target The target to validate
   * @return VALIDATED if the target was successfully validated, an error message otherwise
   */
  public static String validateFlowTarget(VMTTarget target) {

    if (target != null) {
      String logPrefix = target.getNameOrAddress() + " : ";

      if (!FeaturesManager.vmtMANAGER.isNetworkModeEnabled()) {

        logger.warn(logPrefix + "Validation failed");
        return UNLICENSED;
      }

      if ("NETFLOW".equals(target.getVersion())) {

        ch.ethz.ssh2.Connection conn = null;
        try {

          if (logger.isDebugEnabled())
            logger.debug(logPrefix + "Validating " + target.getNameOrAddress());

          VMTCredentials credentials = target.getCredentials();
          if (credentials instanceof UsernamePassword) {

            UsernamePassword user = (UsernamePassword) credentials;
            String password =
                VMTEncryptionUtil.decrypt(
                    credentials, MediationPackage.eINSTANCE.getUsernamePassword_Password());
            conn =
                SshUtil.establishConnection(
                    target.getNameOrAddress(), user.getUsername(), password);
            if (conn != null && conn.isAuthenticationComplete()) {
              Session ioSess = conn.openSession();
              ioSess.execCommand(nFlowDumpCommand);
              return VALIDATED;
            } else {
              logger.warn(logPrefix + "Validation failed");
              String reason =
                  "Cannot establish SSH connection with the flow collector using the credential";
              return reason;
            }
          }
        } catch (Exception e) {
          logger.warn(logPrefix + "Validation failed");
          return e.getClass().getSimpleName();
        } finally {
          SshUtil.closeConnection(conn, target);
        }
      } else if ("SFLOW".equals(target.getVersion())) {

        String targetAddress = target.getNameOrAddress();
        String url = formUrl(targetAddress, SFLOW_REQUEST_IN_JSON);
        URL nodesURL;
        URLConnection nodesConnection = null;
        InputStreamReader in = null;
        try {

          nodesURL = new java.net.URL(url);
          nodesConnection = nodesURL.openConnection();
          nodesConnection.connect();
          in = new InputStreamReader((InputStream) nodesConnection.getContent());
          if (in.ready()) return VALIDATED;
          else return "Cannot validate the SFLOW target";
        } catch (Exception e) {
          return e.getMessage();
        } finally {
          // Close the connection
          if (in != null) {
            try {
              in.close();
            } catch (IOException e) {
              handleException(
                  e,
                  logger,
                  "The following exception occured while attempting to close the connection");
            }
          }
        }
      }

    } else {
      logger.warn("Null target : Validation failed");
      return "TARGET IS NULL";
    }
    return VALIDATED; // TODO: probably not the wanted behaviour
  }