Пример #1
0
  private String execAndGetOutput(String command)
      throws JSchException, MachineException, IOException {
    ChannelExec exec = (ChannelExec) session.openChannel("exec");
    exec.setCommand(command);

    try (BufferedReader reader = new BufferedReader(new InputStreamReader(exec.getInputStream()));
        InputStream erStream = exec.getErrStream()) {

      exec.connect(connectionTimeout);

      ListLineConsumer listLineConsumer = new ListLineConsumer();
      String line;
      while ((line = reader.readLine()) != null) {
        listLineConsumer.writeLine(line);
      }
      // read stream to wait until command finishes its work
      IoUtil.readStream(erStream);
      if (exec.getExitStatus() != 0) {
        throw new MachineException(
            format(
                "Error code: %s. Error: %s",
                exec.getExitStatus(), IoUtil.readAndCloseQuietly(exec.getErrStream())));
      }
      return listLineConsumer.getText();
    } finally {
      exec.disconnect();
    }
  }
Пример #2
0
  public ExecResult executeCommand(Session session, String command, String workingDir)
      throws PortalServiceException {
    ChannelExec channel = null;
    if (workingDir != null) {
      command = "cd " + workingDir + "; " + command;
    }

    try {
      channel = (ChannelExec) session.openChannel("exec");
      channel.setCommand(command);
      channel.setInputStream(null);
      channel.setErrStream(null);

      channel.connect();

      try (InputStream out = channel.getInputStream();
          InputStream err = channel.getErrStream()) {
        String outStr = readStream(out, channel);
        String errStr = readStream(err, channel);
        return new ExecResult(outStr, errStr, channel.getExitStatus());
      } catch (IOException | InterruptedException e) {
        throw new PortalServiceException(e.getMessage(), e);
      }
    } catch (JSchException e) {
      throw new PortalServiceException(e.getMessage(), e);
    } finally {
      if (channel != null) {
        channel.disconnect();
      }
    }
  }
Пример #3
0
 /*
  * (non-Javadoc)
  *
  * @see org.apache.ivy.repository.Repository#list(java.lang.String)
  */
 public List list(String parent) throws IOException {
   Message.debug("SShRepository:list called: " + parent);
   ArrayList result = new ArrayList();
   Session session = null;
   ChannelExec channel = null;
   session = getSession(parent);
   channel = getExecChannel(session);
   URI parentUri = null;
   try {
     parentUri = new URI(parent);
   } catch (URISyntaxException e) {
     IOException ioe = new IOException("The uri '" + parent + "' is not valid!");
     ioe.initCause(e);
     throw ioe;
   }
   String fullCmd = replaceArgument(listCommand, parentUri.getPath());
   channel.setCommand(fullCmd);
   StringBuffer stdOut = new StringBuffer();
   StringBuffer stdErr = new StringBuffer();
   readSessionOutput(channel, stdOut, stdErr);
   if (channel.getExitStatus() != 0) {
     Message.error("Ssh ListCommand exited with status != 0");
     Message.error(stdErr.toString());
     return null;
   } else {
     BufferedReader br = new BufferedReader(new StringReader(stdOut.toString()));
     String line = null;
     while ((line = br.readLine()) != null) {
       result.add(line);
     }
   }
   return result;
 }
Пример #4
0
 /**
  * check for existence of file or dir on target system
  *
  * @param filePath to the object to check
  * @param session to use
  * @return true: object exists, false otherwise
  */
 private boolean checkExistence(String filePath, Session session) throws IOException {
   Message.debug("SShRepository: checkExistence called: " + filePath);
   ChannelExec channel = null;
   channel = getExecChannel(session);
   String fullCmd = replaceArgument(existCommand, filePath);
   channel.setCommand(fullCmd);
   StringBuffer stdOut = new StringBuffer();
   StringBuffer stdErr = new StringBuffer();
   readSessionOutput(channel, stdOut, stdErr);
   return channel.getExitStatus() == 0;
 }
Пример #5
0
 @Override
 public ExecResponse create() throws Exception {
   try {
     ConnectionWithStreams<ChannelExec> connection = execConnection(command);
     executor = acquire(connection);
     String outputString = Strings2.toStringAndClose(connection.getInputStream());
     String errorString = Strings2.toStringAndClose(connection.getErrStream());
     int errorStatus = executor.getExitStatus();
     int i = 0;
     String message = String.format("bad status -1 %s", toString());
     while ((errorStatus = executor.getExitStatus()) == -1
         && i < JschSshClient.this.sshRetries) {
       logger.warn("<< " + message);
       backoffForAttempt(++i, message);
     }
     if (errorStatus == -1) throw new SshException(message);
     return new ExecResponse(outputString, errorString, errorStatus);
   } finally {
     clear();
   }
 }
