Exemplo n.º 1
0
  /**
   * This will execute the given command with given session and session is not closed at the end.
   *
   * @param commandInfo
   * @param session
   * @param commandOutput
   * @throws SSHApiException
   */
  public static Session executeCommand(
      CommandInfo commandInfo, Session session, CommandOutput commandOutput)
      throws SSHApiException {

    String command = commandInfo.getCommand();

    Channel channel = null;
    try {
      if (!session.isConnected()) {
        session.connect();
      }
      channel = session.openChannel("exec");
      ((ChannelExec) channel).setCommand(command);
    } catch (JSchException e) {
      session.disconnect();

      throw new SSHApiException("Unable to execute command - ", e);
    }

    channel.setInputStream(null);
    ((ChannelExec) channel).setErrStream(commandOutput.getStandardError());
    try {
      channel.connect();
    } catch (JSchException e) {

      channel.disconnect();
      session.disconnect();
      throw new SSHApiException("Unable to retrieve command output. Command - " + command, e);
    }

    commandOutput.onOutput(channel);
    // Only disconnecting the channel, session can be reused
    channel.disconnect();
    return session;
  }
Exemplo n.º 2
0
 public <T> T await(Command<K, V, T> cmd, long timeout, TimeUnit unit) {
   if (!cmd.await(timeout, unit)) {
     cmd.cancel(true);
     throw new RedisException("Command timed out");
   }
   CommandOutput<K, V, T> output = cmd.getOutput();
   if (output.hasError()) throw new RedisException(output.getError());
   return output.get();
 }
Exemplo n.º 3
0
 /** @inheritDoc */
 @Override
 public void printError(Throwable e) {
   switch (config.getVerboseLevel()) {
     case VERBOSE:
       output.printError(e);
       break;
     case SILENT:
       break;
     case BRIEF:
     default:
       output.printMessage("#" + ExceptionUtils.getMessage(e));
       break;
   }
 }
Exemplo n.º 4
0
 /**
  * Get the command output and if the command hasn't completed yet, wait until it does.
  *
  * @return The command output.
  */
 @Override
 public T get() {
   try {
     latch.await();
     return output.get();
   } catch (InterruptedException e) {
     throw new RedisCommandInterruptedException(e);
   }
 }
Exemplo n.º 5
0
  public CommandOutput getCommandOutput(String shellId, String commandId) {
    String messageId = UUID.randomUUID().toString();
    HashMap<String, String> options = null; // new HashMap<>();

    prepareRequest(URI_ACTION_SHELL_RECEIVE, shellId, messageId, options);

    // add SOAP body
    Receive recv = new Receive();
    DesiredStreamType stream = new DesiredStreamType();
    stream.setCommandId(commandId);
    stream.getValue().add("stdout stderr");
    recv.setDesiredStream(stream);

    CommandOutput commandOutput = new CommandOutput();

    // fetch output in a loop until command finishes
    while (true) {
      ReceiveResponse response = wsmanService.receive(recv); // ws call

      for (StreamType streamItem : response.getStream()) {
        if (streamItem.getName().equals("stdout")) {
          try {
            commandOutput.std_out += Base64Utility.decode(new String(streamItem.getValue()));
          } catch (Base64Exception ex) {
            Logger.getLogger(Protocol.class.getName()).log(Level.SEVERE, null, ex);
          }
        } else if (streamItem.getName().equals("stderr")) {
          try {
            commandOutput.std_err += Base64Utility.decode(new String(streamItem.getValue()));
          } catch (Base64Exception ex) {
            Logger.getLogger(Protocol.class.getName()).log(Level.SEVERE, null, ex);
          }
        }
      }

      // quit loop when command output says 'done'
      if (response.getCommandState().getState().equals(COMMAND_STATE_DONE)) {
        commandOutput.statusCode = response.getCommandState().getExitCode().intValue();
        break;
      }
    }

    return commandOutput;
  }
