Ejemplo n.º 1
0
  public static void main(String[] args) {
    String hostname = "123.57.48.109";
    String username = "******";
    String password = "******";

    try {
      /* Create a connection instance */

      Connection conn = new Connection(hostname);

      /* Now connect */

      conn.connect();

      /* Authenticate */

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

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

      /* Create a session */

      SCPClient scpclient = conn.createSCPClient();

      scpclient.get("/alidata/account.log", "D:\\temp");

      /* Close the connection */

      conn.close();

    } catch (IOException e) {
      e.printStackTrace(System.err);
      System.exit(2);
    }
  }
  @OnEvent(component = "UpdateClusterParamsForm", value = "submit")
  @Secured("ROLE_ADMIN")
  Object onUpdateClusterParamsForm() {
    String info = "Update: Ok<br/>";
    info += dataSource.updateParams(cluster);
    Cache.refreshClusterParams();

    if (!cluster.isLocal()) {
      try {
        Connection conn =
            PublicKeyAuthentication.connect(
                cluster.getUsername(),
                cluster.getHostname(),
                cluster.getPrivateKeyPath(),
                cluster.getPassphrase());
        if (conn != null) {
          conn.close();
        }
      } catch (Exception e) {
        info = e.getMessage();
        e.printStackTrace();
      }
    }

    infoPage.setUp(info, "Updating cluster params:");

    return infoPage;
  }
  @Override
  public Session connect(UserDetails userDetails, boolean verifyHostKey) throws Throwable {
    ConnectionInfo connInfo =
        ganymedConn.connect(
            verifyHostKey
                ? new ServerHostKeyVerifier() {

                  @Override
                  public boolean verifyServerHostKey(
                      String hostname,
                      int port,
                      String serverHostKeyAlgorithm,
                      byte[] serverHostKey)
                      throws Exception {
                    if (_serverDetails.hostKey() == null) {
                      // no host key is stored locally.
                      return false;
                    }
                    if (!_serverDetails.host().equals(hostname)) {
                      // host name not equal
                      return false;
                    }
                    String algorithm = _serverDetails.hostKeyAlgorithm();
                    if (algorithm == null || !algorithm.equals(serverHostKeyAlgorithm)) {
                      // host key algorithm does not match
                      return false;
                    }
                    byte[] hostKey = _serverDetails.hostKeyBytes();
                    return Arrays.equals(hostKey, serverHostKey);
                  }
                }
                : null);
    if (connInfo.serverHostKey != null && _serverDetails.hostKey() == null) {
      _serverDetails.setHostKey(connInfo.serverHostKey);
    }
    boolean authenticated = false;
    if (userDetails.password() == null && userDetails.privateKey() == null) {
      throw new IllegalArgumentException(
          "Expecting user password or private key. None is specified.");
    }
    if (userDetails.password() != null) {
      authenticated =
          ganymedConn.authenticateWithPassword(userDetails.username(), userDetails.password());
    }
    if (!authenticated && userDetails.privateKey() != null) {
      authenticated =
          ganymedConn.authenticateWithPublicKey(
              userDetails.username(),
              userDetails.privateKey().toCharArray(),
              userDetails.passphrase());
    }
    if (!authenticated) {
      throw new RuntimeException("Failed to authenticate user " + userDetails.username());
    }
    GanymedSession session = new GanymedSession(userDetails, this);
    session.open();
    return session;
  }
  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);
    }
  }
Ejemplo n.º 5
0
  public void connect() throws IOException {
    try {
      connection.connect();
      isAuthenticated = connection.authenticateWithPassword(account, password); // Authenticate
      if (!isAuthenticated) {
        throw new IOException("isAuthenticated=" + isAuthenticated);
      }

    } catch (IOException e) {
      throw e;
    }
  }
Ejemplo n.º 6
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);
    }
  }
Ejemplo n.º 7
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");
    }
  }
Ejemplo n.º 8
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();
  }
Ejemplo n.º 9
0
 public void disconnect() {
   connection.close();
 }
Ejemplo n.º 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
  }
Ejemplo n.º 11
0
 @Override
 public void disconnect() throws Throwable {
   ganymedConn.close();
 }