Пример #6
0
 public ExecResponse exec(String command) {
   checkConnected();
   ChannelExec executor = null;
   try {
     try {
       executor = (ChannelExec) session.openChannel("exec");
       executor.setPty(true);
     } catch (JSchException e) {
       throw new SshException(
           String.format("%s@%s:%d: Error connecting to exec.", username, host, port), e);
     }
     executor.setCommand(command);
     ByteArrayOutputStream error = new ByteArrayOutputStream();
     executor.setErrStream(error);
     try {
       executor.connect();
       String outputString = Strings2.toStringAndClose(executor.getInputStream());
       String errorString = error.toString();
       int errorStatus = executor.getExitStatus();
       int i = 0;
       while ((errorStatus = executor.getExitStatus()) == -1 && i < this.sshRetries)
         backoffForAttempt(++i, String.format("%s@%s:%d: bad status: -1", username, host, port));
       if (errorStatus == -1)
         throw new SshException(
             String.format(
                 "%s@%s:%d: received exit status %d executing %s",
                 username, host, port, executor.getExitStatus(), command));
       return new ExecResponse(outputString, errorString, errorStatus);
     } catch (Exception e) {
       throw new SshException(
           String.format("%s@%s:%d: Error executing command: %s", username, host, port, command),
           e);
     }
   } finally {
     if (executor != null) executor.disconnect();
   }
 }
Пример #7
0
 /**
  * FIXME Comment this
  *
  * @param session
  * @param cmd
  * @return return code of the process.
  * @throws JSchException if there's an underlying problem exposed in SSH
  * @throws IOException if there's a problem attaching streams.
  * @throws TimeoutException if we exceeded our timeout
  */
 private int executeCommand(Session session, String cmd)
     throws JSchException, IOException, TimeoutException {
   final ChannelExec channel;
   session.setTimeout((int) maxwait);
   /* execute the command */
   channel = (ChannelExec) session.openChannel("exec");
   channel.setCommand(cmd);
   attachStreams(channel);
   project.log("executing command: " + cmd, Project.MSG_VERBOSE);
   channel.connect();
   try {
     waitFor(channel);
   } finally {
     streamHandler.stop();
     closeStreams(channel);
   }
   return channel.getExitStatus();
 }
Пример #8
0
  private int execAndGetCode(String command) throws JSchException, IOException {
    ChannelExec exec = (ChannelExec) session.openChannel("exec");
    exec.setCommand(command);

    try (InputStream inStream = exec.getInputStream();
        InputStream erStream = exec.getErrStream()) {

      exec.connect(connectionTimeout);

      // read streams to wait until command finishes its work
      IoUtil.readStream(inStream);
      IoUtil.readStream(erStream);
    } finally {
      exec.disconnect();
    }

    return exec.getExitStatus();
  }
Пример #9
0
  public Streams executeCommand(String command, boolean ignoreFailures)
      throws CommandExecutionException {
    ChannelExec channel = null;
    BufferedReader stdoutReader = null;
    BufferedReader stderrReader = null;
    try {
      channel = (ChannelExec) session.openChannel(EXEC_CHANNEL);

      channel.setCommand(command + "\n");

      InputStream stdout = channel.getInputStream();
      InputStream stderr = channel.getErrStream();

      channel.connect();

      stdoutReader = new BufferedReader(new InputStreamReader(stdout));
      stderrReader = new BufferedReader(new InputStreamReader(stderr));

      Streams streams = CommandExecutorStreamProcessor.processStreams(stderrReader, stdoutReader);

      if (streams.getErr().length() > 0 && !ignoreFailures) {
        int exitCode = channel.getExitStatus();
        throw new CommandExecutionException("Exit code: " + exitCode + " - " + streams.getErr());
      }

      return streams;
    } catch (IOException e) {
      throw new CommandExecutionException("Cannot execute remote command: " + command, e);
    } catch (JSchException e) {
      throw new CommandExecutionException("Cannot execute remote command: " + command, e);
    } finally {
      IOUtil.close(stdoutReader);
      IOUtil.close(stderrReader);
      if (channel != null) {
        channel.disconnect();
      }
    }
  }