Exemplo n.º 6
0
 /**
  * Get the command output and if the command hasn't completed yet, wait up to the specified time
  * until it does.
  *
  * @param timeout Maximum time to wait for a result.
  * @param unit Unit of time for the timeout.
  * @return The command output.
  * @throws TimeoutException if the wait timed out.
  */
 @Override
 public T get(long timeout, TimeUnit unit) throws TimeoutException {
   try {
     // 等待线程
     if (!latch.await(timeout, unit)) {
       throw new TimeoutException("Command timed out");
     }
   } catch (InterruptedException e) {
     throw new RedisCommandInterruptedException(e);
   }
   return output.get();
 }
Exemplo n.º 7
0
 /** @inheritDoc */
 @Override
 public void printMessage(String message) {
   if (config.getVerboseLevel() != VerboseLevel.SILENT) {
     output.printMessage("#" + message);
   }
 }
Exemplo n.º 8
0
 /** @inheritDoc */
 @Override
 public void print(String value) {
   output.print(value);
 }
Exemplo n.º 9
0
 /** @inheritDoc */
 @Override
 public void close() {
   output.close();
 }
Exemplo n.º 10
0
  /**
   * This will not reuse any session, it will create the session and close it at the end
   *
   * @param commandInfo Encapsulated information about command. E.g :- executable name parameters
   *     etc ...
   * @param serverInfo The SSHing server information.
   * @param authenticationInfo Security data needs to be communicated with remote server.
   * @param commandOutput The output of the command.
   * @param configReader configuration required for ssh/gshissh connection
   * @throws SSHApiException throw exception when error occurs
   */
  public static void executeCommand(
      CommandInfo commandInfo,
      ServerInfo serverInfo,
      AuthenticationInfo authenticationInfo,
      CommandOutput commandOutput,
      ConfigReader configReader)
      throws SSHApiException {

    if (authenticationInfo instanceof GSIAuthenticationInfo) {
      System.setProperty(
          X509_CERT_DIR,
          (String)
              ((GSIAuthenticationInfo) authenticationInfo).getProperties().get("X509_CERT_DIR"));
    }

    JSch jsch = new ExtendedJSch();

    log.debug(
        "Connecting to server - "
            + serverInfo.getHost()
            + ":"
            + serverInfo.getPort()
            + " with user name - "
            + serverInfo.getUserName());

    Session session;

    try {
      session =
          jsch.getSession(serverInfo.getUserName(), serverInfo.getHost(), serverInfo.getPort());
    } catch (JSchException e) {
      throw new SSHApiException(
          "An exception occurred while creating SSH session."
              + "Connecting server - "
              + serverInfo.getHost()
              + ":"
              + serverInfo.getPort()
              + " connecting user name - "
              + serverInfo.getUserName(),
          e);
    }

    java.util.Properties config = configReader.getProperties();
    session.setConfig(config);

    // =============================================================
    // Handling vanilla SSH pieces
    // =============================================================
    if (authenticationInfo instanceof SSHPasswordAuthentication) {
      String password =
          ((SSHPasswordAuthentication) authenticationInfo)
              .getPassword(serverInfo.getUserName(), serverInfo.getHost());

      session.setUserInfo(new SSHAPIUIKeyboardInteractive(password));

      // TODO figure out why we need to set password to session
      session.setPassword(password);

    } else if (authenticationInfo instanceof SSHPublicKeyFileAuthentication) {
      SSHPublicKeyFileAuthentication sshPublicKeyFileAuthentication =
          (SSHPublicKeyFileAuthentication) authenticationInfo;

      String privateKeyFile =
          sshPublicKeyFileAuthentication.getPrivateKeyFile(
              serverInfo.getUserName(), serverInfo.getHost());

      logDebug("The private key file for vanilla SSH " + privateKeyFile);

      String publicKeyFile =
          sshPublicKeyFileAuthentication.getPrivateKeyFile(
              serverInfo.getUserName(), serverInfo.getHost());

      logDebug("The public key file for vanilla SSH " + publicKeyFile);

      Identity identityFile;

      try {
        identityFile = GSISSHIdentityFile.newInstance(privateKeyFile, null, jsch);
      } catch (JSchException e) {
        throw new SSHApiException(
            "An exception occurred while initializing keys using files. "
                + "(private key and public key)."
                + "Connecting server - "
                + serverInfo.getHost()
                + ":"
                + serverInfo.getPort()
                + " connecting user name - "
                + serverInfo.getUserName()
                + " private key file - "
                + privateKeyFile
                + ", public key file - "
                + publicKeyFile,
            e);
      }

      // Add identity to identity repository
      GSISSHIdentityRepository identityRepository = new GSISSHIdentityRepository(jsch);
      identityRepository.add(identityFile);

      // Set repository to session
      session.setIdentityRepository(identityRepository);

      // Set the user info
      SSHKeyPasswordHandler sshKeyPasswordHandler =
          new SSHKeyPasswordHandler((SSHKeyAuthentication) authenticationInfo);

      session.setUserInfo(sshKeyPasswordHandler);

    } else if (authenticationInfo instanceof SSHPublicKeyAuthentication) {

      SSHPublicKeyAuthentication sshPublicKeyAuthentication =
          (SSHPublicKeyAuthentication) authenticationInfo;

      Identity identityFile;

      try {
        String name = serverInfo.getUserName() + "_" + serverInfo.getHost();
        identityFile =
            GSISSHIdentityFile.newInstance(
                name,
                sshPublicKeyAuthentication.getPrivateKey(
                    serverInfo.getUserName(), serverInfo.getHost()),
                sshPublicKeyAuthentication.getPublicKey(
                    serverInfo.getUserName(), serverInfo.getHost()),
                jsch);
      } catch (JSchException e) {
        throw new SSHApiException(
            "An exception occurred while initializing keys using byte arrays. "
                + "(private key and public key)."
                + "Connecting server - "
                + serverInfo.getHost()
                + ":"
                + serverInfo.getPort()
                + " connecting user name - "
                + serverInfo.getUserName(),
            e);
      }

      // Add identity to identity repository
      GSISSHIdentityRepository identityRepository = new GSISSHIdentityRepository(jsch);
      identityRepository.add(identityFile);

      // Set repository to session
      session.setIdentityRepository(identityRepository);

      // Set the user info
      SSHKeyPasswordHandler sshKeyPasswordHandler =
          new SSHKeyPasswordHandler((SSHKeyAuthentication) authenticationInfo);

      session.setUserInfo(sshKeyPasswordHandler);
    }

    // Not a good way, but we dont have any choice
    if (session instanceof ExtendedSession) {
      if (authenticationInfo instanceof GSIAuthenticationInfo) {
        ((ExtendedSession) session)
            .setAuthenticationInfo((GSIAuthenticationInfo) authenticationInfo);
      }
    }

    try {
      session.connect();
    } catch (JSchException e) {
      throw new SSHApiException(
          "An exception occurred while connecting to server."
              + "Connecting server - "
              + serverInfo.getHost()
              + ":"
              + serverInfo.getPort()
              + " connecting user name - "
              + serverInfo.getUserName(),
          e);
    }

    String command = commandInfo.getCommand();

    Channel channel;
    try {
      channel = session.openChannel("exec");
      ((ChannelExec) channel).setCommand(command);
    } catch (JSchException e) {
      session.disconnect();

      throw new SSHApiException(
          "Unable to execute command - "
              + command
              + " on server - "
              + serverInfo.getHost()
              + ":"
              + serverInfo.getPort()
              + " connecting user name - "
              + serverInfo.getUserName(),
          e);
    }

    channel.setInputStream(null);
    ((ChannelExec) channel).setErrStream(commandOutput.getStandardError());

    try {
      channel.connect();
    } catch (JSchException e) {

      channel.disconnect();
      session.disconnect();

      throw new SSHApiException(
          "Unable to retrieve command output. Command - "
              + command
              + " on server - "
              + serverInfo.getHost()
              + ":"
              + serverInfo.getPort()
              + " connecting user name - "
              + serverInfo.getUserName(),
          e);
    }

    commandOutput.onOutput(channel);

    channel.disconnect();
    session.disconnect();
  }