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);
    }
  }
示例#2
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);
    }
  }
示例#3
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());
   }
 }
示例#4
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");
    }
  }
示例#5
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
  }