Пример #10
0
    @Override
    public Integer call() {
      int exitstatus = Integer.MAX_VALUE;
      Boolean useIdentityFile = null;
      String credentials = null;
      String userName = nodeCredentials.getUsername();

      if (nodeCredentials instanceof LoginCredentialsPassword) {
        useIdentityFile = false;
        credentials = ((LoginCredentialsPassword) nodeCredentials).getPassword();
      } else if (nodeCredentials instanceof LoginCredentialsPrivateKey) {
        useIdentityFile = true;
        credentials = ((LoginCredentialsPrivateKey) nodeCredentials).getKey().getKeyPath();
      }

      ChannelExec c = null;
      SshClient ssh = null;

      try {
        ssh = new SshClient();
        ssh.createSession(nodeAddress, userName, false);

        log.info("connecting with username: "******"connecting using identity file: " + credentials);
        } else {
          log.info("connecting using password: "******"executing command: " + command);
        c.connect();

        new Thread(
                new Runnable() {
                  public void run() {
                    String line;
                    BufferedReader bufferedInputReader =
                        new BufferedReader(new InputStreamReader(is));
                    try {
                      while ((line = bufferedInputReader.readLine()) != null) {
                        output.append(line);
                        synchronized (timeStamp) {
                          timeStamp = System.currentTimeMillis();
                        }
                      }
                    } catch (IOException e) {
                      e.printStackTrace();
                    }
                  }
                })
            .start();

        new Thread(
                new Runnable() {
                  public void run() {
                    String line;
                    BufferedReader bufferedErrorReader =
                        new BufferedReader(new InputStreamReader(err));
                    try {
                      while ((line = bufferedErrorReader.readLine()) != null) {
                        error.append(line);
                        synchronized (timeStamp) {
                          timeStamp = System.currentTimeMillis();
                        }
                      }
                    } catch (IOException e) {
                      e.printStackTrace();
                    }
                  }
                })
            .start();

        while (!c.isClosed()) {
          synchronized (this.timeStamp) {
            if (System.currentTimeMillis() - this.timeStamp > MAXIMUM_WAITING_TIME_INACTIVITY) {
              log.warn("command execution seems inactive, canceling!");
              break;
            }
          }
          log.info("waiting for command to finish.");
          try {
            Thread.sleep(SshClient.DEFAULT_WAITING_TIME_PER_CYCLE);
          } catch (InterruptedException e) {
            e.printStackTrace();
          }
        }
        exitstatus = c.getExitStatus();

      } catch (JSchException e) {
        e.printStackTrace();
      } catch (IOException e) {
        e.printStackTrace();
      } finally {
        if (c != null) {
          c.disconnect();
        }

        if (ssh != null) {
          try {
            ssh.disconnectSession();
          } catch (JSchException e) {
            e.printStackTrace();
          }
        }
      }
      return exitstatus;
    }
Пример #11
0
  /**
   * Execute the command on the destination path and parse the output to return an integer
   *
   * @param command
   * @param path
   * @return Process PID or null if can't get it.
   * @throws RemoteAccessException if connection down
   */
  private Integer execute(String command, Path path) throws RemoteAccessException {
    log.debug(command);
    ChannelExec channel = null;
    StringBuilder sb = new StringBuilder();
    try {
      channel = channelManager.getExecChannel(path);
      // TODO: Decor with tee to write on standard err and out stream and
      // alse remote scratch file

      channel.setCommand(command);

      channel.setInputStream(null);
      channel.setErrStream(System.err);

      InputStream in = channel.getInputStream();

      channel.connect();

      // Read Pid
      byte[] tmp = new byte[1024];
      while (true) {
        while (in.available() > 0) {
          int i = in.read(tmp, 0, 1024);
          if (i < 0) {
            break;
          }
          sb.append(new String(tmp, 0, i));
        }
        if (channel.isClosed()) {

          break;
        }
        try {
          Thread.sleep(1000);
        } catch (Exception e) {
          log.error("Runtime error. Thread Interupted.", e);
          throw new RemoteAccessException("Thread interupted", e);
        }
      }
      if (channel.getExitStatus() < 0) {
        throw new RemoteAccessException("SSH connection close abruptly");
      }

    } catch (Exception e) {
      throw new RemoteAccessException("Unable to SSH connect. Command: " + command, e);
    } finally {
      try {
        if (channel != null) {
          channel.disconnect();
        }
      } catch (Exception e) {
        log.error("SSH disconnect error", e);
      }
    }
    // parse pid
    Integer pid = null;
    try {
      pid = Integer.valueOf(sb.toString().trim());
    } catch (NumberFormatException e) {
      log.warn("Unable to convert the command output to PID. Output =  " + sb.toString());
    }
    return pid;
  }